path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
app/javascript/mastodon/features/compose/components/character_counter.js
TheInventrix/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { length } from 'stringz'; export default class CharacterCounter extends React.PureComponent { static propTypes = { text: PropTypes.string.isRequired, max: PropTypes.number.isRequired, }; checkRemainingText (diff) { if (diff < 0) { return <span className='character-counter character-counter--over'>{diff}</span>; } return <span className='character-counter'>{diff}</span>; } render () { const diff = this.props.max - length(this.props.text); return this.checkRemainingText(diff); } }
src/components/Checkbox/Checkbox-story.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withKnobs, boolean, text } from '@storybook/addon-knobs'; import Checkbox from '../Checkbox'; import CheckboxSkeleton from '../Checkbox/Checkbox.Skeleton'; const props = () => ({ className: 'some-class', labelText: text('Label text (labelText)', 'Checkbox label'), indeterminate: boolean('Intermediate (indeterminate)', false), disabled: boolean('Disabled (disabled)', false), hideLabel: boolean('No label (hideLabel)', false), wrapperClassName: text('Wrapper CSS class name (wrapperClassName)', ''), onChange: action('onChange'), }); storiesOf('Checkbox', module) .addDecorator(withKnobs) .add( 'checked', () => { const checkboxProps = props(); return ( <fieldset className="bx--fieldset"> <legend className="bx--label">Checkbox heading</legend> <Checkbox defaultChecked {...checkboxProps} id="checkbox-label-1" /> <Checkbox defaultChecked {...checkboxProps} id="checkbox-label-2" /> </fieldset> ); }, { info: { text: ` Checkboxes are used when there is a list of options and the user may select multiple options, including all or none. The example below shows how the Checkbox component can be used as an uncontrolled component that is initially checked by setting the defaultChecked property to true. To use the component in a controlled way, you should set the checked property instead. `, }, } ) .add( 'unchecked', () => { const checkboxProps = props(); return ( <fieldset className="bx--fieldset"> <legend className="bx--label">Checkbox heading</legend> <Checkbox {...checkboxProps} id="checkbox-label-1" /> <Checkbox {...checkboxProps} id="checkbox-label-2" /> </fieldset> ); }, { info: { text: ` Checkboxes are used when there is a list of options and the user may select multiple options, including all or none. The example below shows how the Checkbox component can be used as an uncontrolled component that is initially unchecked. To use the component in a controlled way, you should set the checked property instead. `, }, } ) .add( 'skeleton', () => ( <div> <CheckboxSkeleton /> </div> ), { info: { text: ` Placeholder skeleton state to use when content is loading. `, }, } );
components/jsx/ListOfCheckboxes.js
Reynslan/moggo
var React = require('react'); var CheckboxWithLabel = require('./CheckboxWithLabel.js'); var Site = require('./Site.js'); module.exports = React.createClass({ render: function () { var items = {}; var i = 0; for (var category in this.props.retrievedCategoriesSettings) { var currentCategory = this.props.retrievedCategoriesSettings[category]; items['name-' + i++] = ( <li> <CheckboxWithLabel name={currentCategory.category + "_checkbox"} labelOn={currentCategory.name + Site.extensionText.appendToBlockedCategory} labelOff={currentCategory.name} currentSettings={currentCategory}/> </li> ); } return ( <ul> {items} </ul> ); } });
app/components/SearchEngine.js
JobCompare/jc-ui
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Action from '../../utils/wrappers/redux/Action'; import actionTypes from '../../utils/definitions/action_types/SearchEngineActionTypes'; import OverlayController from '../../utils/OverlayController'; import Overlay from './containers/Overlay'; /* * Sanity Checklist: * - ensure Overlay is appeared when input is focused. * - ensure that by clicking a wrapper div of input should make input be focused * - ensure that when search result shows up when two or more characters are present on input * - ensure characters present on input is reasonably similar as results being displayed * - ensure that no more than 5 results are shown given characters on input * - ensure that by clicking the overlay, overlay disappears, input is blurred, and result are hidden * - ensure that by pressing esc (either focusing on input or result) should have same behavior as above * - ensure that by pressing up and down arrow, user can navigate between input and results * - TODO: ensure that clicking or pressing enter on selected item in result, displays chip on input * - TODO: ensure first item in result is focused by default upon change characters on input */ export class SearchEngine extends React.Component { constructor({ placeholder, endpoint, className }) { super(); this.onClick = this.onClick.bind(this); this.onFocus = this.onFocus.bind(this); this.onOverlayClick = this.onOverlayClick.bind(this); this.onKeyUp = this.onKeyUp.bind(this); this.searchByName = this.searchByName.bind(this); this.attributes = { root: { className: `search-engine ${className || ''}`.trim(), onKeyUp: this.onKeyUp, }, input: { type: 'text', placeholder: placeholder || 'Search something', onFocus: this.onFocus, }, }; this.state = { isBlurred: true }; this.endpoint = endpoint || ''; } onClick(event) { event.preventDefault(); this.inputField.focus(); } onFocus(event) { event.preventDefault(); OverlayController.show(this.overlay.element); this.setState(prev => ({ isBlurred: false })); } onOverlayClick(event) { event.preventDefault(); this.setState(prev => ({ isBlurred: true })); } onKeyUp(event) { event.preventDefault(); const { activeElement } = document; const tabIndex = parseInt(activeElement.tabIndex); const results = [this.inputField, ...this.result.childNodes]; const size = results.length; const keyCode = event.keyCode || event.which; switch (keyCode) { case 27: { // ESC this.inputField.blur(); if (activeElement && results.indexOf(activeElement) !== -1) { results[tabIndex].blur(); } OverlayController.hide(this.overlay.element); this.setState(prev => ({ isBlurred: true })); break; } case 38: { // Up Arrow if (activeElement && results.indexOf(activeElement) !== -1) { results[tabIndex].blur(); } results[(size + (tabIndex - 1)) % size].focus(); break; } case 40: { // Down Arrow if (activeElement && results.indexOf(activeElement) !== -1) { results[tabIndex].blur(); } results[(tabIndex + 1) % size].focus(); break; } default: { this.searchByName(this.inputField.value.toLowerCase().trim()); } } } searchByName(keyword='') { const { SEARCH_BY_NAME } = actionTypes; this.props.dispatch(new Action(SEARCH_BY_NAME, { keyword, endpoint: this.endpoint })); } // TODO: svg may not work in certain browsers. think of alternatives render() { return ( <div {...this.attributes.root}> <Overlay ref={(element) => { this.overlay = element; }} onClick={this.onOverlayClick}/> <div className='search-engine-input overlay-content' onClick={this.onClick}> <svg width='20' height='20' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg'> <circle fill='none' strokeWidth='1.1' cx='9' cy='9' r='7'> </circle> <path fill='none' strokeWidth='1.1' d='M14,14 L18,18 L14,14 Z'> </path> </svg> <input ref={(element) => { this.inputField = element; }} {...this.attributes.input} /> </div> <ul className='search-result overlay-content' ref={(element) => { this.result = element; }}> {!this.state.isBlurred && this.props.result.map((item, i) => ( <li tabIndex={i+1}> <img src={item.logo} alt={`The image of ${item.name}`} /> <span className='search-result-name'>{item.name}</span> <span className='search-result-metadata'>{item.location.text}</span> </li> ))} </ul> </div> ); } } SearchEngine.propTypes = { result: PropTypes.array, dispatch: PropTypes.func, placeholder: PropTypes.string, endpoint: PropTypes.string, className: PropTypes.string, }; const mapStateToProps = store => ({ result: store.SearchEngineReducer }); export default connect(mapStateToProps)(SearchEngine);
ajax/libs/d3fc/10.0.0/d3fc.bundle.js
emmy41124/cdnjs
!function() { var d3 = { version: "3.5.17" }; var d3_arraySlice = [].slice, d3_array = function(list) { return d3_arraySlice.call(list); }; var d3_document = this.document; function d3_documentElement(node) { return node && (node.ownerDocument || node.document || node).documentElement; } function d3_window(node) { return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView); } if (d3_document) { try { d3_array(d3_document.documentElement.childNodes)[0].nodeType; } catch (e) { d3_array = function(list) { var i = list.length, array = new Array(i); while (i--) array[i] = list[i]; return array; }; } } if (!Date.now) Date.now = function() { return +new Date(); }; if (d3_document) { try { d3_document.createElement("DIV").style.setProperty("opacity", 0, ""); } catch (error) { var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; d3_element_prototype.setAttribute = function(name, value) { d3_element_setAttribute.call(this, name, value + ""); }; d3_element_prototype.setAttributeNS = function(space, local, value) { d3_element_setAttributeNS.call(this, space, local, value + ""); }; d3_style_prototype.setProperty = function(name, value, priority) { d3_style_setProperty.call(this, name, value + "", priority); }; } } d3.ascending = d3_ascending; function d3_ascending(a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; } d3.descending = function(a, b) { return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; }; d3.min = function(array, f) { var i = -1, n = array.length, a, b; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = b; break; } while (++i < n) if ((b = array[i]) != null && a > b) a = b; } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; } return a; }; d3.max = function(array, f) { var i = -1, n = array.length, a, b; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = b; break; } while (++i < n) if ((b = array[i]) != null && b > a) a = b; } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; } return a; }; d3.extent = function(array, f) { var i = -1, n = array.length, a, b, c; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = c = b; break; } while (++i < n) if ((b = array[i]) != null) { if (a > b) a = b; if (c < b) c = b; } } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = c = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null) { if (a > b) a = b; if (c < b) c = b; } } return [ a, c ]; }; function d3_number(x) { return x === null ? NaN : +x; } function d3_numeric(x) { return !isNaN(x); } d3.sum = function(array, f) { var s = 0, n = array.length, a, i = -1; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = +array[i])) s += a; } else { while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; } return s; }; d3.mean = function(array, f) { var s = 0, n = array.length, a, i = -1, j = n; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; } else { while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; } if (j) return s / j; }; d3.quantile = function(values, p) { var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; return e ? v + e * (values[h] - v) : v; }; d3.median = function(array, f) { var numbers = [], n = array.length, a, i = -1; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); } else { while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); } if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); }; d3.variance = function(array, f) { var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; if (arguments.length === 1) { while (++i < n) { if (d3_numeric(a = d3_number(array[i]))) { d = a - m; m += d / ++j; s += d * (a - m); } } } else { while (++i < n) { if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { d = a - m; m += d / ++j; s += d * (a - m); } } } if (j > 1) return s / (j - 1); }; d3.deviation = function() { var v = d3.variance.apply(this, arguments); return v ? Math.sqrt(v) : v; }; function d3_bisector(compare) { return { left: function(a, x, lo, hi) { if (arguments.length < 3) lo = 0; if (arguments.length < 4) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; } return lo; }, right: function(a, x, lo, hi) { if (arguments.length < 3) lo = 0; if (arguments.length < 4) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; } return lo; } }; } var d3_bisect = d3_bisector(d3_ascending); d3.bisectLeft = d3_bisect.left; d3.bisect = d3.bisectRight = d3_bisect.right; d3.bisector = function(f) { return d3_bisector(f.length === 1 ? function(d, x) { return d3_ascending(f(d), x); } : f); }; d3.shuffle = function(array, i0, i1) { if ((m = arguments.length) < 3) { i1 = array.length; if (m < 2) i0 = 0; } var m = i1 - i0, t, i; while (m) { i = Math.random() * m-- | 0; t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; } return array; }; d3.permute = function(array, indexes) { var i = indexes.length, permutes = new Array(i); while (i--) permutes[i] = array[indexes[i]]; return permutes; }; d3.pairs = function(array) { var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; return pairs; }; d3.transpose = function(matrix) { if (!(n = matrix.length)) return []; for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) { for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) { row[j] = matrix[j][i]; } } return transpose; }; function d3_transposeLength(d) { return d.length; } d3.zip = function() { return d3.transpose(arguments); }; d3.keys = function(map) { var keys = []; for (var key in map) keys.push(key); return keys; }; d3.values = function(map) { var values = []; for (var key in map) values.push(map[key]); return values; }; d3.entries = function(map) { var entries = []; for (var key in map) entries.push({ key: key, value: map[key] }); return entries; }; d3.merge = function(arrays) { var n = arrays.length, m, i = -1, j = 0, merged, array; while (++i < n) j += arrays[i].length; merged = new Array(j); while (--n >= 0) { array = arrays[n]; m = array.length; while (--m >= 0) { merged[--j] = array[m]; } } return merged; }; var abs = Math.abs; d3.range = function(start, stop, step) { if (arguments.length < 3) { step = 1; if (arguments.length < 2) { stop = start; start = 0; } } if ((stop - start) / step === Infinity) throw new Error("infinite range"); var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; start *= k, stop *= k, step *= k; if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); return range; }; function d3_range_integerScale(x) { var k = 1; while (x * k % 1) k *= 10; return k; } function d3_class(ctor, properties) { for (var key in properties) { Object.defineProperty(ctor.prototype, key, { value: properties[key], enumerable: false }); } } d3.map = function(object, f) { var map = new d3_Map(); if (object instanceof d3_Map) { object.forEach(function(key, value) { map.set(key, value); }); } else if (Array.isArray(object)) { var i = -1, n = object.length, o; if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); } else { for (var key in object) map.set(key, object[key]); } return map; }; function d3_Map() { this._ = Object.create(null); } var d3_map_proto = "__proto__", d3_map_zero = "\x00"; d3_class(d3_Map, { has: d3_map_has, get: function(key) { return this._[d3_map_escape(key)]; }, set: function(key, value) { return this._[d3_map_escape(key)] = value; }, remove: d3_map_remove, keys: d3_map_keys, values: function() { var values = []; for (var key in this._) values.push(this._[key]); return values; }, entries: function() { var entries = []; for (var key in this._) entries.push({ key: d3_map_unescape(key), value: this._[key] }); return entries; }, size: d3_map_size, empty: d3_map_empty, forEach: function(f) { for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); } }); function d3_map_escape(key) { return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; } function d3_map_unescape(key) { return (key += "")[0] === d3_map_zero ? key.slice(1) : key; } function d3_map_has(key) { return d3_map_escape(key) in this._; } function d3_map_remove(key) { return (key = d3_map_escape(key)) in this._ && delete this._[key]; } function d3_map_keys() { var keys = []; for (var key in this._) keys.push(d3_map_unescape(key)); return keys; } function d3_map_size() { var size = 0; for (var key in this._) ++size; return size; } function d3_map_empty() { for (var key in this._) return false; return true; } d3.nest = function() { var nest = {}, keys = [], sortKeys = [], sortValues, rollup; function map(mapType, array, depth) { if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; while (++i < n) { if (values = valuesByKey.get(keyValue = key(object = array[i]))) { values.push(object); } else { valuesByKey.set(keyValue, [ object ]); } } if (mapType) { object = mapType(); setter = function(keyValue, values) { object.set(keyValue, map(mapType, values, depth)); }; } else { object = {}; setter = function(keyValue, values) { object[keyValue] = map(mapType, values, depth); }; } valuesByKey.forEach(setter); return object; } function entries(map, depth) { if (depth >= keys.length) return map; var array = [], sortKey = sortKeys[depth++]; map.forEach(function(key, keyMap) { array.push({ key: key, values: entries(keyMap, depth) }); }); return sortKey ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array; } nest.map = function(array, mapType) { return map(mapType, array, 0); }; nest.entries = function(array) { return entries(map(d3.map, array, 0), 0); }; nest.key = function(d) { keys.push(d); return nest; }; nest.sortKeys = function(order) { sortKeys[keys.length - 1] = order; return nest; }; nest.sortValues = function(order) { sortValues = order; return nest; }; nest.rollup = function(f) { rollup = f; return nest; }; return nest; }; d3.set = function(array) { var set = new d3_Set(); if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); return set; }; function d3_Set() { this._ = Object.create(null); } d3_class(d3_Set, { has: d3_map_has, add: function(key) { this._[d3_map_escape(key += "")] = true; return key; }, remove: d3_map_remove, values: d3_map_keys, size: d3_map_size, empty: d3_map_empty, forEach: function(f) { for (var key in this._) f.call(this, d3_map_unescape(key)); } }); d3.behavior = {}; function d3_identity(d) { return d; } d3.rebind = function(target, source) { var i = 1, n = arguments.length, method; while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); return target; }; function d3_rebind(target, source, method) { return function() { var value = method.apply(source, arguments); return value === source ? target : value; }; } function d3_vendorSymbol(object, name) { if (name in object) return name; name = name.charAt(0).toUpperCase() + name.slice(1); for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { var prefixName = d3_vendorPrefixes[i] + name; if (prefixName in object) return prefixName; } } var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; function d3_noop() {} d3.dispatch = function() { var dispatch = new d3_dispatch(), i = -1, n = arguments.length; while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); return dispatch; }; function d3_dispatch() {} d3_dispatch.prototype.on = function(type, listener) { var i = type.indexOf("."), name = ""; if (i >= 0) { name = type.slice(i + 1); type = type.slice(0, i); } if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); if (arguments.length === 2) { if (listener == null) for (type in this) { if (this.hasOwnProperty(type)) this[type].on(name, null); } return this; } }; function d3_dispatch_event(dispatch) { var listeners = [], listenerByName = new d3_Map(); function event() { var z = listeners, i = -1, n = z.length, l; while (++i < n) if (l = z[i].on) l.apply(this, arguments); return dispatch; } event.on = function(name, listener) { var l = listenerByName.get(name), i; if (arguments.length < 2) return l && l.on; if (l) { l.on = null; listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); listenerByName.remove(name); } if (listener) listeners.push(listenerByName.set(name, { on: listener })); return dispatch; }; return event; } d3.event = null; function d3_eventPreventDefault() { d3.event.preventDefault(); } function d3_eventSource() { var e = d3.event, s; while (s = e.sourceEvent) e = s; return e; } function d3_eventDispatch(target) { var dispatch = new d3_dispatch(), i = 0, n = arguments.length; while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); dispatch.of = function(thiz, argumentz) { return function(e1) { try { var e0 = e1.sourceEvent = d3.event; e1.target = target; d3.event = e1; dispatch[e1.type].apply(thiz, argumentz); } finally { d3.event = e0; } }; }; return dispatch; } d3.requote = function(s) { return s.replace(d3_requote_re, "\\$&"); }; var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; var d3_subclass = {}.__proto__ ? function(object, prototype) { object.__proto__ = prototype; } : function(object, prototype) { for (var property in prototype) object[property] = prototype[property]; }; function d3_selection(groups) { d3_subclass(groups, d3_selectionPrototype); return groups; } var d3_select = function(s, n) { return n.querySelector(s); }, d3_selectAll = function(s, n) { return n.querySelectorAll(s); }, d3_selectMatches = function(n, s) { var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; d3_selectMatches = function(n, s) { return d3_selectMatcher.call(n, s); }; return d3_selectMatches(n, s); }; if (typeof Sizzle === "function") { d3_select = function(s, n) { return Sizzle(s, n)[0] || null; }; d3_selectAll = Sizzle; d3_selectMatches = Sizzle.matchesSelector; } d3.selection = function() { return d3.select(d3_document.documentElement); }; var d3_selectionPrototype = d3.selection.prototype = []; d3_selectionPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, group, node; selector = d3_selection_selector(selector); for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); subgroup.parentNode = (group = this[j]).parentNode; for (var i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroup.push(subnode = selector.call(node, node.__data__, i, j)); if (subnode && "__data__" in node) subnode.__data__ = node.__data__; } else { subgroup.push(null); } } } return d3_selection(subgroups); }; function d3_selection_selector(selector) { return typeof selector === "function" ? selector : function() { return d3_select(selector, this); }; } d3_selectionPrototype.selectAll = function(selector) { var subgroups = [], subgroup, node; selector = d3_selection_selectorAll(selector); for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); subgroup.parentNode = node; } } } return d3_selection(subgroups); }; function d3_selection_selectorAll(selector) { return typeof selector === "function" ? selector : function() { return d3_selectAll(selector, this); }; } var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; var d3_nsPrefix = { svg: "http://www.w3.org/2000/svg", xhtml: d3_nsXhtml, xlink: "http://www.w3.org/1999/xlink", xml: "http://www.w3.org/XML/1998/namespace", xmlns: "http://www.w3.org/2000/xmlns/" }; d3.ns = { prefix: d3_nsPrefix, qualify: function(name) { var i = name.indexOf(":"), prefix = name; if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); return d3_nsPrefix.hasOwnProperty(prefix) ? { space: d3_nsPrefix[prefix], local: name } : name; } }; d3_selectionPrototype.attr = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { var node = this.node(); name = d3.ns.qualify(name); return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); } for (value in name) this.each(d3_selection_attr(value, name[value])); return this; } return this.each(d3_selection_attr(name, value)); }; function d3_selection_attr(name, value) { name = d3.ns.qualify(name); function attrNull() { this.removeAttribute(name); } function attrNullNS() { this.removeAttributeNS(name.space, name.local); } function attrConstant() { this.setAttribute(name, value); } function attrConstantNS() { this.setAttributeNS(name.space, name.local, value); } function attrFunction() { var x = value.apply(this, arguments); if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); } function attrFunctionNS() { var x = value.apply(this, arguments); if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); } return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; } function d3_collapse(s) { return s.trim().replace(/\s+/g, " "); } d3_selectionPrototype.classed = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; if (value = node.classList) { while (++i < n) if (!value.contains(name[i])) return false; } else { value = node.getAttribute("class"); while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; } return true; } for (value in name) this.each(d3_selection_classed(value, name[value])); return this; } return this.each(d3_selection_classed(name, value)); }; function d3_selection_classedRe(name) { return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); } function d3_selection_classes(name) { return (name + "").trim().split(/^|\s+/); } function d3_selection_classed(name, value) { name = d3_selection_classes(name).map(d3_selection_classedName); var n = name.length; function classedConstant() { var i = -1; while (++i < n) name[i](this, value); } function classedFunction() { var i = -1, x = value.apply(this, arguments); while (++i < n) name[i](this, x); } return typeof value === "function" ? classedFunction : classedConstant; } function d3_selection_classedName(name) { var re = d3_selection_classedRe(name); return function(node, value) { if (c = node.classList) return value ? c.add(name) : c.remove(name); var c = node.getAttribute("class") || ""; if (value) { re.lastIndex = 0; if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); } else { node.setAttribute("class", d3_collapse(c.replace(re, " "))); } }; } d3_selectionPrototype.style = function(name, value, priority) { var n = arguments.length; if (n < 3) { if (typeof name !== "string") { if (n < 2) value = ""; for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); return this; } if (n < 2) { var node = this.node(); return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); } priority = ""; } return this.each(d3_selection_style(name, value, priority)); }; function d3_selection_style(name, value, priority) { function styleNull() { this.style.removeProperty(name); } function styleConstant() { this.style.setProperty(name, value, priority); } function styleFunction() { var x = value.apply(this, arguments); if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); } return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; } d3_selectionPrototype.property = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") return this.node()[name]; for (value in name) this.each(d3_selection_property(value, name[value])); return this; } return this.each(d3_selection_property(name, value)); }; function d3_selection_property(name, value) { function propertyNull() { delete this[name]; } function propertyConstant() { this[name] = value; } function propertyFunction() { var x = value.apply(this, arguments); if (x == null) delete this[name]; else this[name] = x; } return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; } d3_selectionPrototype.text = function(value) { return arguments.length ? this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.textContent = v == null ? "" : v; } : value == null ? function() { this.textContent = ""; } : function() { this.textContent = value; }) : this.node().textContent; }; d3_selectionPrototype.html = function(value) { return arguments.length ? this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.innerHTML = v == null ? "" : v; } : value == null ? function() { this.innerHTML = ""; } : function() { this.innerHTML = value; }) : this.node().innerHTML; }; d3_selectionPrototype.append = function(name) { name = d3_selection_creator(name); return this.select(function() { return this.appendChild(name.apply(this, arguments)); }); }; function d3_selection_creator(name) { function create() { var document = this.ownerDocument, namespace = this.namespaceURI; return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name); } function createNS() { return this.ownerDocument.createElementNS(name.space, name.local); } return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; } d3_selectionPrototype.insert = function(name, before) { name = d3_selection_creator(name); before = d3_selection_selector(before); return this.select(function() { return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); }); }; d3_selectionPrototype.remove = function() { return this.each(d3_selectionRemove); }; function d3_selectionRemove() { var parent = this.parentNode; if (parent) parent.removeChild(this); } d3_selectionPrototype.data = function(value, key) { var i = -1, n = this.length, group, node; if (!arguments.length) { value = new Array(n = (group = this[0]).length); while (++i < n) { if (node = group[i]) { value[i] = node.__data__; } } return value; } function bind(group, groupData) { var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; if (key) { var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; for (i = -1; ++i < n; ) { if (node = group[i]) { if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) { exitNodes[i] = node; } else { nodeByKeyValue.set(keyValue, node); } keyValues[i] = keyValue; } } for (i = -1; ++i < m; ) { if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { enterNodes[i] = d3_selection_dataNode(nodeData); } else if (node !== true) { updateNodes[i] = node; node.__data__ = nodeData; } nodeByKeyValue.set(keyValue, true); } for (i = -1; ++i < n; ) { if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) { exitNodes[i] = group[i]; } } } else { for (i = -1; ++i < n0; ) { node = group[i]; nodeData = groupData[i]; if (node) { node.__data__ = nodeData; updateNodes[i] = node; } else { enterNodes[i] = d3_selection_dataNode(nodeData); } } for (;i < m; ++i) { enterNodes[i] = d3_selection_dataNode(groupData[i]); } for (;i < n; ++i) { exitNodes[i] = group[i]; } } enterNodes.update = updateNodes; enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; enter.push(enterNodes); update.push(updateNodes); exit.push(exitNodes); } var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); if (typeof value === "function") { while (++i < n) { bind(group = this[i], value.call(group, group.parentNode.__data__, i)); } } else { while (++i < n) { bind(group = this[i], value); } } update.enter = function() { return enter; }; update.exit = function() { return exit; }; return update; }; function d3_selection_dataNode(data) { return { __data__: data }; } d3_selectionPrototype.datum = function(value) { return arguments.length ? this.property("__data__", value) : this.property("__data__"); }; d3_selectionPrototype.filter = function(filter) { var subgroups = [], subgroup, group, node; if (typeof filter !== "function") filter = d3_selection_filter(filter); for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); subgroup.parentNode = (group = this[j]).parentNode; for (var i = 0, n = group.length; i < n; i++) { if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { subgroup.push(node); } } } return d3_selection(subgroups); }; function d3_selection_filter(selector) { return function() { return d3_selectMatches(this, selector); }; } d3_selectionPrototype.order = function() { for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { if (node = group[i]) { if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); next = node; } } } return this; }; d3_selectionPrototype.sort = function(comparator) { comparator = d3_selection_sortComparator.apply(this, arguments); for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); return this.order(); }; function d3_selection_sortComparator(comparator) { if (!arguments.length) comparator = d3_ascending; return function(a, b) { return a && b ? comparator(a.__data__, b.__data__) : !a - !b; }; } d3_selectionPrototype.each = function(callback) { return d3_selection_each(this, function(node, i, j) { callback.call(node, node.__data__, i, j); }); }; function d3_selection_each(groups, callback) { for (var j = 0, m = groups.length; j < m; j++) { for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { if (node = group[i]) callback(node, i, j); } } return groups; } d3_selectionPrototype.call = function(callback) { var args = d3_array(arguments); callback.apply(args[0] = this, args); return this; }; d3_selectionPrototype.empty = function() { return !this.node(); }; d3_selectionPrototype.node = function() { for (var j = 0, m = this.length; j < m; j++) { for (var group = this[j], i = 0, n = group.length; i < n; i++) { var node = group[i]; if (node) return node; } } return null; }; d3_selectionPrototype.size = function() { var n = 0; d3_selection_each(this, function() { ++n; }); return n; }; function d3_selection_enter(selection) { d3_subclass(selection, d3_selection_enterPrototype); return selection; } var d3_selection_enterPrototype = []; d3.selection.enter = d3_selection_enter; d3.selection.enter.prototype = d3_selection_enterPrototype; d3_selection_enterPrototype.append = d3_selectionPrototype.append; d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; d3_selection_enterPrototype.node = d3_selectionPrototype.node; d3_selection_enterPrototype.call = d3_selectionPrototype.call; d3_selection_enterPrototype.size = d3_selectionPrototype.size; d3_selection_enterPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, upgroup, group, node; for (var j = -1, m = this.length; ++j < m; ) { upgroup = (group = this[j]).update; subgroups.push(subgroup = []); subgroup.parentNode = group.parentNode; for (var i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); subnode.__data__ = node.__data__; } else { subgroup.push(null); } } } return d3_selection(subgroups); }; d3_selection_enterPrototype.insert = function(name, before) { if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); return d3_selectionPrototype.insert.call(this, name, before); }; function d3_selection_enterInsertBefore(enter) { var i0, j0; return function(d, i, j) { var group = enter[j].update, n = group.length, node; if (j != j0) j0 = j, i0 = 0; if (i >= i0) i0 = i + 1; while (!(node = group[i0]) && ++i0 < n) ; return node; }; } d3.select = function(node) { var group; if (typeof node === "string") { group = [ d3_select(node, d3_document) ]; group.parentNode = d3_document.documentElement; } else { group = [ node ]; group.parentNode = d3_documentElement(node); } return d3_selection([ group ]); }; d3.selectAll = function(nodes) { var group; if (typeof nodes === "string") { group = d3_array(d3_selectAll(nodes, d3_document)); group.parentNode = d3_document.documentElement; } else { group = d3_array(nodes); group.parentNode = null; } return d3_selection([ group ]); }; d3_selectionPrototype.on = function(type, listener, capture) { var n = arguments.length; if (n < 3) { if (typeof type !== "string") { if (n < 2) listener = false; for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); return this; } if (n < 2) return (n = this.node()["__on" + type]) && n._; capture = false; } return this.each(d3_selection_on(type, listener, capture)); }; function d3_selection_on(type, listener, capture) { var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; if (i > 0) type = type.slice(0, i); var filter = d3_selection_onFilters.get(type); if (filter) type = filter, wrap = d3_selection_onFilter; function onRemove() { var l = this[name]; if (l) { this.removeEventListener(type, l, l.$); delete this[name]; } } function onAdd() { var l = wrap(listener, d3_array(arguments)); onRemove.call(this); this.addEventListener(type, this[name] = l, l.$ = capture); l._ = listener; } function removeAll() { var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; for (var name in this) { if (match = name.match(re)) { var l = this[name]; this.removeEventListener(match[1], l, l.$); delete this[name]; } } } return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; } var d3_selection_onFilters = d3.map({ mouseenter: "mouseover", mouseleave: "mouseout" }); if (d3_document) { d3_selection_onFilters.forEach(function(k) { if ("on" + k in d3_document) d3_selection_onFilters.remove(k); }); } function d3_selection_onListener(listener, argumentz) { return function(e) { var o = d3.event; d3.event = e; argumentz[0] = this.__data__; try { listener.apply(this, argumentz); } finally { d3.event = o; } }; } function d3_selection_onFilter(listener, argumentz) { var l = d3_selection_onListener(listener, argumentz); return function(e) { var target = this, related = e.relatedTarget; if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { l.call(target, e); } }; } var d3_event_dragSelect, d3_event_dragId = 0; function d3_event_dragSuppress(node) { var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); if (d3_event_dragSelect == null) { d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); } if (d3_event_dragSelect) { var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; style[d3_event_dragSelect] = "none"; } return function(suppressClick) { w.on(name, null); if (d3_event_dragSelect) style[d3_event_dragSelect] = select; if (suppressClick) { var off = function() { w.on(click, null); }; w.on(click, function() { d3_eventPreventDefault(); off(); }, true); setTimeout(off, 0); } }; } d3.mouse = function(container) { return d3_mousePoint(container, d3_eventSource()); }; var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; function d3_mousePoint(container, e) { if (e.changedTouches) e = e.changedTouches[0]; var svg = container.ownerSVGElement || container; if (svg.createSVGPoint) { var point = svg.createSVGPoint(); if (d3_mouse_bug44083 < 0) { var window = d3_window(container); if (window.scrollX || window.scrollY) { svg = d3.select("body").append("svg").style({ position: "absolute", top: 0, left: 0, margin: 0, padding: 0, border: "none" }, "important"); var ctm = svg[0][0].getScreenCTM(); d3_mouse_bug44083 = !(ctm.f || ctm.e); svg.remove(); } } if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, point.y = e.clientY; point = point.matrixTransform(container.getScreenCTM().inverse()); return [ point.x, point.y ]; } var rect = container.getBoundingClientRect(); return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; } d3.touch = function(container, touches, identifier) { if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { if ((touch = touches[i]).identifier === identifier) { return d3_mousePoint(container, touch); } } }; d3.behavior.drag = function() { var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); function drag() { this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); } function dragstart(id, position, subject, move, end) { return function() { var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); if (origin) { dragOffset = origin.apply(that, arguments); dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; } else { dragOffset = [ 0, 0 ]; } dispatch({ type: "dragstart" }); function moved() { var position1 = position(parent, dragId), dx, dy; if (!position1) return; dx = position1[0] - position0[0]; dy = position1[1] - position0[1]; dragged |= dx | dy; position0 = position1; dispatch({ type: "drag", x: position1[0] + dragOffset[0], y: position1[1] + dragOffset[1], dx: dx, dy: dy }); } function ended() { if (!position(parent, dragId)) return; dragSubject.on(move + dragName, null).on(end + dragName, null); dragRestore(dragged); dispatch({ type: "dragend" }); } }; } drag.origin = function(x) { if (!arguments.length) return origin; origin = x; return drag; }; return d3.rebind(drag, event, "on"); }; function d3_behavior_dragTouchId() { return d3.event.changedTouches[0].identifier; } d3.touches = function(container, touches) { if (arguments.length < 2) touches = d3_eventSource().touches; return touches ? d3_array(touches).map(function(touch) { var point = d3_mousePoint(container, touch); point.identifier = touch.identifier; return point; }) : []; }; var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; function d3_sgn(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } function d3_cross2d(a, b, c) { return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); } function d3_acos(x) { return x > 1 ? 0 : x < -1 ? π : Math.acos(x); } function d3_asin(x) { return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); } function d3_sinh(x) { return ((x = Math.exp(x)) - 1 / x) / 2; } function d3_cosh(x) { return ((x = Math.exp(x)) + 1 / x) / 2; } function d3_tanh(x) { return ((x = Math.exp(2 * x)) - 1) / (x + 1); } function d3_haversin(x) { return (x = Math.sin(x / 2)) * x; } var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; d3.interpolateZoom = function(p0, p1) { var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; if (d2 < ε2) { S = Math.log(w1 / w0) / ρ; i = function(t) { return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ]; }; } else { var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); S = (r1 - r0) / ρ; i = function(t) { var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; }; } i.duration = S * 1e3; return i; }; d3.behavior.zoom = function() { var view = { x: 0, y: 0, k: 1 }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; if (!d3_behavior_zoomWheel) { d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { return d3.event.wheelDelta; }, "mousewheel") : (d3_behavior_zoomDelta = function() { return -d3.event.detail; }, "MozMousePixelScroll"); } function zoom(g) { g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); } zoom.event = function(g) { g.each(function() { var dispatch = event.of(this, arguments), view1 = view; if (d3_transitionInheritId) { d3.select(this).transition().each("start.zoom", function() { view = this.__chart__ || { x: 0, y: 0, k: 1 }; zoomstarted(dispatch); }).tween("zoom:zoom", function() { var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); return function(t) { var l = i(t), k = dx / l[2]; this.__chart__ = view = { x: cx - l[0] * k, y: cy - l[1] * k, k: k }; zoomed(dispatch); }; }).each("interrupt.zoom", function() { zoomended(dispatch); }).each("end.zoom", function() { zoomended(dispatch); }); } else { this.__chart__ = view; zoomstarted(dispatch); zoomed(dispatch); zoomended(dispatch); } }); }; zoom.translate = function(_) { if (!arguments.length) return [ view.x, view.y ]; view = { x: +_[0], y: +_[1], k: view.k }; rescale(); return zoom; }; zoom.scale = function(_) { if (!arguments.length) return view.k; view = { x: view.x, y: view.y, k: null }; scaleTo(+_); rescale(); return zoom; }; zoom.scaleExtent = function(_) { if (!arguments.length) return scaleExtent; scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; return zoom; }; zoom.center = function(_) { if (!arguments.length) return center; center = _ && [ +_[0], +_[1] ]; return zoom; }; zoom.size = function(_) { if (!arguments.length) return size; size = _ && [ +_[0], +_[1] ]; return zoom; }; zoom.duration = function(_) { if (!arguments.length) return duration; duration = +_; return zoom; }; zoom.x = function(z) { if (!arguments.length) return x1; x1 = z; x0 = z.copy(); view = { x: 0, y: 0, k: 1 }; return zoom; }; zoom.y = function(z) { if (!arguments.length) return y1; y1 = z; y0 = z.copy(); view = { x: 0, y: 0, k: 1 }; return zoom; }; function location(p) { return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; } function point(l) { return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; } function scaleTo(s) { view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); } function translateTo(p, l) { l = point(l); view.x += p[0] - l[0]; view.y += p[1] - l[1]; } function zoomTo(that, p, l, k) { that.__chart__ = { x: view.x, y: view.y, k: view.k }; scaleTo(Math.pow(2, k)); translateTo(center0 = p, l); that = d3.select(that); if (duration > 0) that = that.transition().duration(duration); that.call(zoom.event); } function rescale() { if (x1) x1.domain(x0.range().map(function(x) { return (x - view.x) / view.k; }).map(x0.invert)); if (y1) y1.domain(y0.range().map(function(y) { return (y - view.y) / view.k; }).map(y0.invert)); } function zoomstarted(dispatch) { if (!zooming++) dispatch({ type: "zoomstart" }); } function zoomed(dispatch) { rescale(); dispatch({ type: "zoom", scale: view.k, translate: [ view.x, view.y ] }); } function zoomended(dispatch) { if (!--zooming) dispatch({ type: "zoomend" }), center0 = null; } function mousedowned() { var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); d3_selection_interrupt.call(that); zoomstarted(dispatch); function moved() { dragged = 1; translateTo(d3.mouse(that), location0); zoomed(dispatch); } function ended() { subject.on(mousemove, null).on(mouseup, null); dragRestore(dragged); zoomended(dispatch); } } function touchstarted() { var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); started(); zoomstarted(dispatch); subject.on(mousedown, null).on(touchstart, started); function relocate() { var touches = d3.touches(that); scale0 = view.k; touches.forEach(function(t) { if (t.identifier in locations0) locations0[t.identifier] = location(t); }); return touches; } function started() { var target = d3.event.target; d3.select(target).on(touchmove, moved).on(touchend, ended); targets.push(target); var changed = d3.event.changedTouches; for (var i = 0, n = changed.length; i < n; ++i) { locations0[changed[i].identifier] = null; } var touches = relocate(), now = Date.now(); if (touches.length === 1) { if (now - touchtime < 500) { var p = touches[0]; zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); d3_eventPreventDefault(); } touchtime = now; } else if (touches.length > 1) { var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; distance0 = dx * dx + dy * dy; } } function moved() { var touches = d3.touches(that), p0, l0, p1, l1; d3_selection_interrupt.call(that); for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { p1 = touches[i]; if (l1 = locations0[p1.identifier]) { if (l0) break; p0 = p1, l0 = l1; } } if (l1) { var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; scaleTo(scale1 * scale0); } touchtime = null; translateTo(p0, l0); zoomed(dispatch); } function ended() { if (d3.event.touches.length) { var changed = d3.event.changedTouches; for (var i = 0, n = changed.length; i < n; ++i) { delete locations0[changed[i].identifier]; } for (var identifier in locations0) { return void relocate(); } } d3.selectAll(targets).on(zoomName, null); subject.on(mousedown, mousedowned).on(touchstart, touchstarted); dragRestore(); zoomended(dispatch); } } function mousewheeled() { var dispatch = event.of(this, arguments); if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch); mousewheelTimer = setTimeout(function() { mousewheelTimer = null; zoomended(dispatch); }, 50); d3_eventPreventDefault(); scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); translateTo(center0, translate0); zoomed(dispatch); } function dblclicked() { var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); } return d3.rebind(zoom, event, "on"); }; var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; d3.color = d3_color; function d3_color() {} d3_color.prototype.toString = function() { return this.rgb() + ""; }; d3.hsl = d3_hsl; function d3_hsl(h, s, l) { return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); } var d3_hslPrototype = d3_hsl.prototype = new d3_color(); d3_hslPrototype.brighter = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_hsl(this.h, this.s, this.l / k); }; d3_hslPrototype.darker = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_hsl(this.h, this.s, k * this.l); }; d3_hslPrototype.rgb = function() { return d3_hsl_rgb(this.h, this.s, this.l); }; function d3_hsl_rgb(h, s, l) { var m1, m2; h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; l = l < 0 ? 0 : l > 1 ? 1 : l; m2 = l <= .5 ? l * (1 + s) : l + s - l * s; m1 = 2 * l - m2; function v(h) { if (h > 360) h -= 360; else if (h < 0) h += 360; if (h < 60) return m1 + (m2 - m1) * h / 60; if (h < 180) return m2; if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; return m1; } function vv(h) { return Math.round(v(h) * 255); } return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); } d3.hcl = d3_hcl; function d3_hcl(h, c, l) { return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); } var d3_hclPrototype = d3_hcl.prototype = new d3_color(); d3_hclPrototype.brighter = function(k) { return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); }; d3_hclPrototype.darker = function(k) { return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); }; d3_hclPrototype.rgb = function() { return d3_hcl_lab(this.h, this.c, this.l).rgb(); }; function d3_hcl_lab(h, c, l) { if (isNaN(h)) h = 0; if (isNaN(c)) c = 0; return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); } d3.lab = d3_lab; function d3_lab(l, a, b) { return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); } var d3_lab_K = 18; var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; var d3_labPrototype = d3_lab.prototype = new d3_color(); d3_labPrototype.brighter = function(k) { return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); }; d3_labPrototype.darker = function(k) { return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); }; d3_labPrototype.rgb = function() { return d3_lab_rgb(this.l, this.a, this.b); }; function d3_lab_rgb(l, a, b) { var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; x = d3_lab_xyz(x) * d3_lab_X; y = d3_lab_xyz(y) * d3_lab_Y; z = d3_lab_xyz(z) * d3_lab_Z; return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); } function d3_lab_hcl(l, a, b) { return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); } function d3_lab_xyz(x) { return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; } function d3_xyz_lab(x) { return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; } function d3_xyz_rgb(r) { return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); } d3.rgb = d3_rgb; function d3_rgb(r, g, b) { return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); } function d3_rgbNumber(value) { return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); } function d3_rgbString(value) { return d3_rgbNumber(value) + ""; } var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); d3_rgbPrototype.brighter = function(k) { k = Math.pow(.7, arguments.length ? k : 1); var r = this.r, g = this.g, b = this.b, i = 30; if (!r && !g && !b) return new d3_rgb(i, i, i); if (r && r < i) r = i; if (g && g < i) g = i; if (b && b < i) b = i; return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); }; d3_rgbPrototype.darker = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_rgb(k * this.r, k * this.g, k * this.b); }; d3_rgbPrototype.hsl = function() { return d3_rgb_hsl(this.r, this.g, this.b); }; d3_rgbPrototype.toString = function() { return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); }; function d3_rgb_hex(v) { return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); } function d3_rgb_parse(format, rgb, hsl) { var r = 0, g = 0, b = 0, m1, m2, color; m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase()); if (m1) { m2 = m1[2].split(","); switch (m1[1]) { case "hsl": { return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); } case "rgb": { return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); } } } if (color = d3_rgb_names.get(format)) { return rgb(color.r, color.g, color.b); } if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { if (format.length === 4) { r = (color & 3840) >> 4; r = r >> 4 | r; g = color & 240; g = g >> 4 | g; b = color & 15; b = b << 4 | b; } else if (format.length === 7) { r = (color & 16711680) >> 16; g = (color & 65280) >> 8; b = color & 255; } } return rgb(r, g, b); } function d3_rgb_hsl(r, g, b) { var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; if (d) { s = l < .5 ? d / (max + min) : d / (2 - max - min); if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; h *= 60; } else { h = NaN; s = l > 0 && l < 1 ? 0 : h; } return new d3_hsl(h, s, l); } function d3_rgb_lab(r, g, b) { r = d3_rgb_xyz(r); g = d3_rgb_xyz(g); b = d3_rgb_xyz(b); var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); } function d3_rgb_xyz(r) { return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); } function d3_rgb_parseNumber(c) { var f = parseFloat(c); return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; } var d3_rgb_names = d3.map({ aliceblue: 15792383, antiquewhite: 16444375, aqua: 65535, aquamarine: 8388564, azure: 15794175, beige: 16119260, bisque: 16770244, black: 0, blanchedalmond: 16772045, blue: 255, blueviolet: 9055202, brown: 10824234, burlywood: 14596231, cadetblue: 6266528, chartreuse: 8388352, chocolate: 13789470, coral: 16744272, cornflowerblue: 6591981, cornsilk: 16775388, crimson: 14423100, cyan: 65535, darkblue: 139, darkcyan: 35723, darkgoldenrod: 12092939, darkgray: 11119017, darkgreen: 25600, darkgrey: 11119017, darkkhaki: 12433259, darkmagenta: 9109643, darkolivegreen: 5597999, darkorange: 16747520, darkorchid: 10040012, darkred: 9109504, darksalmon: 15308410, darkseagreen: 9419919, darkslateblue: 4734347, darkslategray: 3100495, darkslategrey: 3100495, darkturquoise: 52945, darkviolet: 9699539, deeppink: 16716947, deepskyblue: 49151, dimgray: 6908265, dimgrey: 6908265, dodgerblue: 2003199, firebrick: 11674146, floralwhite: 16775920, forestgreen: 2263842, fuchsia: 16711935, gainsboro: 14474460, ghostwhite: 16316671, gold: 16766720, goldenrod: 14329120, gray: 8421504, green: 32768, greenyellow: 11403055, grey: 8421504, honeydew: 15794160, hotpink: 16738740, indianred: 13458524, indigo: 4915330, ivory: 16777200, khaki: 15787660, lavender: 15132410, lavenderblush: 16773365, lawngreen: 8190976, lemonchiffon: 16775885, lightblue: 11393254, lightcoral: 15761536, lightcyan: 14745599, lightgoldenrodyellow: 16448210, lightgray: 13882323, lightgreen: 9498256, lightgrey: 13882323, lightpink: 16758465, lightsalmon: 16752762, lightseagreen: 2142890, lightskyblue: 8900346, lightslategray: 7833753, lightslategrey: 7833753, lightsteelblue: 11584734, lightyellow: 16777184, lime: 65280, limegreen: 3329330, linen: 16445670, magenta: 16711935, maroon: 8388608, mediumaquamarine: 6737322, mediumblue: 205, mediumorchid: 12211667, mediumpurple: 9662683, mediumseagreen: 3978097, mediumslateblue: 8087790, mediumspringgreen: 64154, mediumturquoise: 4772300, mediumvioletred: 13047173, midnightblue: 1644912, mintcream: 16121850, mistyrose: 16770273, moccasin: 16770229, navajowhite: 16768685, navy: 128, oldlace: 16643558, olive: 8421376, olivedrab: 7048739, orange: 16753920, orangered: 16729344, orchid: 14315734, palegoldenrod: 15657130, palegreen: 10025880, paleturquoise: 11529966, palevioletred: 14381203, papayawhip: 16773077, peachpuff: 16767673, peru: 13468991, pink: 16761035, plum: 14524637, powderblue: 11591910, purple: 8388736, rebeccapurple: 6697881, red: 16711680, rosybrown: 12357519, royalblue: 4286945, saddlebrown: 9127187, salmon: 16416882, sandybrown: 16032864, seagreen: 3050327, seashell: 16774638, sienna: 10506797, silver: 12632256, skyblue: 8900331, slateblue: 6970061, slategray: 7372944, slategrey: 7372944, snow: 16775930, springgreen: 65407, steelblue: 4620980, tan: 13808780, teal: 32896, thistle: 14204888, tomato: 16737095, turquoise: 4251856, violet: 15631086, wheat: 16113331, white: 16777215, whitesmoke: 16119285, yellow: 16776960, yellowgreen: 10145074 }); d3_rgb_names.forEach(function(key, value) { d3_rgb_names.set(key, d3_rgbNumber(value)); }); function d3_functor(v) { return typeof v === "function" ? v : function() { return v; }; } d3.functor = d3_functor; d3.xhr = d3_xhrType(d3_identity); function d3_xhrType(response) { return function(url, mimeType, callback) { if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, mimeType = null; return d3_xhr(url, mimeType, response, callback); }; } function d3_xhr(url, mimeType, response, callback) { var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { request.readyState > 3 && respond(); }; function respond() { var status = request.status, result; if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { try { result = response.call(xhr, request); } catch (e) { dispatch.error.call(xhr, e); return; } dispatch.load.call(xhr, result); } else { dispatch.error.call(xhr, request); } } request.onprogress = function(event) { var o = d3.event; d3.event = event; try { dispatch.progress.call(xhr, request); } finally { d3.event = o; } }; xhr.header = function(name, value) { name = (name + "").toLowerCase(); if (arguments.length < 2) return headers[name]; if (value == null) delete headers[name]; else headers[name] = value + ""; return xhr; }; xhr.mimeType = function(value) { if (!arguments.length) return mimeType; mimeType = value == null ? null : value + ""; return xhr; }; xhr.responseType = function(value) { if (!arguments.length) return responseType; responseType = value; return xhr; }; xhr.response = function(value) { response = value; return xhr; }; [ "get", "post" ].forEach(function(method) { xhr[method] = function() { return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); }; }); xhr.send = function(method, data, callback) { if (arguments.length === 2 && typeof data === "function") callback = data, data = null; request.open(method, url, true); if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); if (responseType != null) request.responseType = responseType; if (callback != null) xhr.on("error", callback).on("load", function(request) { callback(null, request); }); dispatch.beforesend.call(xhr, request); request.send(data == null ? null : data); return xhr; }; xhr.abort = function() { request.abort(); return xhr; }; d3.rebind(xhr, dispatch, "on"); return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); } function d3_xhr_fixCallback(callback) { return callback.length === 1 ? function(error, request) { callback(error == null ? request : null); } : callback; } function d3_xhrHasResponse(request) { var type = request.responseType; return type && type !== "text" ? request.response : request.responseText; } d3.dsv = function(delimiter, mimeType) { var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); function dsv(url, row, callback) { if (arguments.length < 3) callback = row, row = null; var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); xhr.row = function(_) { return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; }; return xhr; } function response(request) { return dsv.parse(request.responseText); } function typedResponse(f) { return function(request) { return dsv.parse(request.responseText, f); }; } dsv.parse = function(text, f) { var o; return dsv.parseRows(text, function(row, i) { if (o) return o(row, i - 1); var a = new Function("d", "return {" + row.map(function(name, i) { return JSON.stringify(name) + ": d[" + i + "]"; }).join(",") + "}"); o = f ? function(row, i) { return f(a(row), i); } : a; }); }; dsv.parseRows = function(text, f) { var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; function token() { if (I >= N) return EOF; if (eol) return eol = false, EOL; var j = I; if (text.charCodeAt(j) === 34) { var i = j; while (i++ < N) { if (text.charCodeAt(i) === 34) { if (text.charCodeAt(i + 1) !== 34) break; ++i; } } I = i + 2; var c = text.charCodeAt(i + 1); if (c === 13) { eol = true; if (text.charCodeAt(i + 2) === 10) ++I; } else if (c === 10) { eol = true; } return text.slice(j + 1, i).replace(/""/g, '"'); } while (I < N) { var c = text.charCodeAt(I++), k = 1; if (c === 10) eol = true; else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } else if (c !== delimiterCode) continue; return text.slice(j, I - k); } return text.slice(j); } while ((t = token()) !== EOF) { var a = []; while (t !== EOL && t !== EOF) { a.push(t); t = token(); } if (f && (a = f(a, n++)) == null) continue; rows.push(a); } return rows; }; dsv.format = function(rows) { if (Array.isArray(rows[0])) return dsv.formatRows(rows); var fieldSet = new d3_Set(), fields = []; rows.forEach(function(row) { for (var field in row) { if (!fieldSet.has(field)) { fields.push(fieldSet.add(field)); } } }); return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { return fields.map(function(field) { return formatValue(row[field]); }).join(delimiter); })).join("\n"); }; dsv.formatRows = function(rows) { return rows.map(formatRow).join("\n"); }; function formatRow(row) { return row.map(formatValue).join(delimiter); } function formatValue(text) { return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; } return dsv; }; d3.csv = d3.dsv(",", "text/csv"); d3.tsv = d3.dsv(" ", "text/tab-separated-values"); var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { setTimeout(callback, 17); }; d3.timer = function() { d3_timer.apply(this, arguments); }; function d3_timer(callback, delay, then) { var n = arguments.length; if (n < 2) delay = 0; if (n < 3) then = Date.now(); var time = then + delay, timer = { c: callback, t: time, n: null }; if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; d3_timer_queueTail = timer; if (!d3_timer_interval) { d3_timer_timeout = clearTimeout(d3_timer_timeout); d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } return timer; } function d3_timer_step() { var now = d3_timer_mark(), delay = d3_timer_sweep() - now; if (delay > 24) { if (isFinite(delay)) { clearTimeout(d3_timer_timeout); d3_timer_timeout = setTimeout(d3_timer_step, delay); } d3_timer_interval = 0; } else { d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } } d3.timer.flush = function() { d3_timer_mark(); d3_timer_sweep(); }; function d3_timer_mark() { var now = Date.now(), timer = d3_timer_queueHead; while (timer) { if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; timer = timer.n; } return now; } function d3_timer_sweep() { var t0, t1 = d3_timer_queueHead, time = Infinity; while (t1) { if (t1.c) { if (t1.t < time) time = t1.t; t1 = (t0 = t1).n; } else { t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; } } d3_timer_queueTail = t0; return time; } function d3_format_precision(x, p) { return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); } d3.round = function(x, n) { return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); }; var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); d3.formatPrefix = function(value, precision) { var i = 0; if (value = +value) { if (value < 0) value *= -1; if (precision) value = d3.round(value, d3_format_precision(value, precision)); i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); } return d3_formatPrefixes[8 + i / 3]; }; function d3_formatPrefix(d, i) { var k = Math.pow(10, abs(8 - i) * 3); return { scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; }, symbol: d }; } function d3_locale_numberFormat(locale) { var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; while (i > 0 && g > 0) { if (length + g + 1 > width) g = Math.max(1, width - length); t.push(value.substring(i -= g, i + g)); if ((length += g + 1) > width) break; g = locale_grouping[j = (j + 1) % locale_grouping.length]; } return t.reverse().join(locale_thousands); } : d3_identity; return function(specifier) { var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; if (precision) precision = +precision.substring(1); if (zfill || fill === "0" && align === "=") { zfill = fill = "0"; align = "="; } switch (type) { case "n": comma = true; type = "g"; break; case "%": scale = 100; suffix = "%"; type = "f"; break; case "p": scale = 100; suffix = "%"; type = "r"; break; case "b": case "o": case "x": case "X": if (symbol === "#") prefix = "0" + type.toLowerCase(); case "c": exponent = false; case "d": integer = true; precision = 0; break; case "s": scale = -1; type = "r"; break; } if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; if (type == "r" && !precision) type = "g"; if (precision != null) { if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); } type = d3_format_types.get(type) || d3_format_typeDefault; var zcomma = zfill && comma; return function(value) { var fullSuffix = suffix; if (integer && value % 1) return ""; var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; if (scale < 0) { var unit = d3.formatPrefix(value, precision); value = unit.scale(value); fullSuffix = unit.symbol + suffix; } else { value *= scale; } value = type(value, precision); var i = value.lastIndexOf("."), before, after; if (i < 0) { var j = exponent ? value.lastIndexOf("e") : -1; if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); } else { before = value.substring(0, i); after = locale_decimal + value.substring(i + 1); } if (!zfill && comma) before = formatGroup(before, Infinity); var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); negative += prefix; value = before + after; return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; }; }; } var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; var d3_format_types = d3.map({ b: function(x) { return x.toString(2); }, c: function(x) { return String.fromCharCode(x); }, o: function(x) { return x.toString(8); }, x: function(x) { return x.toString(16); }, X: function(x) { return x.toString(16).toUpperCase(); }, g: function(x, p) { return x.toPrecision(p); }, e: function(x, p) { return x.toExponential(p); }, f: function(x, p) { return x.toFixed(p); }, r: function(x, p) { return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); } }); function d3_format_typeDefault(x) { return x + ""; } var d3_time = d3.time = {}, d3_date = Date; function d3_date_utc() { this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); } d3_date_utc.prototype = { getDate: function() { return this._.getUTCDate(); }, getDay: function() { return this._.getUTCDay(); }, getFullYear: function() { return this._.getUTCFullYear(); }, getHours: function() { return this._.getUTCHours(); }, getMilliseconds: function() { return this._.getUTCMilliseconds(); }, getMinutes: function() { return this._.getUTCMinutes(); }, getMonth: function() { return this._.getUTCMonth(); }, getSeconds: function() { return this._.getUTCSeconds(); }, getTime: function() { return this._.getTime(); }, getTimezoneOffset: function() { return 0; }, valueOf: function() { return this._.valueOf(); }, setDate: function() { d3_time_prototype.setUTCDate.apply(this._, arguments); }, setDay: function() { d3_time_prototype.setUTCDay.apply(this._, arguments); }, setFullYear: function() { d3_time_prototype.setUTCFullYear.apply(this._, arguments); }, setHours: function() { d3_time_prototype.setUTCHours.apply(this._, arguments); }, setMilliseconds: function() { d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); }, setMinutes: function() { d3_time_prototype.setUTCMinutes.apply(this._, arguments); }, setMonth: function() { d3_time_prototype.setUTCMonth.apply(this._, arguments); }, setSeconds: function() { d3_time_prototype.setUTCSeconds.apply(this._, arguments); }, setTime: function() { d3_time_prototype.setTime.apply(this._, arguments); } }; var d3_time_prototype = Date.prototype; function d3_time_interval(local, step, number) { function round(date) { var d0 = local(date), d1 = offset(d0, 1); return date - d0 < d1 - date ? d0 : d1; } function ceil(date) { step(date = local(new d3_date(date - 1)), 1); return date; } function offset(date, k) { step(date = new d3_date(+date), k); return date; } function range(t0, t1, dt) { var time = ceil(t0), times = []; if (dt > 1) { while (time < t1) { if (!(number(time) % dt)) times.push(new Date(+time)); step(time, 1); } } else { while (time < t1) times.push(new Date(+time)), step(time, 1); } return times; } function range_utc(t0, t1, dt) { try { d3_date = d3_date_utc; var utc = new d3_date_utc(); utc._ = t0; return range(utc, t1, dt); } finally { d3_date = Date; } } local.floor = local; local.round = round; local.ceil = ceil; local.offset = offset; local.range = range; var utc = local.utc = d3_time_interval_utc(local); utc.floor = utc; utc.round = d3_time_interval_utc(round); utc.ceil = d3_time_interval_utc(ceil); utc.offset = d3_time_interval_utc(offset); utc.range = range_utc; return local; } function d3_time_interval_utc(method) { return function(date, k) { try { d3_date = d3_date_utc; var utc = new d3_date_utc(); utc._ = date; return method(utc, k)._; } finally { d3_date = Date; } }; } d3_time.year = d3_time_interval(function(date) { date = d3_time.day(date); date.setMonth(0, 1); return date; }, function(date, offset) { date.setFullYear(date.getFullYear() + offset); }, function(date) { return date.getFullYear(); }); d3_time.years = d3_time.year.range; d3_time.years.utc = d3_time.year.utc.range; d3_time.day = d3_time_interval(function(date) { var day = new d3_date(2e3, 0); day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); return day; }, function(date, offset) { date.setDate(date.getDate() + offset); }, function(date) { return date.getDate() - 1; }); d3_time.days = d3_time.day.range; d3_time.days.utc = d3_time.day.utc.range; d3_time.dayOfYear = function(date) { var year = d3_time.year(date); return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); }; [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { i = 7 - i; var interval = d3_time[day] = d3_time_interval(function(date) { (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); return date; }, function(date, offset) { date.setDate(date.getDate() + Math.floor(offset) * 7); }, function(date) { var day = d3_time.year(date).getDay(); return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); }); d3_time[day + "s"] = interval.range; d3_time[day + "s"].utc = interval.utc.range; d3_time[day + "OfYear"] = function(date) { var day = d3_time.year(date).getDay(); return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); }; }); d3_time.week = d3_time.sunday; d3_time.weeks = d3_time.sunday.range; d3_time.weeks.utc = d3_time.sunday.utc.range; d3_time.weekOfYear = d3_time.sundayOfYear; function d3_locale_timeFormat(locale) { var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; function d3_time_format(template) { var n = template.length; function format(date) { var string = [], i = -1, j = 0, c, p, f; while (++i < n) { if (template.charCodeAt(i) === 37) { string.push(template.slice(j, i)); if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); string.push(c); j = i + 1; } } string.push(template.slice(j, i)); return string.join(""); } format.parse = function(string) { var d = { y: 1900, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0, Z: null }, i = d3_time_parse(d, template, string, 0); if (i != string.length) return null; if ("p" in d) d.H = d.H % 12 + d.p * 12; var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) { if (!("w" in d)) d.w = "W" in d ? 1 : 0; date.setFullYear(d.y, 0, 1); date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); } else date.setFullYear(d.y, d.m, d.d); date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); return localZ ? date._ : date; }; format.toString = function() { return template; }; return format; } function d3_time_parse(date, template, string, j) { var c, p, t, i = 0, n = template.length, m = string.length; while (i < n) { if (j >= m) return -1; c = template.charCodeAt(i++); if (c === 37) { t = template.charAt(i++); p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; if (!p || (j = p(date, string, j)) < 0) return -1; } else if (c != string.charCodeAt(j++)) { return -1; } } return j; } d3_time_format.utc = function(template) { var local = d3_time_format(template); function format(date) { try { d3_date = d3_date_utc; var utc = new d3_date(); utc._ = date; return local(utc); } finally { d3_date = Date; } } format.parse = function(string) { try { d3_date = d3_date_utc; var date = local.parse(string); return date && date._; } finally { d3_date = Date; } }; format.toString = local.toString; return format; }; d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); locale_periods.forEach(function(p, i) { d3_time_periodLookup.set(p.toLowerCase(), i); }); var d3_time_formats = { a: function(d) { return locale_shortDays[d.getDay()]; }, A: function(d) { return locale_days[d.getDay()]; }, b: function(d) { return locale_shortMonths[d.getMonth()]; }, B: function(d) { return locale_months[d.getMonth()]; }, c: d3_time_format(locale_dateTime), d: function(d, p) { return d3_time_formatPad(d.getDate(), p, 2); }, e: function(d, p) { return d3_time_formatPad(d.getDate(), p, 2); }, H: function(d, p) { return d3_time_formatPad(d.getHours(), p, 2); }, I: function(d, p) { return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); }, j: function(d, p) { return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); }, L: function(d, p) { return d3_time_formatPad(d.getMilliseconds(), p, 3); }, m: function(d, p) { return d3_time_formatPad(d.getMonth() + 1, p, 2); }, M: function(d, p) { return d3_time_formatPad(d.getMinutes(), p, 2); }, p: function(d) { return locale_periods[+(d.getHours() >= 12)]; }, S: function(d, p) { return d3_time_formatPad(d.getSeconds(), p, 2); }, U: function(d, p) { return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); }, w: function(d) { return d.getDay(); }, W: function(d, p) { return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); }, x: d3_time_format(locale_date), X: d3_time_format(locale_time), y: function(d, p) { return d3_time_formatPad(d.getFullYear() % 100, p, 2); }, Y: function(d, p) { return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); }, Z: d3_time_zone, "%": function() { return "%"; } }; var d3_time_parsers = { a: d3_time_parseWeekdayAbbrev, A: d3_time_parseWeekday, b: d3_time_parseMonthAbbrev, B: d3_time_parseMonth, c: d3_time_parseLocaleFull, d: d3_time_parseDay, e: d3_time_parseDay, H: d3_time_parseHour24, I: d3_time_parseHour24, j: d3_time_parseDayOfYear, L: d3_time_parseMilliseconds, m: d3_time_parseMonthNumber, M: d3_time_parseMinutes, p: d3_time_parseAmPm, S: d3_time_parseSeconds, U: d3_time_parseWeekNumberSunday, w: d3_time_parseWeekdayNumber, W: d3_time_parseWeekNumberMonday, x: d3_time_parseLocaleDate, X: d3_time_parseLocaleTime, y: d3_time_parseYear, Y: d3_time_parseFullYear, Z: d3_time_parseZone, "%": d3_time_parseLiteralPercent }; function d3_time_parseWeekdayAbbrev(date, string, i) { d3_time_dayAbbrevRe.lastIndex = 0; var n = d3_time_dayAbbrevRe.exec(string.slice(i)); return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseWeekday(date, string, i) { d3_time_dayRe.lastIndex = 0; var n = d3_time_dayRe.exec(string.slice(i)); return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseMonthAbbrev(date, string, i) { d3_time_monthAbbrevRe.lastIndex = 0; var n = d3_time_monthAbbrevRe.exec(string.slice(i)); return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseMonth(date, string, i) { d3_time_monthRe.lastIndex = 0; var n = d3_time_monthRe.exec(string.slice(i)); return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseLocaleFull(date, string, i) { return d3_time_parse(date, d3_time_formats.c.toString(), string, i); } function d3_time_parseLocaleDate(date, string, i) { return d3_time_parse(date, d3_time_formats.x.toString(), string, i); } function d3_time_parseLocaleTime(date, string, i) { return d3_time_parse(date, d3_time_formats.X.toString(), string, i); } function d3_time_parseAmPm(date, string, i) { var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); return n == null ? -1 : (date.p = n, i); } return d3_time_format; } var d3_time_formatPads = { "-": "", _: " ", "0": "0" }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; function d3_time_formatPad(value, fill, width) { var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); } function d3_time_formatRe(names) { return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); } function d3_time_formatLookup(names) { var map = new d3_Map(), i = -1, n = names.length; while (++i < n) map.set(names[i].toLowerCase(), i); return map; } function d3_time_parseWeekdayNumber(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 1)); return n ? (date.w = +n[0], i + n[0].length) : -1; } function d3_time_parseWeekNumberSunday(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i)); return n ? (date.U = +n[0], i + n[0].length) : -1; } function d3_time_parseWeekNumberMonday(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i)); return n ? (date.W = +n[0], i + n[0].length) : -1; } function d3_time_parseFullYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 4)); return n ? (date.y = +n[0], i + n[0].length) : -1; } function d3_time_parseYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; } function d3_time_parseZone(date, string, i) { return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, i + 5) : -1; } function d3_time_expandYear(d) { return d + (d > 68 ? 1900 : 2e3); } function d3_time_parseMonthNumber(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.m = n[0] - 1, i + n[0].length) : -1; } function d3_time_parseDay(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.d = +n[0], i + n[0].length) : -1; } function d3_time_parseDayOfYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 3)); return n ? (date.j = +n[0], i + n[0].length) : -1; } function d3_time_parseHour24(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.H = +n[0], i + n[0].length) : -1; } function d3_time_parseMinutes(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.M = +n[0], i + n[0].length) : -1; } function d3_time_parseSeconds(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.S = +n[0], i + n[0].length) : -1; } function d3_time_parseMilliseconds(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 3)); return n ? (date.L = +n[0], i + n[0].length) : -1; } function d3_time_zone(d) { var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); } function d3_time_parseLiteralPercent(date, string, i) { d3_time_percentRe.lastIndex = 0; var n = d3_time_percentRe.exec(string.slice(i, i + 1)); return n ? i + n[0].length : -1; } function d3_time_formatMulti(formats) { var n = formats.length, i = -1; while (++i < n) formats[i][0] = this(formats[i][0]); return function(date) { var i = 0, f = formats[i]; while (!f[1](date)) f = formats[++i]; return f[0](date); }; } d3.locale = function(locale) { return { numberFormat: d3_locale_numberFormat(locale), timeFormat: d3_locale_timeFormat(locale) }; }; var d3_locale_enUS = d3.locale({ decimal: ".", thousands: ",", grouping: [ 3 ], currency: [ "$", "" ], dateTime: "%a %b %e %X %Y", date: "%m/%d/%Y", time: "%H:%M:%S", periods: [ "AM", "PM" ], days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }); d3.format = d3_locale_enUS.numberFormat; d3.geo = {}; function d3_adder() {} d3_adder.prototype = { s: 0, t: 0, add: function(y) { d3_adderSum(y, this.t, d3_adderTemp); d3_adderSum(d3_adderTemp.s, this.s, this); if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; }, reset: function() { this.s = this.t = 0; }, valueOf: function() { return this.s; } }; var d3_adderTemp = new d3_adder(); function d3_adderSum(a, b, o) { var x = o.s = a + b, bv = x - a, av = x - bv; o.t = a - av + (b - bv); } d3.geo.stream = function(object, listener) { if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { d3_geo_streamObjectType[object.type](object, listener); } else { d3_geo_streamGeometry(object, listener); } }; function d3_geo_streamGeometry(geometry, listener) { if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { d3_geo_streamGeometryType[geometry.type](geometry, listener); } } var d3_geo_streamObjectType = { Feature: function(feature, listener) { d3_geo_streamGeometry(feature.geometry, listener); }, FeatureCollection: function(object, listener) { var features = object.features, i = -1, n = features.length; while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); } }; var d3_geo_streamGeometryType = { Sphere: function(object, listener) { listener.sphere(); }, Point: function(object, listener) { object = object.coordinates; listener.point(object[0], object[1], object[2]); }, MultiPoint: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); }, LineString: function(object, listener) { d3_geo_streamLine(object.coordinates, listener, 0); }, MultiLineString: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); }, Polygon: function(object, listener) { d3_geo_streamPolygon(object.coordinates, listener); }, MultiPolygon: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); }, GeometryCollection: function(object, listener) { var geometries = object.geometries, i = -1, n = geometries.length; while (++i < n) d3_geo_streamGeometry(geometries[i], listener); } }; function d3_geo_streamLine(coordinates, listener, closed) { var i = -1, n = coordinates.length - closed, coordinate; listener.lineStart(); while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); listener.lineEnd(); } function d3_geo_streamPolygon(coordinates, listener) { var i = -1, n = coordinates.length; listener.polygonStart(); while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); listener.polygonEnd(); } d3.geo.area = function(object) { d3_geo_areaSum = 0; d3.geo.stream(object, d3_geo_area); return d3_geo_areaSum; }; var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); var d3_geo_area = { sphere: function() { d3_geo_areaSum += 4 * π; }, point: d3_noop, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: function() { d3_geo_areaRingSum.reset(); d3_geo_area.lineStart = d3_geo_areaRingStart; }, polygonEnd: function() { var area = 2 * d3_geo_areaRingSum; d3_geo_areaSum += area < 0 ? 4 * π + area : area; d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; } }; function d3_geo_areaRingStart() { var λ00, φ00, λ0, cosφ0, sinφ0; d3_geo_area.point = function(λ, φ) { d3_geo_area.point = nextPoint; λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), sinφ0 = Math.sin(φ); }; function nextPoint(λ, φ) { λ *= d3_radians; φ = φ * d3_radians / 2 + π / 4; var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); d3_geo_areaRingSum.add(Math.atan2(v, u)); λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; } d3_geo_area.lineEnd = function() { nextPoint(λ00, φ00); }; } function d3_geo_cartesian(spherical) { var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; } function d3_geo_cartesianDot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } function d3_geo_cartesianCross(a, b) { return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; } function d3_geo_cartesianAdd(a, b) { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; } function d3_geo_cartesianScale(vector, k) { return [ vector[0] * k, vector[1] * k, vector[2] * k ]; } function d3_geo_cartesianNormalize(d) { var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); d[0] /= l; d[1] /= l; d[2] /= l; } function d3_geo_spherical(cartesian) { return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; } function d3_geo_sphericalEqual(a, b) { return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; } d3.geo.bounds = function() { var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; var bound = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { bound.point = ringPoint; bound.lineStart = ringStart; bound.lineEnd = ringEnd; dλSum = 0; d3_geo_area.polygonStart(); }, polygonEnd: function() { d3_geo_area.polygonEnd(); bound.point = point; bound.lineStart = lineStart; bound.lineEnd = lineEnd; if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; range[0] = λ0, range[1] = λ1; } }; function point(λ, φ) { ranges.push(range = [ λ0 = λ, λ1 = λ ]); if (φ < φ0) φ0 = φ; if (φ > φ1) φ1 = φ; } function linePoint(λ, φ) { var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); if (p0) { var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); d3_geo_cartesianNormalize(inflection); inflection = d3_geo_spherical(inflection); var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { var φi = inflection[1] * d3_degrees; if (φi > φ1) φ1 = φi; } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { var φi = -inflection[1] * d3_degrees; if (φi < φ0) φ0 = φi; } else { if (φ < φ0) φ0 = φ; if (φ > φ1) φ1 = φ; } if (antimeridian) { if (λ < λ_) { if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; } else { if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } } else { if (λ1 >= λ0) { if (λ < λ0) λ0 = λ; if (λ > λ1) λ1 = λ; } else { if (λ > λ_) { if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; } else { if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } } } } else { point(λ, φ); } p0 = p, λ_ = λ; } function lineStart() { bound.point = linePoint; } function lineEnd() { range[0] = λ0, range[1] = λ1; bound.point = point; p0 = null; } function ringPoint(λ, φ) { if (p0) { var dλ = λ - λ_; dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; } else λ__ = λ, φ__ = φ; d3_geo_area.point(λ, φ); linePoint(λ, φ); } function ringStart() { d3_geo_area.lineStart(); } function ringEnd() { ringPoint(λ__, φ__); d3_geo_area.lineEnd(); if (abs(dλSum) > ε) λ0 = -(λ1 = 180); range[0] = λ0, range[1] = λ1; p0 = null; } function angle(λ0, λ1) { return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; } function compareRanges(a, b) { return a[0] - b[0]; } function withinRange(x, range) { return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; } return function(feature) { φ1 = λ1 = -(λ0 = φ0 = Infinity); ranges = []; d3.geo.stream(feature, bound); var n = ranges.length; if (n) { ranges.sort(compareRanges); for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { b = ranges[i]; if (withinRange(b[0], a) || withinRange(b[1], a)) { if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; } else { merged.push(a = b); } } var best = -Infinity, dλ; for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { b = merged[i]; if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; } } ranges = range = null; return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; }; }(); d3.geo.centroid = function(object) { d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; d3.geo.stream(object, d3_geo_centroid); var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; if (m < ε2) { x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; m = x * x + y * y + z * z; if (m < ε2) return [ NaN, NaN ]; } return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; }; var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; var d3_geo_centroid = { sphere: d3_noop, point: d3_geo_centroidPoint, lineStart: d3_geo_centroidLineStart, lineEnd: d3_geo_centroidLineEnd, polygonStart: function() { d3_geo_centroid.lineStart = d3_geo_centroidRingStart; }, polygonEnd: function() { d3_geo_centroid.lineStart = d3_geo_centroidLineStart; } }; function d3_geo_centroidPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); } function d3_geo_centroidPointXYZ(x, y, z) { ++d3_geo_centroidW0; d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; } function d3_geo_centroidLineStart() { var x0, y0, z0; d3_geo_centroid.point = function(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); x0 = cosφ * Math.cos(λ); y0 = cosφ * Math.sin(λ); z0 = Math.sin(φ); d3_geo_centroid.point = nextPoint; d3_geo_centroidPointXYZ(x0, y0, z0); }; function nextPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); d3_geo_centroidW1 += w; d3_geo_centroidX1 += w * (x0 + (x0 = x)); d3_geo_centroidY1 += w * (y0 + (y0 = y)); d3_geo_centroidZ1 += w * (z0 + (z0 = z)); d3_geo_centroidPointXYZ(x0, y0, z0); } } function d3_geo_centroidLineEnd() { d3_geo_centroid.point = d3_geo_centroidPoint; } function d3_geo_centroidRingStart() { var λ00, φ00, x0, y0, z0; d3_geo_centroid.point = function(λ, φ) { λ00 = λ, φ00 = φ; d3_geo_centroid.point = nextPoint; λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); x0 = cosφ * Math.cos(λ); y0 = cosφ * Math.sin(λ); z0 = Math.sin(φ); d3_geo_centroidPointXYZ(x0, y0, z0); }; d3_geo_centroid.lineEnd = function() { nextPoint(λ00, φ00); d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; d3_geo_centroid.point = d3_geo_centroidPoint; }; function nextPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); d3_geo_centroidX2 += v * cx; d3_geo_centroidY2 += v * cy; d3_geo_centroidZ2 += v * cz; d3_geo_centroidW1 += w; d3_geo_centroidX1 += w * (x0 + (x0 = x)); d3_geo_centroidY1 += w * (y0 + (y0 = y)); d3_geo_centroidZ1 += w * (z0 + (z0 = z)); d3_geo_centroidPointXYZ(x0, y0, z0); } } function d3_geo_compose(a, b) { function compose(x, y) { return x = a(x, y), b(x[0], x[1]); } if (a.invert && b.invert) compose.invert = function(x, y) { return x = b.invert(x, y), x && a.invert(x[0], x[1]); }; return compose; } function d3_true() { return true; } function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { var subject = [], clip = []; segments.forEach(function(segment) { if ((n = segment.length - 1) <= 0) return; var n, p0 = segment[0], p1 = segment[n]; if (d3_geo_sphericalEqual(p0, p1)) { listener.lineStart(); for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); listener.lineEnd(); return; } var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); a.o = b; subject.push(a); clip.push(b); a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); b = new d3_geo_clipPolygonIntersection(p1, null, a, true); a.o = b; subject.push(a); clip.push(b); }); clip.sort(compare); d3_geo_clipPolygonLinkCircular(subject); d3_geo_clipPolygonLinkCircular(clip); if (!subject.length) return; for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { clip[i].e = entry = !entry; } var start = subject[0], points, point; while (1) { var current = start, isSubject = true; while (current.v) if ((current = current.n) === start) return; points = current.z; listener.lineStart(); do { current.v = current.o.v = true; if (current.e) { if (isSubject) { for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); } else { interpolate(current.x, current.n.x, 1, listener); } current = current.n; } else { if (isSubject) { points = current.p.z; for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); } else { interpolate(current.x, current.p.x, -1, listener); } current = current.p; } current = current.o; points = current.z; isSubject = !isSubject; } while (!current.v); listener.lineEnd(); } } function d3_geo_clipPolygonLinkCircular(array) { if (!(n = array.length)) return; var n, i = 0, a = array[0], b; while (++i < n) { a.n = b = array[i]; b.p = a; a = b; } a.n = b = array[0]; b.p = a; } function d3_geo_clipPolygonIntersection(point, points, other, entry) { this.x = point; this.z = points; this.o = other; this.e = entry; this.v = false; this.n = this.p = null; } function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { return function(rotate, listener) { var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); var clip = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { clip.point = pointRing; clip.lineStart = ringStart; clip.lineEnd = ringEnd; segments = []; polygon = []; }, polygonEnd: function() { clip.point = point; clip.lineStart = lineStart; clip.lineEnd = lineEnd; segments = d3.merge(segments); var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); if (segments.length) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); } else if (clipStartInside) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); } if (polygonStarted) listener.polygonEnd(), polygonStarted = false; segments = polygon = null; }, sphere: function() { listener.polygonStart(); listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); listener.polygonEnd(); } }; function point(λ, φ) { var point = rotate(λ, φ); if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); } function pointLine(λ, φ) { var point = rotate(λ, φ); line.point(point[0], point[1]); } function lineStart() { clip.point = pointLine; line.lineStart(); } function lineEnd() { clip.point = point; line.lineEnd(); } var segments; var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; function pointRing(λ, φ) { ring.push([ λ, φ ]); var point = rotate(λ, φ); ringListener.point(point[0], point[1]); } function ringStart() { ringListener.lineStart(); ring = []; } function ringEnd() { pointRing(ring[0][0], ring[0][1]); ringListener.lineEnd(); var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; ring.pop(); polygon.push(ring); ring = null; if (!n) return; if (clean & 1) { segment = ringSegments[0]; var n = segment.length - 1, i = -1, point; if (n > 0) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; listener.lineStart(); while (++i < n) listener.point((point = segment[i])[0], point[1]); listener.lineEnd(); } return; } if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); } return clip; }; } function d3_geo_clipSegmentLength1(segment) { return segment.length > 1; } function d3_geo_clipBufferListener() { var lines = [], line; return { lineStart: function() { lines.push(line = []); }, point: function(λ, φ) { line.push([ λ, φ ]); }, lineEnd: d3_noop, buffer: function() { var buffer = lines; lines = []; line = null; return buffer; }, rejoin: function() { if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); } }; } function d3_geo_clipSort(a, b) { return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); } var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); function d3_geo_clipAntimeridianLine(listener) { var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; return { lineStart: function() { listener.lineStart(); clean = 1; }, point: function(λ1, φ1) { var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); if (abs(dλ - π) < ε) { listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); listener.point(sλ0, φ0); listener.lineEnd(); listener.lineStart(); listener.point(sλ1, φ0); listener.point(λ1, φ0); clean = 0; } else if (sλ0 !== sλ1 && dλ >= π) { if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); listener.point(sλ0, φ0); listener.lineEnd(); listener.lineStart(); listener.point(sλ1, φ0); clean = 0; } listener.point(λ0 = λ1, φ0 = φ1); sλ0 = sλ1; }, lineEnd: function() { listener.lineEnd(); λ0 = φ0 = NaN; }, clean: function() { return 2 - clean; } }; } function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; } function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { var φ; if (from == null) { φ = direction * halfπ; listener.point(-π, φ); listener.point(0, φ); listener.point(π, φ); listener.point(π, 0); listener.point(π, -φ); listener.point(0, -φ); listener.point(-π, -φ); listener.point(-π, 0); listener.point(-π, φ); } else if (abs(from[0] - to[0]) > ε) { var s = from[0] < to[0] ? π : -π; φ = direction * s / 2; listener.point(-s, φ); listener.point(0, φ); listener.point(s, φ); } else { listener.point(to[0], to[1]); } } function d3_geo_pointInPolygon(point, polygon) { var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; d3_geo_areaRingSum.reset(); for (var i = 0, n = polygon.length; i < n; ++i) { var ring = polygon[i], m = ring.length; if (!m) continue; var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; while (true) { if (j === m) j = 0; point = ring[j]; var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); polarAngle += antimeridian ? dλ + sdλ * τ : dλ; if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); d3_geo_cartesianNormalize(arc); var intersection = d3_geo_cartesianCross(meridianNormal, arc); d3_geo_cartesianNormalize(intersection); var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { winding += antimeridian ^ dλ >= 0 ? 1 : -1; } } if (!j++) break; λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; } } return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1; } function d3_geo_clipCircle(radius) { var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); function visible(λ, φ) { return Math.cos(λ) * Math.cos(φ) > cr; } function clipLine(listener) { var point0, c0, v0, v00, clean; return { lineStart: function() { v00 = v0 = false; clean = 1; }, point: function(λ, φ) { var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; if (!point0 && (v00 = v0 = v)) listener.lineStart(); if (v !== v0) { point2 = intersect(point0, point1); if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { point1[0] += ε; point1[1] += ε; v = visible(point1[0], point1[1]); } } if (v !== v0) { clean = 0; if (v) { listener.lineStart(); point2 = intersect(point1, point0); listener.point(point2[0], point2[1]); } else { point2 = intersect(point0, point1); listener.point(point2[0], point2[1]); listener.lineEnd(); } point0 = point2; } else if (notHemisphere && point0 && smallRadius ^ v) { var t; if (!(c & c0) && (t = intersect(point1, point0, true))) { clean = 0; if (smallRadius) { listener.lineStart(); listener.point(t[0][0], t[0][1]); listener.point(t[1][0], t[1][1]); listener.lineEnd(); } else { listener.point(t[1][0], t[1][1]); listener.lineEnd(); listener.lineStart(); listener.point(t[0][0], t[0][1]); } } } if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { listener.point(point1[0], point1[1]); } point0 = point1, v0 = v, c0 = c; }, lineEnd: function() { if (v0) listener.lineEnd(); point0 = null; }, clean: function() { return clean | (v00 && v0) << 1; } }; } function intersect(a, b, two) { var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; if (!determinant) return !two && a; var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); d3_geo_cartesianAdd(A, B); var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); if (t2 < 0) return; var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); d3_geo_cartesianAdd(q, A); q = d3_geo_spherical(q); if (!two) return q; var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); d3_geo_cartesianAdd(q1, A); return [ q, d3_geo_spherical(q1) ]; } } function code(λ, φ) { var r = smallRadius ? radius : π - radius, code = 0; if (λ < -r) code |= 1; else if (λ > r) code |= 2; if (φ < -r) code |= 4; else if (φ > r) code |= 8; return code; } } function d3_geom_clipLine(x0, y0, x1, y1) { return function(line) { var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; r = x0 - ax; if (!dx && r > 0) return; r /= dx; if (dx < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dx > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = x1 - ax; if (!dx && r < 0) return; r /= dx; if (dx < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dx > 0) { if (r < t0) return; if (r < t1) t1 = r; } r = y0 - ay; if (!dy && r > 0) return; r /= dy; if (dy < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dy > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = y1 - ay; if (!dy && r < 0) return; r /= dy; if (dy < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dy > 0) { if (r < t0) return; if (r < t1) t1 = r; } if (t0 > 0) line.a = { x: ax + t0 * dx, y: ay + t0 * dy }; if (t1 < 1) line.b = { x: ax + t1 * dx, y: ay + t1 * dy }; return line; }; } var d3_geo_clipExtentMAX = 1e9; d3.geo.clipExtent = function() { var x0, y0, x1, y1, stream, clip, clipExtent = { stream: function(output) { if (stream) stream.valid = false; stream = clip(output); stream.valid = true; return stream; }, extent: function(_) { if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); if (stream) stream.valid = false, stream = null; return clipExtent; } }; return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); }; function d3_geo_clipExtent(x0, y0, x1, y1) { return function(listener) { var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; var clip = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { listener = bufferListener; segments = []; polygon = []; clean = true; }, polygonEnd: function() { listener = listener_; segments = d3.merge(segments); var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; if (inside || visible) { listener.polygonStart(); if (inside) { listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); } if (visible) { d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); } listener.polygonEnd(); } segments = polygon = ring = null; } }; function insidePolygon(p) { var wn = 0, n = polygon.length, y = p[1]; for (var i = 0; i < n; ++i) { for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { b = v[j]; if (a[1] <= y) { if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; } else { if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; } a = b; } } return wn !== 0; } function interpolate(from, to, direction, listener) { var a = 0, a1 = 0; if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { do { listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); } while ((a = (a + direction + 4) % 4) !== a1); } else { listener.point(to[0], to[1]); } } function pointVisible(x, y) { return x0 <= x && x <= x1 && y0 <= y && y <= y1; } function point(x, y) { if (pointVisible(x, y)) listener.point(x, y); } var x__, y__, v__, x_, y_, v_, first, clean; function lineStart() { clip.point = linePoint; if (polygon) polygon.push(ring = []); first = true; v_ = false; x_ = y_ = NaN; } function lineEnd() { if (segments) { linePoint(x__, y__); if (v__ && v_) bufferListener.rejoin(); segments.push(bufferListener.buffer()); } clip.point = point; if (v_) listener.lineEnd(); } function linePoint(x, y) { x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); var v = pointVisible(x, y); if (polygon) ring.push([ x, y ]); if (first) { x__ = x, y__ = y, v__ = v; first = false; if (v) { listener.lineStart(); listener.point(x, y); } } else { if (v && v_) listener.point(x, y); else { var l = { a: { x: x_, y: y_ }, b: { x: x, y: y } }; if (clipLine(l)) { if (!v_) { listener.lineStart(); listener.point(l.a.x, l.a.y); } listener.point(l.b.x, l.b.y); if (!v) listener.lineEnd(); clean = false; } else if (v) { listener.lineStart(); listener.point(x, y); clean = false; } } } x_ = x, y_ = y, v_ = v; } return clip; }; function corner(p, direction) { return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; } function compare(a, b) { return comparePoints(a.x, b.x); } function comparePoints(a, b) { var ca = corner(a, 1), cb = corner(b, 1); return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; } } function d3_geo_conic(projectAt) { var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); p.parallels = function(_) { if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); }; return p; } function d3_geo_conicEqualArea(φ0, φ1) { var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; function forward(λ, φ) { var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; } forward.invert = function(x, y) { var ρ0_y = ρ0 - y; return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; }; return forward; } (d3.geo.conicEqualArea = function() { return d3_geo_conic(d3_geo_conicEqualArea); }).raw = d3_geo_conicEqualArea; d3.geo.albers = function() { return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); }; d3.geo.albersUsa = function() { var lower48 = d3.geo.albers(); var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); var point, pointStream = { point: function(x, y) { point = [ x, y ]; } }, lower48Point, alaskaPoint, hawaiiPoint; function albersUsa(coordinates) { var x = coordinates[0], y = coordinates[1]; point = null; (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); return point; } albersUsa.invert = function(coordinates) { var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); }; albersUsa.stream = function(stream) { var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); return { point: function(x, y) { lower48Stream.point(x, y); alaskaStream.point(x, y); hawaiiStream.point(x, y); }, sphere: function() { lower48Stream.sphere(); alaskaStream.sphere(); hawaiiStream.sphere(); }, lineStart: function() { lower48Stream.lineStart(); alaskaStream.lineStart(); hawaiiStream.lineStart(); }, lineEnd: function() { lower48Stream.lineEnd(); alaskaStream.lineEnd(); hawaiiStream.lineEnd(); }, polygonStart: function() { lower48Stream.polygonStart(); alaskaStream.polygonStart(); hawaiiStream.polygonStart(); }, polygonEnd: function() { lower48Stream.polygonEnd(); alaskaStream.polygonEnd(); hawaiiStream.polygonEnd(); } }; }; albersUsa.precision = function(_) { if (!arguments.length) return lower48.precision(); lower48.precision(_); alaska.precision(_); hawaii.precision(_); return albersUsa; }; albersUsa.scale = function(_) { if (!arguments.length) return lower48.scale(); lower48.scale(_); alaska.scale(_ * .35); hawaii.scale(_); return albersUsa.translate(lower48.translate()); }; albersUsa.translate = function(_) { if (!arguments.length) return lower48.translate(); var k = lower48.scale(), x = +_[0], y = +_[1]; lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; return albersUsa; }; return albersUsa.scale(1070); }; var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { point: d3_noop, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: function() { d3_geo_pathAreaPolygon = 0; d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; }, polygonEnd: function() { d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); } }; function d3_geo_pathAreaRingStart() { var x00, y00, x0, y0; d3_geo_pathArea.point = function(x, y) { d3_geo_pathArea.point = nextPoint; x00 = x0 = x, y00 = y0 = y; }; function nextPoint(x, y) { d3_geo_pathAreaPolygon += y0 * x - x0 * y; x0 = x, y0 = y; } d3_geo_pathArea.lineEnd = function() { nextPoint(x00, y00); }; } var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; var d3_geo_pathBounds = { point: d3_geo_pathBoundsPoint, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: d3_noop, polygonEnd: d3_noop }; function d3_geo_pathBoundsPoint(x, y) { if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; } function d3_geo_pathBuffer() { var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; var stream = { point: point, lineStart: function() { stream.point = pointLineStart; }, lineEnd: lineEnd, polygonStart: function() { stream.lineEnd = lineEndPolygon; }, polygonEnd: function() { stream.lineEnd = lineEnd; stream.point = point; }, pointRadius: function(_) { pointCircle = d3_geo_pathBufferCircle(_); return stream; }, result: function() { if (buffer.length) { var result = buffer.join(""); buffer = []; return result; } } }; function point(x, y) { buffer.push("M", x, ",", y, pointCircle); } function pointLineStart(x, y) { buffer.push("M", x, ",", y); stream.point = pointLine; } function pointLine(x, y) { buffer.push("L", x, ",", y); } function lineEnd() { stream.point = point; } function lineEndPolygon() { buffer.push("Z"); } return stream; } function d3_geo_pathBufferCircle(radius) { return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; } var d3_geo_pathCentroid = { point: d3_geo_pathCentroidPoint, lineStart: d3_geo_pathCentroidLineStart, lineEnd: d3_geo_pathCentroidLineEnd, polygonStart: function() { d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; }, polygonEnd: function() { d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; } }; function d3_geo_pathCentroidPoint(x, y) { d3_geo_centroidX0 += x; d3_geo_centroidY0 += y; ++d3_geo_centroidZ0; } function d3_geo_pathCentroidLineStart() { var x0, y0; d3_geo_pathCentroid.point = function(x, y) { d3_geo_pathCentroid.point = nextPoint; d3_geo_pathCentroidPoint(x0 = x, y0 = y); }; function nextPoint(x, y) { var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); d3_geo_centroidX1 += z * (x0 + x) / 2; d3_geo_centroidY1 += z * (y0 + y) / 2; d3_geo_centroidZ1 += z; d3_geo_pathCentroidPoint(x0 = x, y0 = y); } } function d3_geo_pathCentroidLineEnd() { d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; } function d3_geo_pathCentroidRingStart() { var x00, y00, x0, y0; d3_geo_pathCentroid.point = function(x, y) { d3_geo_pathCentroid.point = nextPoint; d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); }; function nextPoint(x, y) { var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); d3_geo_centroidX1 += z * (x0 + x) / 2; d3_geo_centroidY1 += z * (y0 + y) / 2; d3_geo_centroidZ1 += z; z = y0 * x - x0 * y; d3_geo_centroidX2 += z * (x0 + x); d3_geo_centroidY2 += z * (y0 + y); d3_geo_centroidZ2 += z * 3; d3_geo_pathCentroidPoint(x0 = x, y0 = y); } d3_geo_pathCentroid.lineEnd = function() { nextPoint(x00, y00); }; } function d3_geo_pathContext(context) { var pointRadius = 4.5; var stream = { point: point, lineStart: function() { stream.point = pointLineStart; }, lineEnd: lineEnd, polygonStart: function() { stream.lineEnd = lineEndPolygon; }, polygonEnd: function() { stream.lineEnd = lineEnd; stream.point = point; }, pointRadius: function(_) { pointRadius = _; return stream; }, result: d3_noop }; function point(x, y) { context.moveTo(x + pointRadius, y); context.arc(x, y, pointRadius, 0, τ); } function pointLineStart(x, y) { context.moveTo(x, y); stream.point = pointLine; } function pointLine(x, y) { context.lineTo(x, y); } function lineEnd() { stream.point = point; } function lineEndPolygon() { context.closePath(); } return stream; } function d3_geo_resample(project) { var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; function resample(stream) { return (maxDepth ? resampleRecursive : resampleNone)(stream); } function resampleNone(stream) { return d3_geo_transformPoint(stream, function(x, y) { x = project(x, y); stream.point(x[0], x[1]); }); } function resampleRecursive(stream) { var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; var resample = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { stream.polygonStart(); resample.lineStart = ringStart; }, polygonEnd: function() { stream.polygonEnd(); resample.lineStart = lineStart; } }; function point(x, y) { x = project(x, y); stream.point(x[0], x[1]); } function lineStart() { x0 = NaN; resample.point = linePoint; stream.lineStart(); } function linePoint(λ, φ) { var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); stream.point(x0, y0); } function lineEnd() { resample.point = point; stream.lineEnd(); } function ringStart() { lineStart(); resample.point = ringPoint; resample.lineEnd = ringEnd; } function ringPoint(λ, φ) { linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; resample.point = linePoint; } function ringEnd() { resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); resample.lineEnd = lineEnd; lineEnd(); } return resample; } function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; if (d2 > 4 * δ2 && depth--) { var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); stream.point(x2, y2); resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); } } } resample.precision = function(_) { if (!arguments.length) return Math.sqrt(δ2); maxDepth = (δ2 = _ * _) > 0 && 16; return resample; }; return resample; } d3.geo.path = function() { var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; function path(object) { if (object) { if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); d3.geo.stream(object, cacheStream); } return contextStream.result(); } path.area = function(object) { d3_geo_pathAreaSum = 0; d3.geo.stream(object, projectStream(d3_geo_pathArea)); return d3_geo_pathAreaSum; }; path.centroid = function(object) { d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; }; path.bounds = function(object) { d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); d3.geo.stream(object, projectStream(d3_geo_pathBounds)); return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; }; path.projection = function(_) { if (!arguments.length) return projection; projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; return reset(); }; path.context = function(_) { if (!arguments.length) return context; contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); return reset(); }; path.pointRadius = function(_) { if (!arguments.length) return pointRadius; pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); return path; }; function reset() { cacheStream = null; return path; } return path.projection(d3.geo.albersUsa()).context(null); }; function d3_geo_pathProjectStream(project) { var resample = d3_geo_resample(function(x, y) { return project([ x * d3_degrees, y * d3_degrees ]); }); return function(stream) { return d3_geo_projectionRadians(resample(stream)); }; } d3.geo.transform = function(methods) { return { stream: function(stream) { var transform = new d3_geo_transform(stream); for (var k in methods) transform[k] = methods[k]; return transform; } }; }; function d3_geo_transform(stream) { this.stream = stream; } d3_geo_transform.prototype = { point: function(x, y) { this.stream.point(x, y); }, sphere: function() { this.stream.sphere(); }, lineStart: function() { this.stream.lineStart(); }, lineEnd: function() { this.stream.lineEnd(); }, polygonStart: function() { this.stream.polygonStart(); }, polygonEnd: function() { this.stream.polygonEnd(); } }; function d3_geo_transformPoint(stream, point) { return { point: point, sphere: function() { stream.sphere(); }, lineStart: function() { stream.lineStart(); }, lineEnd: function() { stream.lineEnd(); }, polygonStart: function() { stream.polygonStart(); }, polygonEnd: function() { stream.polygonEnd(); } }; } d3.geo.projection = d3_geo_projection; d3.geo.projectionMutator = d3_geo_projectionMutator; function d3_geo_projection(project) { return d3_geo_projectionMutator(function() { return project; })(); } function d3_geo_projectionMutator(projectAt) { var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { x = project(x, y); return [ x[0] * k + δx, δy - x[1] * k ]; }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; function projection(point) { point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); return [ point[0] * k + δx, δy - point[1] * k ]; } function invert(point) { point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; } projection.stream = function(output) { if (stream) stream.valid = false; stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); stream.valid = true; return stream; }; projection.clipAngle = function(_) { if (!arguments.length) return clipAngle; preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); return invalidate(); }; projection.clipExtent = function(_) { if (!arguments.length) return clipExtent; clipExtent = _; postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; return invalidate(); }; projection.scale = function(_) { if (!arguments.length) return k; k = +_; return reset(); }; projection.translate = function(_) { if (!arguments.length) return [ x, y ]; x = +_[0]; y = +_[1]; return reset(); }; projection.center = function(_) { if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; λ = _[0] % 360 * d3_radians; φ = _[1] % 360 * d3_radians; return reset(); }; projection.rotate = function(_) { if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; δλ = _[0] % 360 * d3_radians; δφ = _[1] % 360 * d3_radians; δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; return reset(); }; d3.rebind(projection, projectResample, "precision"); function reset() { projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); var center = project(λ, φ); δx = x - center[0] * k; δy = y + center[1] * k; return invalidate(); } function invalidate() { if (stream) stream.valid = false, stream = null; return projection; } return function() { project = projectAt.apply(this, arguments); projection.invert = project.invert && invert; return reset(); }; } function d3_geo_projectionRadians(stream) { return d3_geo_transformPoint(stream, function(x, y) { stream.point(x * d3_radians, y * d3_radians); }); } function d3_geo_equirectangular(λ, φ) { return [ λ, φ ]; } (d3.geo.equirectangular = function() { return d3_geo_projection(d3_geo_equirectangular); }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; d3.geo.rotation = function(rotate) { rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); function forward(coordinates) { coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; } forward.invert = function(coordinates) { coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; }; return forward; }; function d3_geo_identityRotation(λ, φ) { return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; } d3_geo_identityRotation.invert = d3_geo_equirectangular; function d3_geo_rotation(δλ, δφ, δγ) { return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; } function d3_geo_forwardRotationλ(δλ) { return function(λ, φ) { return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; }; } function d3_geo_rotationλ(δλ) { var rotation = d3_geo_forwardRotationλ(δλ); rotation.invert = d3_geo_forwardRotationλ(-δλ); return rotation; } function d3_geo_rotationφγ(δφ, δγ) { var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); function rotation(λ, φ) { var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; } rotation.invert = function(λ, φ) { var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; }; return rotation; } d3.geo.circle = function() { var origin = [ 0, 0 ], angle, precision = 6, interpolate; function circle() { var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; interpolate(null, null, 1, { point: function(x, y) { ring.push(x = rotate(x, y)); x[0] *= d3_degrees, x[1] *= d3_degrees; } }); return { type: "Polygon", coordinates: [ ring ] }; } circle.origin = function(x) { if (!arguments.length) return origin; origin = x; return circle; }; circle.angle = function(x) { if (!arguments.length) return angle; interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); return circle; }; circle.precision = function(_) { if (!arguments.length) return precision; interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); return circle; }; return circle.angle(90); }; function d3_geo_circleInterpolate(radius, precision) { var cr = Math.cos(radius), sr = Math.sin(radius); return function(from, to, direction, listener) { var step = direction * precision; if (from != null) { from = d3_geo_circleAngle(cr, from); to = d3_geo_circleAngle(cr, to); if (direction > 0 ? from < to : from > to) from += direction * τ; } else { from = radius + direction * τ; to = radius - .5 * step; } for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); } }; } function d3_geo_circleAngle(cr, point) { var a = d3_geo_cartesian(point); a[0] -= cr; d3_geo_cartesianNormalize(a); var angle = d3_acos(-a[1]); return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); } d3.geo.distance = function(a, b) { var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); }; d3.geo.graticule = function() { var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; function graticule() { return { type: "MultiLineString", coordinates: lines() }; } function lines() { return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return abs(x % DX) > ε; }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return abs(y % DY) > ε; }).map(y)); } graticule.lines = function() { return lines().map(function(coordinates) { return { type: "LineString", coordinates: coordinates }; }); }; graticule.outline = function() { return { type: "Polygon", coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] }; }; graticule.extent = function(_) { if (!arguments.length) return graticule.minorExtent(); return graticule.majorExtent(_).minorExtent(_); }; graticule.majorExtent = function(_) { if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; X0 = +_[0][0], X1 = +_[1][0]; Y0 = +_[0][1], Y1 = +_[1][1]; if (X0 > X1) _ = X0, X0 = X1, X1 = _; if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; return graticule.precision(precision); }; graticule.minorExtent = function(_) { if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; x0 = +_[0][0], x1 = +_[1][0]; y0 = +_[0][1], y1 = +_[1][1]; if (x0 > x1) _ = x0, x0 = x1, x1 = _; if (y0 > y1) _ = y0, y0 = y1, y1 = _; return graticule.precision(precision); }; graticule.step = function(_) { if (!arguments.length) return graticule.minorStep(); return graticule.majorStep(_).minorStep(_); }; graticule.majorStep = function(_) { if (!arguments.length) return [ DX, DY ]; DX = +_[0], DY = +_[1]; return graticule; }; graticule.minorStep = function(_) { if (!arguments.length) return [ dx, dy ]; dx = +_[0], dy = +_[1]; return graticule; }; graticule.precision = function(_) { if (!arguments.length) return precision; precision = +_; x = d3_geo_graticuleX(y0, y1, 90); y = d3_geo_graticuleY(x0, x1, precision); X = d3_geo_graticuleX(Y0, Y1, 90); Y = d3_geo_graticuleY(X0, X1, precision); return graticule; }; return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); }; function d3_geo_graticuleX(y0, y1, dy) { var y = d3.range(y0, y1 - ε, dy).concat(y1); return function(x) { return y.map(function(y) { return [ x, y ]; }); }; } function d3_geo_graticuleY(x0, x1, dx) { var x = d3.range(x0, x1 - ε, dx).concat(x1); return function(y) { return x.map(function(x) { return [ x, y ]; }); }; } function d3_source(d) { return d.source; } function d3_target(d) { return d.target; } d3.geo.greatArc = function() { var source = d3_source, source_, target = d3_target, target_; function greatArc() { return { type: "LineString", coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] }; } greatArc.distance = function() { return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); }; greatArc.source = function(_) { if (!arguments.length) return source; source = _, source_ = typeof _ === "function" ? null : _; return greatArc; }; greatArc.target = function(_) { if (!arguments.length) return target; target = _, target_ = typeof _ === "function" ? null : _; return greatArc; }; greatArc.precision = function() { return arguments.length ? greatArc : 0; }; return greatArc; }; d3.geo.interpolate = function(source, target) { return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); }; function d3_geo_interpolate(x0, y0, x1, y1) { var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); var interpolate = d ? function(t) { var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; } : function() { return [ x0 * d3_degrees, y0 * d3_degrees ]; }; interpolate.distance = d; return interpolate; } d3.geo.length = function(object) { d3_geo_lengthSum = 0; d3.geo.stream(object, d3_geo_length); return d3_geo_lengthSum; }; var d3_geo_lengthSum; var d3_geo_length = { sphere: d3_noop, point: d3_noop, lineStart: d3_geo_lengthLineStart, lineEnd: d3_noop, polygonStart: d3_noop, polygonEnd: d3_noop }; function d3_geo_lengthLineStart() { var λ0, sinφ0, cosφ0; d3_geo_length.point = function(λ, φ) { λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); d3_geo_length.point = nextPoint; }; d3_geo_length.lineEnd = function() { d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; }; function nextPoint(λ, φ) { var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; } } function d3_geo_azimuthal(scale, angle) { function azimuthal(λ, φ) { var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; } azimuthal.invert = function(x, y) { var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; }; return azimuthal; } var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { return Math.sqrt(2 / (1 + cosλcosφ)); }, function(ρ) { return 2 * Math.asin(ρ / 2); }); (d3.geo.azimuthalEqualArea = function() { return d3_geo_projection(d3_geo_azimuthalEqualArea); }).raw = d3_geo_azimuthalEqualArea; var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { var c = Math.acos(cosλcosφ); return c && c / Math.sin(c); }, d3_identity); (d3.geo.azimuthalEquidistant = function() { return d3_geo_projection(d3_geo_azimuthalEquidistant); }).raw = d3_geo_azimuthalEquidistant; function d3_geo_conicConformal(φ0, φ1) { var cosφ0 = Math.cos(φ0), t = function(φ) { return Math.tan(π / 4 + φ / 2); }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; if (!n) return d3_geo_mercator; function forward(λ, φ) { if (F > 0) { if (φ < -halfπ + ε) φ = -halfπ + ε; } else { if (φ > halfπ - ε) φ = halfπ - ε; } var ρ = F / Math.pow(t(φ), n); return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; } forward.invert = function(x, y) { var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; }; return forward; } (d3.geo.conicConformal = function() { return d3_geo_conic(d3_geo_conicConformal); }).raw = d3_geo_conicConformal; function d3_geo_conicEquidistant(φ0, φ1) { var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; if (abs(n) < ε) return d3_geo_equirectangular; function forward(λ, φ) { var ρ = G - φ; return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; } forward.invert = function(x, y) { var ρ0_y = G - y; return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; }; return forward; } (d3.geo.conicEquidistant = function() { return d3_geo_conic(d3_geo_conicEquidistant); }).raw = d3_geo_conicEquidistant; var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { return 1 / cosλcosφ; }, Math.atan); (d3.geo.gnomonic = function() { return d3_geo_projection(d3_geo_gnomonic); }).raw = d3_geo_gnomonic; function d3_geo_mercator(λ, φ) { return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; } d3_geo_mercator.invert = function(x, y) { return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; }; function d3_geo_mercatorProjection(project) { var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; m.scale = function() { var v = scale.apply(m, arguments); return v === m ? clipAuto ? m.clipExtent(null) : m : v; }; m.translate = function() { var v = translate.apply(m, arguments); return v === m ? clipAuto ? m.clipExtent(null) : m : v; }; m.clipExtent = function(_) { var v = clipExtent.apply(m, arguments); if (v === m) { if (clipAuto = _ == null) { var k = π * scale(), t = translate(); clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); } } else if (clipAuto) { v = null; } return v; }; return m.clipExtent(null); } (d3.geo.mercator = function() { return d3_geo_mercatorProjection(d3_geo_mercator); }).raw = d3_geo_mercator; var d3_geo_orthographic = d3_geo_azimuthal(function() { return 1; }, Math.asin); (d3.geo.orthographic = function() { return d3_geo_projection(d3_geo_orthographic); }).raw = d3_geo_orthographic; var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { return 1 / (1 + cosλcosφ); }, function(ρ) { return 2 * Math.atan(ρ); }); (d3.geo.stereographic = function() { return d3_geo_projection(d3_geo_stereographic); }).raw = d3_geo_stereographic; function d3_geo_transverseMercator(λ, φ) { return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; } d3_geo_transverseMercator.invert = function(x, y) { return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; }; (d3.geo.transverseMercator = function() { var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; projection.center = function(_) { return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); }; projection.rotate = function(_) { return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), [ _[0], _[1], _[2] - 90 ]); }; return rotate([ 0, 0, 90 ]); }).raw = d3_geo_transverseMercator; d3.geom = {}; function d3_geom_pointX(d) { return d[0]; } function d3_geom_pointY(d) { return d[1]; } d3.geom.hull = function(vertices) { var x = d3_geom_pointX, y = d3_geom_pointY; if (arguments.length) return hull(vertices); function hull(data) { if (data.length < 3) return []; var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; for (i = 0; i < n; i++) { points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); } points.sort(d3_geom_hullOrder); for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); return polygon; } hull.x = function(_) { return arguments.length ? (x = _, hull) : x; }; hull.y = function(_) { return arguments.length ? (y = _, hull) : y; }; return hull; }; function d3_geom_hullUpper(points) { var n = points.length, hull = [ 0, 1 ], hs = 2; for (var i = 2; i < n; i++) { while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; hull[hs++] = i; } return hull.slice(0, hs); } function d3_geom_hullOrder(a, b) { return a[0] - b[0] || a[1] - b[1]; } d3.geom.polygon = function(coordinates) { d3_subclass(coordinates, d3_geom_polygonPrototype); return coordinates; }; var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; d3_geom_polygonPrototype.area = function() { var i = -1, n = this.length, a, b = this[n - 1], area = 0; while (++i < n) { a = b; b = this[i]; area += a[1] * b[0] - a[0] * b[1]; } return area * .5; }; d3_geom_polygonPrototype.centroid = function(k) { var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; if (!arguments.length) k = -1 / (6 * this.area()); while (++i < n) { a = b; b = this[i]; c = a[0] * b[1] - b[0] * a[1]; x += (a[0] + b[0]) * c; y += (a[1] + b[1]) * c; } return [ x * k, y * k ]; }; d3_geom_polygonPrototype.clip = function(subject) { var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; while (++i < n) { input = subject.slice(); subject.length = 0; b = this[i]; c = input[(m = input.length - closed) - 1]; j = -1; while (++j < m) { d = input[j]; if (d3_geom_polygonInside(d, a, b)) { if (!d3_geom_polygonInside(c, a, b)) { subject.push(d3_geom_polygonIntersect(c, d, a, b)); } subject.push(d); } else if (d3_geom_polygonInside(c, a, b)) { subject.push(d3_geom_polygonIntersect(c, d, a, b)); } c = d; } if (closed) subject.push(subject[0]); a = b; } return subject; }; function d3_geom_polygonInside(p, a, b) { return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); } function d3_geom_polygonIntersect(c, d, a, b) { var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); return [ x1 + ua * x21, y1 + ua * y21 ]; } function d3_geom_polygonClosed(coordinates) { var a = coordinates[0], b = coordinates[coordinates.length - 1]; return !(a[0] - b[0] || a[1] - b[1]); } var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; function d3_geom_voronoiBeach() { d3_geom_voronoiRedBlackNode(this); this.edge = this.site = this.circle = null; } function d3_geom_voronoiCreateBeach(site) { var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); beach.site = site; return beach; } function d3_geom_voronoiDetachBeach(beach) { d3_geom_voronoiDetachCircle(beach); d3_geom_voronoiBeaches.remove(beach); d3_geom_voronoiBeachPool.push(beach); d3_geom_voronoiRedBlackNode(beach); } function d3_geom_voronoiRemoveBeach(beach) { var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { x: x, y: y }, previous = beach.P, next = beach.N, disappearing = [ beach ]; d3_geom_voronoiDetachBeach(beach); var lArc = previous; while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { previous = lArc.P; disappearing.unshift(lArc); d3_geom_voronoiDetachBeach(lArc); lArc = previous; } disappearing.unshift(lArc); d3_geom_voronoiDetachCircle(lArc); var rArc = next; while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { next = rArc.N; disappearing.push(rArc); d3_geom_voronoiDetachBeach(rArc); rArc = next; } disappearing.push(rArc); d3_geom_voronoiDetachCircle(rArc); var nArcs = disappearing.length, iArc; for (iArc = 1; iArc < nArcs; ++iArc) { rArc = disappearing[iArc]; lArc = disappearing[iArc - 1]; d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); } lArc = disappearing[0]; rArc = disappearing[nArcs - 1]; rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); } function d3_geom_voronoiAddBeach(site) { var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; while (node) { dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; if (dxl > ε) node = node.L; else { dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); if (dxr > ε) { if (!node.R) { lArc = node; break; } node = node.R; } else { if (dxl > -ε) { lArc = node.P; rArc = node; } else if (dxr > -ε) { lArc = node; rArc = node.N; } else { lArc = rArc = node; } break; } } } var newArc = d3_geom_voronoiCreateBeach(site); d3_geom_voronoiBeaches.insert(lArc, newArc); if (!lArc && !rArc) return; if (lArc === rArc) { d3_geom_voronoiDetachCircle(lArc); rArc = d3_geom_voronoiCreateBeach(lArc.site); d3_geom_voronoiBeaches.insert(newArc, rArc); newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); return; } if (!rArc) { newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); return; } d3_geom_voronoiDetachCircle(lArc); d3_geom_voronoiDetachCircle(rArc); var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { x: (cy * hb - by * hc) / d + ax, y: (bx * hc - cx * hb) / d + ay }; d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); } function d3_geom_voronoiLeftBreakPoint(arc, directrix) { var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; if (!pby2) return rfocx; var lArc = arc.P; if (!lArc) return -Infinity; site = lArc.site; var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; if (!plby2) return lfocx; var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; return (rfocx + lfocx) / 2; } function d3_geom_voronoiRightBreakPoint(arc, directrix) { var rArc = arc.N; if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); var site = arc.site; return site.y === directrix ? site.x : Infinity; } function d3_geom_voronoiCell(site) { this.site = site; this.edges = []; } d3_geom_voronoiCell.prototype.prepare = function() { var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; while (iHalfEdge--) { edge = halfEdges[iHalfEdge].edge; if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); } halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); return halfEdges.length; }; function d3_geom_voronoiCloseCells(extent) { var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; while (iCell--) { cell = cells[iCell]; if (!cell || !cell.prepare()) continue; halfEdges = cell.edges; nHalfEdges = halfEdges.length; iHalfEdge = 0; while (iHalfEdge < nHalfEdges) { end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { x: x0, y: abs(x2 - x0) < ε ? y2 : y1 } : abs(y3 - y1) < ε && x1 - x3 > ε ? { x: abs(y2 - y1) < ε ? x2 : x1, y: y1 } : abs(x3 - x1) < ε && y3 - y0 > ε ? { x: x1, y: abs(x2 - x1) < ε ? y2 : y0 } : abs(y3 - y0) < ε && x3 - x0 > ε ? { x: abs(y2 - y0) < ε ? x2 : x0, y: y0 } : null), cell.site, null)); ++nHalfEdges; } } } } function d3_geom_voronoiHalfEdgeOrder(a, b) { return b.angle - a.angle; } function d3_geom_voronoiCircle() { d3_geom_voronoiRedBlackNode(this); this.x = this.y = this.arc = this.site = this.cy = null; } function d3_geom_voronoiAttachCircle(arc) { var lArc = arc.P, rArc = arc.N; if (!lArc || !rArc) return; var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; if (lSite === rSite) return; var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; var d = 2 * (ax * cy - ay * cx); if (d >= -ε2) return; var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); circle.arc = arc; circle.site = cSite; circle.x = x + bx; circle.y = cy + Math.sqrt(x * x + y * y); circle.cy = cy; arc.circle = circle; var before = null, node = d3_geom_voronoiCircles._; while (node) { if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { if (node.L) node = node.L; else { before = node.P; break; } } else { if (node.R) node = node.R; else { before = node; break; } } } d3_geom_voronoiCircles.insert(before, circle); if (!before) d3_geom_voronoiFirstCircle = circle; } function d3_geom_voronoiDetachCircle(arc) { var circle = arc.circle; if (circle) { if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; d3_geom_voronoiCircles.remove(circle); d3_geom_voronoiCirclePool.push(circle); d3_geom_voronoiRedBlackNode(circle); arc.circle = null; } } function d3_geom_voronoiClipEdges(extent) { var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; while (i--) { e = edges[i]; if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { e.a = e.b = null; edges.splice(i, 1); } } } function d3_geom_voronoiConnectEdge(edge, extent) { var vb = edge.b; if (vb) return true; var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; if (ry === ly) { if (fx < x0 || fx >= x1) return; if (lx > rx) { if (!va) va = { x: fx, y: y0 }; else if (va.y >= y1) return; vb = { x: fx, y: y1 }; } else { if (!va) va = { x: fx, y: y1 }; else if (va.y < y0) return; vb = { x: fx, y: y0 }; } } else { fm = (lx - rx) / (ry - ly); fb = fy - fm * fx; if (fm < -1 || fm > 1) { if (lx > rx) { if (!va) va = { x: (y0 - fb) / fm, y: y0 }; else if (va.y >= y1) return; vb = { x: (y1 - fb) / fm, y: y1 }; } else { if (!va) va = { x: (y1 - fb) / fm, y: y1 }; else if (va.y < y0) return; vb = { x: (y0 - fb) / fm, y: y0 }; } } else { if (ly < ry) { if (!va) va = { x: x0, y: fm * x0 + fb }; else if (va.x >= x1) return; vb = { x: x1, y: fm * x1 + fb }; } else { if (!va) va = { x: x1, y: fm * x1 + fb }; else if (va.x < x0) return; vb = { x: x0, y: fm * x0 + fb }; } } } edge.a = va; edge.b = vb; return true; } function d3_geom_voronoiEdge(lSite, rSite) { this.l = lSite; this.r = rSite; this.a = this.b = null; } function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { var edge = new d3_geom_voronoiEdge(lSite, rSite); d3_geom_voronoiEdges.push(edge); if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); return edge; } function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { var edge = new d3_geom_voronoiEdge(lSite, null); edge.a = va; edge.b = vb; d3_geom_voronoiEdges.push(edge); return edge; } function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { if (!edge.a && !edge.b) { edge.a = vertex; edge.l = lSite; edge.r = rSite; } else if (edge.l === rSite) { edge.b = vertex; } else { edge.a = vertex; } } function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { var va = edge.a, vb = edge.b; this.edge = edge; this.site = lSite; this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); } d3_geom_voronoiHalfEdge.prototype = { start: function() { return this.edge.l === this.site ? this.edge.a : this.edge.b; }, end: function() { return this.edge.l === this.site ? this.edge.b : this.edge.a; } }; function d3_geom_voronoiRedBlackTree() { this._ = null; } function d3_geom_voronoiRedBlackNode(node) { node.U = node.C = node.L = node.R = node.P = node.N = null; } d3_geom_voronoiRedBlackTree.prototype = { insert: function(after, node) { var parent, grandpa, uncle; if (after) { node.P = after; node.N = after.N; if (after.N) after.N.P = node; after.N = node; if (after.R) { after = after.R; while (after.L) after = after.L; after.L = node; } else { after.R = node; } parent = after; } else if (this._) { after = d3_geom_voronoiRedBlackFirst(this._); node.P = null; node.N = after; after.P = after.L = node; parent = after; } else { node.P = node.N = null; this._ = node; parent = null; } node.L = node.R = null; node.U = parent; node.C = true; after = node; while (parent && parent.C) { grandpa = parent.U; if (parent === grandpa.L) { uncle = grandpa.R; if (uncle && uncle.C) { parent.C = uncle.C = false; grandpa.C = true; after = grandpa; } else { if (after === parent.R) { d3_geom_voronoiRedBlackRotateLeft(this, parent); after = parent; parent = after.U; } parent.C = false; grandpa.C = true; d3_geom_voronoiRedBlackRotateRight(this, grandpa); } } else { uncle = grandpa.L; if (uncle && uncle.C) { parent.C = uncle.C = false; grandpa.C = true; after = grandpa; } else { if (after === parent.L) { d3_geom_voronoiRedBlackRotateRight(this, parent); after = parent; parent = after.U; } parent.C = false; grandpa.C = true; d3_geom_voronoiRedBlackRotateLeft(this, grandpa); } } parent = after.U; } this._.C = false; }, remove: function(node) { if (node.N) node.N.P = node.P; if (node.P) node.P.N = node.N; node.N = node.P = null; var parent = node.U, sibling, left = node.L, right = node.R, next, red; if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); if (parent) { if (parent.L === node) parent.L = next; else parent.R = next; } else { this._ = next; } if (left && right) { red = next.C; next.C = node.C; next.L = left; left.U = next; if (next !== right) { parent = next.U; next.U = node.U; node = next.R; parent.L = node; next.R = right; right.U = next; } else { next.U = parent; parent = next; node = next.R; } } else { red = node.C; node = next; } if (node) node.U = parent; if (red) return; if (node && node.C) { node.C = false; return; } do { if (node === this._) break; if (node === parent.L) { sibling = parent.R; if (sibling.C) { sibling.C = false; parent.C = true; d3_geom_voronoiRedBlackRotateLeft(this, parent); sibling = parent.R; } if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { if (!sibling.R || !sibling.R.C) { sibling.L.C = false; sibling.C = true; d3_geom_voronoiRedBlackRotateRight(this, sibling); sibling = parent.R; } sibling.C = parent.C; parent.C = sibling.R.C = false; d3_geom_voronoiRedBlackRotateLeft(this, parent); node = this._; break; } } else { sibling = parent.L; if (sibling.C) { sibling.C = false; parent.C = true; d3_geom_voronoiRedBlackRotateRight(this, parent); sibling = parent.L; } if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { if (!sibling.L || !sibling.L.C) { sibling.R.C = false; sibling.C = true; d3_geom_voronoiRedBlackRotateLeft(this, sibling); sibling = parent.L; } sibling.C = parent.C; parent.C = sibling.L.C = false; d3_geom_voronoiRedBlackRotateRight(this, parent); node = this._; break; } } sibling.C = true; node = parent; parent = parent.U; } while (!node.C); if (node) node.C = false; } }; function d3_geom_voronoiRedBlackRotateLeft(tree, node) { var p = node, q = node.R, parent = p.U; if (parent) { if (parent.L === p) parent.L = q; else parent.R = q; } else { tree._ = q; } q.U = parent; p.U = q; p.R = q.L; if (p.R) p.R.U = p; q.L = p; } function d3_geom_voronoiRedBlackRotateRight(tree, node) { var p = node, q = node.L, parent = p.U; if (parent) { if (parent.L === p) parent.L = q; else parent.R = q; } else { tree._ = q; } q.U = parent; p.U = q; p.L = q.R; if (p.L) p.L.U = p; q.R = p; } function d3_geom_voronoiRedBlackFirst(node) { while (node.L) node = node.L; return node; } function d3_geom_voronoi(sites, bbox) { var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; d3_geom_voronoiEdges = []; d3_geom_voronoiCells = new Array(sites.length); d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); while (true) { circle = d3_geom_voronoiFirstCircle; if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { if (site.x !== x0 || site.y !== y0) { d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); d3_geom_voronoiAddBeach(site); x0 = site.x, y0 = site.y; } site = sites.pop(); } else if (circle) { d3_geom_voronoiRemoveBeach(circle.arc); } else { break; } } if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); var diagram = { cells: d3_geom_voronoiCells, edges: d3_geom_voronoiEdges }; d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; return diagram; } function d3_geom_voronoiVertexOrder(a, b) { return b.y - a.y || b.x - a.x; } d3.geom.voronoi = function(points) { var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; if (points) return voronoi(points); function voronoi(data) { var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { var s = e.start(); return [ s.x, s.y ]; }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; polygon.point = data[i]; }); return polygons; } function sites(data) { return data.map(function(d, i) { return { x: Math.round(fx(d, i) / ε) * ε, y: Math.round(fy(d, i) / ε) * ε, i: i }; }); } voronoi.links = function(data) { return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { return edge.l && edge.r; }).map(function(edge) { return { source: data[edge.l.i], target: data[edge.r.i] }; }); }; voronoi.triangles = function(data) { var triangles = []; d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; while (++j < m) { e0 = e1; s0 = s1; e1 = edges[j].edge; s1 = e1.l === site ? e1.r : e1.l; if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { triangles.push([ data[i], data[s0.i], data[s1.i] ]); } } }); return triangles; }; voronoi.x = function(_) { return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; }; voronoi.y = function(_) { return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; }; voronoi.clipExtent = function(_) { if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; return voronoi; }; voronoi.size = function(_) { if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); }; return voronoi; }; var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; function d3_geom_voronoiTriangleArea(a, b, c) { return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); } d3.geom.delaunay = function(vertices) { return d3.geom.voronoi().triangles(vertices); }; d3.geom.quadtree = function(points, x1, y1, x2, y2) { var x = d3_geom_pointX, y = d3_geom_pointY, compat; if (compat = arguments.length) { x = d3_geom_quadtreeCompatX; y = d3_geom_quadtreeCompatY; if (compat === 3) { y2 = y1; x2 = x1; y1 = x1 = 0; } return quadtree(points); } function quadtree(data) { var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; if (x1 != null) { x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; } else { x2_ = y2_ = -(x1_ = y1_ = Infinity); xs = [], ys = []; n = data.length; if (compat) for (i = 0; i < n; ++i) { d = data[i]; if (d.x < x1_) x1_ = d.x; if (d.y < y1_) y1_ = d.y; if (d.x > x2_) x2_ = d.x; if (d.y > y2_) y2_ = d.y; xs.push(d.x); ys.push(d.y); } else for (i = 0; i < n; ++i) { var x_ = +fx(d = data[i], i), y_ = +fy(d, i); if (x_ < x1_) x1_ = x_; if (y_ < y1_) y1_ = y_; if (x_ > x2_) x2_ = x_; if (y_ > y2_) y2_ = y_; xs.push(x_); ys.push(y_); } } var dx = x2_ - x1_, dy = y2_ - y1_; if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; function insert(n, d, x, y, x1, y1, x2, y2) { if (isNaN(x) || isNaN(y)) return; if (n.leaf) { var nx = n.x, ny = n.y; if (nx != null) { if (abs(nx - x) + abs(ny - y) < .01) { insertChild(n, d, x, y, x1, y1, x2, y2); } else { var nPoint = n.point; n.x = n.y = n.point = null; insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); insertChild(n, d, x, y, x1, y1, x2, y2); } } else { n.x = x, n.y = y, n.point = d; } } else { insertChild(n, d, x, y, x1, y1, x2, y2); } } function insertChild(n, d, x, y, x1, y1, x2, y2) { var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; n.leaf = false; n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); if (right) x1 = xm; else x2 = xm; if (below) y1 = ym; else y2 = ym; insert(n, d, x, y, x1, y1, x2, y2); } var root = d3_geom_quadtreeNode(); root.add = function(d) { insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); }; root.visit = function(f) { d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); }; root.find = function(point) { return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); }; i = -1; if (x1 == null) { while (++i < n) { insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); } --i; } else data.forEach(root.add); xs = ys = data = d = null; return root; } quadtree.x = function(_) { return arguments.length ? (x = _, quadtree) : x; }; quadtree.y = function(_) { return arguments.length ? (y = _, quadtree) : y; }; quadtree.extent = function(_) { if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], y2 = +_[1][1]; return quadtree; }; quadtree.size = function(_) { if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; return quadtree; }; return quadtree; }; function d3_geom_quadtreeCompatX(d) { return d.x; } function d3_geom_quadtreeCompatY(d) { return d.y; } function d3_geom_quadtreeNode() { return { leaf: true, nodes: [], point: null, x: null, y: null }; } function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { if (!f(node, x1, y1, x2, y2)) { var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); } } function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { var minDistance2 = Infinity, closestPoint; (function find(node, x1, y1, x2, y2) { if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; if (point = node.point) { var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; if (distance2 < minDistance2) { var distance = Math.sqrt(minDistance2 = distance2); x0 = x - distance, y0 = y - distance; x3 = x + distance, y3 = y + distance; closestPoint = point; } } var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; for (var i = below << 1 | right, j = i + 4; i < j; ++i) { if (node = children[i & 3]) switch (i & 3) { case 0: find(node, x1, y1, xm, ym); break; case 1: find(node, xm, y1, x2, ym); break; case 2: find(node, x1, ym, xm, y2); break; case 3: find(node, xm, ym, x2, y2); break; } } })(root, x0, y0, x3, y3); return closestPoint; } d3.interpolateRgb = d3_interpolateRgb; function d3_interpolateRgb(a, b) { a = d3.rgb(a); b = d3.rgb(b); var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; return function(t) { return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); }; } d3.interpolateObject = d3_interpolateObject; function d3_interpolateObject(a, b) { var i = {}, c = {}, k; for (k in a) { if (k in b) { i[k] = d3_interpolate(a[k], b[k]); } else { c[k] = a[k]; } } for (k in b) { if (!(k in a)) { c[k] = b[k]; } } return function(t) { for (k in i) c[k] = i[k](t); return c; }; } d3.interpolateNumber = d3_interpolateNumber; function d3_interpolateNumber(a, b) { a = +a, b = +b; return function(t) { return a * (1 - t) + b * t; }; } d3.interpolateString = d3_interpolateString; function d3_interpolateString(a, b) { var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; a = a + "", b = b + ""; while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { if ((bs = bm.index) > bi) { bs = b.slice(bi, bs); if (s[i]) s[i] += bs; else s[++i] = bs; } if ((am = am[0]) === (bm = bm[0])) { if (s[i]) s[i] += bm; else s[++i] = bm; } else { s[++i] = null; q.push({ i: i, x: d3_interpolateNumber(am, bm) }); } bi = d3_interpolate_numberB.lastIndex; } if (bi < b.length) { bs = b.slice(bi); if (s[i]) s[i] += bs; else s[++i] = bs; } return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { return b(t) + ""; }) : function() { return b; } : (b = q.length, function(t) { for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }); } var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); d3.interpolate = d3_interpolate; function d3_interpolate(a, b) { var i = d3.interpolators.length, f; while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; return f; } d3.interpolators = [ function(a, b) { var t = typeof b; return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); } ]; d3.interpolateArray = d3_interpolateArray; function d3_interpolateArray(a, b) { var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); for (;i < na; ++i) c[i] = a[i]; for (;i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < n0; ++i) c[i] = x[i](t); return c; }; } var d3_ease_default = function() { return d3_identity; }; var d3_ease = d3.map({ linear: d3_ease_default, poly: d3_ease_poly, quad: function() { return d3_ease_quad; }, cubic: function() { return d3_ease_cubic; }, sin: function() { return d3_ease_sin; }, exp: function() { return d3_ease_exp; }, circle: function() { return d3_ease_circle; }, elastic: d3_ease_elastic, back: d3_ease_back, bounce: function() { return d3_ease_bounce; } }); var d3_ease_mode = d3.map({ "in": d3_identity, out: d3_ease_reverse, "in-out": d3_ease_reflect, "out-in": function(f) { return d3_ease_reflect(d3_ease_reverse(f)); } }); d3.ease = function(name) { var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; t = d3_ease.get(t) || d3_ease_default; m = d3_ease_mode.get(m) || d3_identity; return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); }; function d3_ease_clamp(f) { return function(t) { return t <= 0 ? 0 : t >= 1 ? 1 : f(t); }; } function d3_ease_reverse(f) { return function(t) { return 1 - f(1 - t); }; } function d3_ease_reflect(f) { return function(t) { return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); }; } function d3_ease_quad(t) { return t * t; } function d3_ease_cubic(t) { return t * t * t; } function d3_ease_cubicInOut(t) { if (t <= 0) return 0; if (t >= 1) return 1; var t2 = t * t, t3 = t2 * t; return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); } function d3_ease_poly(e) { return function(t) { return Math.pow(t, e); }; } function d3_ease_sin(t) { return 1 - Math.cos(t * halfπ); } function d3_ease_exp(t) { return Math.pow(2, 10 * (t - 1)); } function d3_ease_circle(t) { return 1 - Math.sqrt(1 - t * t); } function d3_ease_elastic(a, p) { var s; if (arguments.length < 2) p = .45; if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); }; } function d3_ease_back(s) { if (!s) s = 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } function d3_ease_bounce(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } d3.interpolateHcl = d3_interpolateHcl; function d3_interpolateHcl(a, b) { a = d3.hcl(a); b = d3.hcl(b); var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; return function(t) { return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; }; } d3.interpolateHsl = d3_interpolateHsl; function d3_interpolateHsl(a, b) { a = d3.hsl(a); b = d3.hsl(b); var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; return function(t) { return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; }; } d3.interpolateLab = d3_interpolateLab; function d3_interpolateLab(a, b) { a = d3.lab(a); b = d3.lab(b); var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; return function(t) { return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; }; } d3.interpolateRound = d3_interpolateRound; function d3_interpolateRound(a, b) { b -= a; return function(t) { return Math.round(a + b * t); }; } d3.transform = function(string) { var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); return (d3.transform = function(string) { if (string != null) { g.setAttribute("transform", string); var t = g.transform.baseVal.consolidate(); } return new d3_transform(t ? t.matrix : d3_transformIdentity); })(string); }; function d3_transform(m) { var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; if (r0[0] * r1[1] < r1[0] * r0[1]) { r0[0] *= -1; r0[1] *= -1; kx *= -1; kz *= -1; } this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; this.translate = [ m.e, m.f ]; this.scale = [ kx, ky ]; this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; } d3_transform.prototype.toString = function() { return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; }; function d3_transformDot(a, b) { return a[0] * b[0] + a[1] * b[1]; } function d3_transformNormalize(a) { var k = Math.sqrt(d3_transformDot(a, a)); if (k) { a[0] /= k; a[1] /= k; } return k; } function d3_transformCombine(a, b, k) { a[0] += k * b[0]; a[1] += k * b[1]; return a; } var d3_transformIdentity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }; d3.interpolateTransform = d3_interpolateTransform; function d3_interpolateTransformPop(s) { return s.length ? s.pop() + "," : ""; } function d3_interpolateTranslate(ta, tb, s, q) { if (ta[0] !== tb[0] || ta[1] !== tb[1]) { var i = s.push("translate(", null, ",", null, ")"); q.push({ i: i - 4, x: d3_interpolateNumber(ta[0], tb[0]) }, { i: i - 2, x: d3_interpolateNumber(ta[1], tb[1]) }); } else if (tb[0] || tb[1]) { s.push("translate(" + tb + ")"); } } function d3_interpolateRotate(ra, rb, s, q) { if (ra !== rb) { if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; q.push({ i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, x: d3_interpolateNumber(ra, rb) }); } else if (rb) { s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); } } function d3_interpolateSkew(wa, wb, s, q) { if (wa !== wb) { q.push({ i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, x: d3_interpolateNumber(wa, wb) }); } else if (wb) { s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); } } function d3_interpolateScale(ka, kb, s, q) { if (ka[0] !== kb[0] || ka[1] !== kb[1]) { var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); q.push({ i: i - 4, x: d3_interpolateNumber(ka[0], kb[0]) }, { i: i - 2, x: d3_interpolateNumber(ka[1], kb[1]) }); } else if (kb[0] !== 1 || kb[1] !== 1) { s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); } } function d3_interpolateTransform(a, b) { var s = [], q = []; a = d3.transform(a), b = d3.transform(b); d3_interpolateTranslate(a.translate, b.translate, s, q); d3_interpolateRotate(a.rotate, b.rotate, s, q); d3_interpolateSkew(a.skew, b.skew, s, q); d3_interpolateScale(a.scale, b.scale, s, q); a = b = null; return function(t) { var i = -1, n = q.length, o; while (++i < n) s[(o = q[i]).i] = o.x(t); return s.join(""); }; } function d3_uninterpolateNumber(a, b) { b = (b -= a = +a) || 1 / b; return function(x) { return (x - a) / b; }; } function d3_uninterpolateClamp(a, b) { b = (b -= a = +a) || 1 / b; return function(x) { return Math.max(0, Math.min(1, (x - a) / b)); }; } d3.layout = {}; d3.layout.bundle = function() { return function(links) { var paths = [], i = -1, n = links.length; while (++i < n) paths.push(d3_layout_bundlePath(links[i])); return paths; }; }; function d3_layout_bundlePath(link) { var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; while (start !== lca) { start = start.parent; points.push(start); } var k = points.length; while (end !== lca) { points.splice(k, 0, end); end = end.parent; } return points; } function d3_layout_bundleAncestors(node) { var ancestors = [], parent = node.parent; while (parent != null) { ancestors.push(node); node = parent; parent = parent.parent; } ancestors.push(node); return ancestors; } function d3_layout_bundleLeastCommonAncestor(a, b) { if (a === b) return a; var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; while (aNode === bNode) { sharedNode = aNode; aNode = aNodes.pop(); bNode = bNodes.pop(); } return sharedNode; } d3.layout.chord = function() { var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; function relayout() { var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; chords = []; groups = []; k = 0, i = -1; while (++i < n) { x = 0, j = -1; while (++j < n) { x += matrix[i][j]; } groupSums.push(x); subgroupIndex.push(d3.range(n)); k += x; } if (sortGroups) { groupIndex.sort(function(a, b) { return sortGroups(groupSums[a], groupSums[b]); }); } if (sortSubgroups) { subgroupIndex.forEach(function(d, i) { d.sort(function(a, b) { return sortSubgroups(matrix[i][a], matrix[i][b]); }); }); } k = (τ - padding * n) / k; x = 0, i = -1; while (++i < n) { x0 = x, j = -1; while (++j < n) { var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; subgroups[di + "-" + dj] = { index: di, subindex: dj, startAngle: a0, endAngle: a1, value: v }; } groups[di] = { index: di, startAngle: x0, endAngle: x, value: groupSums[di] }; x += padding; } i = -1; while (++i < n) { j = i - 1; while (++j < n) { var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; if (source.value || target.value) { chords.push(source.value < target.value ? { source: target, target: source } : { source: source, target: target }); } } } if (sortChords) resort(); } function resort() { chords.sort(function(a, b) { return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); }); } chord.matrix = function(x) { if (!arguments.length) return matrix; n = (matrix = x) && matrix.length; chords = groups = null; return chord; }; chord.padding = function(x) { if (!arguments.length) return padding; padding = x; chords = groups = null; return chord; }; chord.sortGroups = function(x) { if (!arguments.length) return sortGroups; sortGroups = x; chords = groups = null; return chord; }; chord.sortSubgroups = function(x) { if (!arguments.length) return sortSubgroups; sortSubgroups = x; chords = null; return chord; }; chord.sortChords = function(x) { if (!arguments.length) return sortChords; sortChords = x; if (chords) resort(); return chord; }; chord.chords = function() { if (!chords) relayout(); return chords; }; chord.groups = function() { if (!groups) relayout(); return groups; }; return chord; }; d3.layout.force = function() { var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; function repulse(node) { return function(quad, x1, _, x2) { if (quad.point !== node) { var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; if (dw * dw / theta2 < dn) { if (dn < chargeDistance2) { var k = quad.charge / dn; node.px -= dx * k; node.py -= dy * k; } return true; } if (quad.point && dn && dn < chargeDistance2) { var k = quad.pointCharge / dn; node.px -= dx * k; node.py -= dy * k; } } return !quad.charge; }; } force.tick = function() { if ((alpha *= .99) < .005) { timer = null; event.end({ type: "end", alpha: alpha = 0 }); return true; } var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; for (i = 0; i < m; ++i) { o = links[i]; s = o.source; t = o.target; x = t.x - s.x; y = t.y - s.y; if (l = x * x + y * y) { l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; x *= l; y *= l; t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5); t.y -= y * k; s.x += x * (k = 1 - k); s.y += y * k; } } if (k = alpha * gravity) { x = size[0] / 2; y = size[1] / 2; i = -1; if (k) while (++i < n) { o = nodes[i]; o.x += (x - o.x) * k; o.y += (y - o.y) * k; } } if (charge) { d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); i = -1; while (++i < n) { if (!(o = nodes[i]).fixed) { q.visit(repulse(o)); } } } i = -1; while (++i < n) { o = nodes[i]; if (o.fixed) { o.x = o.px; o.y = o.py; } else { o.x -= (o.px - (o.px = o.x)) * friction; o.y -= (o.py - (o.py = o.y)) * friction; } } event.tick({ type: "tick", alpha: alpha }); }; force.nodes = function(x) { if (!arguments.length) return nodes; nodes = x; return force; }; force.links = function(x) { if (!arguments.length) return links; links = x; return force; }; force.size = function(x) { if (!arguments.length) return size; size = x; return force; }; force.linkDistance = function(x) { if (!arguments.length) return linkDistance; linkDistance = typeof x === "function" ? x : +x; return force; }; force.distance = force.linkDistance; force.linkStrength = function(x) { if (!arguments.length) return linkStrength; linkStrength = typeof x === "function" ? x : +x; return force; }; force.friction = function(x) { if (!arguments.length) return friction; friction = +x; return force; }; force.charge = function(x) { if (!arguments.length) return charge; charge = typeof x === "function" ? x : +x; return force; }; force.chargeDistance = function(x) { if (!arguments.length) return Math.sqrt(chargeDistance2); chargeDistance2 = x * x; return force; }; force.gravity = function(x) { if (!arguments.length) return gravity; gravity = +x; return force; }; force.theta = function(x) { if (!arguments.length) return Math.sqrt(theta2); theta2 = x * x; return force; }; force.alpha = function(x) { if (!arguments.length) return alpha; x = +x; if (alpha) { if (x > 0) { alpha = x; } else { timer.c = null, timer.t = NaN, timer = null; event.end({ type: "end", alpha: alpha = 0 }); } } else if (x > 0) { event.start({ type: "start", alpha: alpha = x }); timer = d3_timer(force.tick); } return force; }; force.start = function() { var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; for (i = 0; i < n; ++i) { (o = nodes[i]).index = i; o.weight = 0; } for (i = 0; i < m; ++i) { o = links[i]; if (typeof o.source == "number") o.source = nodes[o.source]; if (typeof o.target == "number") o.target = nodes[o.target]; ++o.source.weight; ++o.target.weight; } for (i = 0; i < n; ++i) { o = nodes[i]; if (isNaN(o.x)) o.x = position("x", w); if (isNaN(o.y)) o.y = position("y", h); if (isNaN(o.px)) o.px = o.x; if (isNaN(o.py)) o.py = o.y; } distances = []; if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; strengths = []; if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; charges = []; if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; function position(dimension, size) { if (!neighbors) { neighbors = new Array(n); for (j = 0; j < n; ++j) { neighbors[j] = []; } for (j = 0; j < m; ++j) { var o = links[j]; neighbors[o.source.index].push(o.target); neighbors[o.target.index].push(o.source); } } var candidates = neighbors[i], j = -1, l = candidates.length, x; while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; return Math.random() * size; } return force.resume(); }; force.resume = function() { return force.alpha(.1); }; force.stop = function() { return force.alpha(0); }; force.drag = function() { if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); if (!arguments.length) return drag; this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); }; function dragmove(d) { d.px = d3.event.x, d.py = d3.event.y; force.resume(); } return d3.rebind(force, event, "on"); }; function d3_layout_forceDragstart(d) { d.fixed |= 2; } function d3_layout_forceDragend(d) { d.fixed &= ~6; } function d3_layout_forceMouseover(d) { d.fixed |= 4; d.px = d.x, d.py = d.y; } function d3_layout_forceMouseout(d) { d.fixed &= ~4; } function d3_layout_forceAccumulate(quad, alpha, charges) { var cx = 0, cy = 0; quad.charge = 0; if (!quad.leaf) { var nodes = quad.nodes, n = nodes.length, i = -1, c; while (++i < n) { c = nodes[i]; if (c == null) continue; d3_layout_forceAccumulate(c, alpha, charges); quad.charge += c.charge; cx += c.charge * c.cx; cy += c.charge * c.cy; } } if (quad.point) { if (!quad.leaf) { quad.point.x += Math.random() - .5; quad.point.y += Math.random() - .5; } var k = alpha * charges[quad.point.index]; quad.charge += quad.pointCharge = k; cx += k * quad.point.x; cy += k * quad.point.y; } quad.cx = cx / quad.charge; quad.cy = cy / quad.charge; } var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; d3.layout.hierarchy = function() { var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; function hierarchy(root) { var stack = [ root ], nodes = [], node; root.depth = 0; while ((node = stack.pop()) != null) { nodes.push(node); if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { var n, childs, child; while (--n >= 0) { stack.push(child = childs[n]); child.parent = node; child.depth = node.depth + 1; } if (value) node.value = 0; node.children = childs; } else { if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; delete node.children; } } d3_layout_hierarchyVisitAfter(root, function(node) { var childs, parent; if (sort && (childs = node.children)) childs.sort(sort); if (value && (parent = node.parent)) parent.value += node.value; }); return nodes; } hierarchy.sort = function(x) { if (!arguments.length) return sort; sort = x; return hierarchy; }; hierarchy.children = function(x) { if (!arguments.length) return children; children = x; return hierarchy; }; hierarchy.value = function(x) { if (!arguments.length) return value; value = x; return hierarchy; }; hierarchy.revalue = function(root) { if (value) { d3_layout_hierarchyVisitBefore(root, function(node) { if (node.children) node.value = 0; }); d3_layout_hierarchyVisitAfter(root, function(node) { var parent; if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; if (parent = node.parent) parent.value += node.value; }); } return root; }; return hierarchy; }; function d3_layout_hierarchyRebind(object, hierarchy) { d3.rebind(object, hierarchy, "sort", "children", "value"); object.nodes = object; object.links = d3_layout_hierarchyLinks; return object; } function d3_layout_hierarchyVisitBefore(node, callback) { var nodes = [ node ]; while ((node = nodes.pop()) != null) { callback(node); if ((children = node.children) && (n = children.length)) { var n, children; while (--n >= 0) nodes.push(children[n]); } } } function d3_layout_hierarchyVisitAfter(node, callback) { var nodes = [ node ], nodes2 = []; while ((node = nodes.pop()) != null) { nodes2.push(node); if ((children = node.children) && (n = children.length)) { var i = -1, n, children; while (++i < n) nodes.push(children[i]); } } while ((node = nodes2.pop()) != null) { callback(node); } } function d3_layout_hierarchyChildren(d) { return d.children; } function d3_layout_hierarchyValue(d) { return d.value; } function d3_layout_hierarchySort(a, b) { return b.value - a.value; } function d3_layout_hierarchyLinks(nodes) { return d3.merge(nodes.map(function(parent) { return (parent.children || []).map(function(child) { return { source: parent, target: child }; }); })); } d3.layout.partition = function() { var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; function position(node, x, dx, dy) { var children = node.children; node.x = x; node.y = node.depth * dy; node.dx = dx; node.dy = dy; if (children && (n = children.length)) { var i = -1, n, c, d; dx = node.value ? dx / node.value : 0; while (++i < n) { position(c = children[i], x, d = c.value * dx, dy); x += d; } } } function depth(node) { var children = node.children, d = 0; if (children && (n = children.length)) { var i = -1, n; while (++i < n) d = Math.max(d, depth(children[i])); } return 1 + d; } function partition(d, i) { var nodes = hierarchy.call(this, d, i); position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); return nodes; } partition.size = function(x) { if (!arguments.length) return size; size = x; return partition; }; return d3_layout_hierarchyRebind(partition, hierarchy); }; d3.layout.pie = function() { var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; function pie(data) { var n = data.length, values = data.map(function(d, i) { return +value.call(pie, d, i); }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v; if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { return values[j] - values[i]; } : function(i, j) { return sort(data[i], data[j]); }); index.forEach(function(i) { arcs[i] = { data: data[i], value: v = values[i], startAngle: a, endAngle: a += v * k + pa, padAngle: p }; }); return arcs; } pie.value = function(_) { if (!arguments.length) return value; value = _; return pie; }; pie.sort = function(_) { if (!arguments.length) return sort; sort = _; return pie; }; pie.startAngle = function(_) { if (!arguments.length) return startAngle; startAngle = _; return pie; }; pie.endAngle = function(_) { if (!arguments.length) return endAngle; endAngle = _; return pie; }; pie.padAngle = function(_) { if (!arguments.length) return padAngle; padAngle = _; return pie; }; return pie; }; var d3_layout_pieSortByValue = {}; d3.layout.stack = function() { var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; function stack(data, index) { if (!(n = data.length)) return data; var series = data.map(function(d, i) { return values.call(stack, d, i); }); var points = series.map(function(d) { return d.map(function(v, i) { return [ x.call(stack, v, i), y.call(stack, v, i) ]; }); }); var orders = order.call(stack, points, index); series = d3.permute(series, orders); points = d3.permute(points, orders); var offsets = offset.call(stack, points, index); var m = series[0].length, n, i, j, o; for (j = 0; j < m; ++j) { out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); for (i = 1; i < n; ++i) { out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); } } return data; } stack.values = function(x) { if (!arguments.length) return values; values = x; return stack; }; stack.order = function(x) { if (!arguments.length) return order; order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; return stack; }; stack.offset = function(x) { if (!arguments.length) return offset; offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; return stack; }; stack.x = function(z) { if (!arguments.length) return x; x = z; return stack; }; stack.y = function(z) { if (!arguments.length) return y; y = z; return stack; }; stack.out = function(z) { if (!arguments.length) return out; out = z; return stack; }; return stack; }; function d3_layout_stackX(d) { return d.x; } function d3_layout_stackY(d) { return d.y; } function d3_layout_stackOut(d, y0, y) { d.y0 = y0; d.y = y; } var d3_layout_stackOrders = d3.map({ "inside-out": function(data) { var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { return max[a] - max[b]; }), top = 0, bottom = 0, tops = [], bottoms = []; for (i = 0; i < n; ++i) { j = index[i]; if (top < bottom) { top += sums[j]; tops.push(j); } else { bottom += sums[j]; bottoms.push(j); } } return bottoms.reverse().concat(tops); }, reverse: function(data) { return d3.range(data.length).reverse(); }, "default": d3_layout_stackOrderDefault }); var d3_layout_stackOffsets = d3.map({ silhouette: function(data) { var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; for (j = 0; j < m; ++j) { for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; if (o > max) max = o; sums.push(o); } for (j = 0; j < m; ++j) { y0[j] = (max - sums[j]) / 2; } return y0; }, wiggle: function(data) { var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; y0[0] = o = o0 = 0; for (j = 1; j < m; ++j) { for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; } s2 += s3 * data[i][j][1]; } y0[j] = o -= s1 ? s2 / s1 * dx : 0; if (o < o0) o0 = o; } for (j = 0; j < m; ++j) y0[j] -= o0; return y0; }, expand: function(data) { var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; for (j = 0; j < m; ++j) { for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; } for (j = 0; j < m; ++j) y0[j] = 0; return y0; }, zero: d3_layout_stackOffsetZero }); function d3_layout_stackOrderDefault(data) { return d3.range(data.length); } function d3_layout_stackOffsetZero(data) { var j = -1, m = data[0].length, y0 = []; while (++j < m) y0[j] = 0; return y0; } function d3_layout_stackMaxIndex(array) { var i = 1, j = 0, v = array[0][1], k, n = array.length; for (;i < n; ++i) { if ((k = array[i][1]) > v) { j = i; v = k; } } return j; } function d3_layout_stackReduceSum(d) { return d.reduce(d3_layout_stackSum, 0); } function d3_layout_stackSum(p, d) { return p + d[1]; } d3.layout.histogram = function() { var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; function histogram(data, i) { var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; while (++i < m) { bin = bins[i] = []; bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); bin.y = 0; } if (m > 0) { i = -1; while (++i < n) { x = values[i]; if (x >= range[0] && x <= range[1]) { bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; bin.y += k; bin.push(data[i]); } } } return bins; } histogram.value = function(x) { if (!arguments.length) return valuer; valuer = x; return histogram; }; histogram.range = function(x) { if (!arguments.length) return ranger; ranger = d3_functor(x); return histogram; }; histogram.bins = function(x) { if (!arguments.length) return binner; binner = typeof x === "number" ? function(range) { return d3_layout_histogramBinFixed(range, x); } : d3_functor(x); return histogram; }; histogram.frequency = function(x) { if (!arguments.length) return frequency; frequency = !!x; return histogram; }; return histogram; }; function d3_layout_histogramBinSturges(range, values) { return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); } function d3_layout_histogramBinFixed(range, n) { var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; while (++x <= n) f[x] = m * x + b; return f; } function d3_layout_histogramRange(values) { return [ d3.min(values), d3.max(values) ]; } d3.layout.pack = function() { var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; function pack(d, i) { var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { return radius; }; root.x = root.y = 0; d3_layout_hierarchyVisitAfter(root, function(d) { d.r = +r(d.value); }); d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); if (padding) { var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; d3_layout_hierarchyVisitAfter(root, function(d) { d.r += dr; }); d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); d3_layout_hierarchyVisitAfter(root, function(d) { d.r -= dr; }); } d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); return nodes; } pack.size = function(_) { if (!arguments.length) return size; size = _; return pack; }; pack.radius = function(_) { if (!arguments.length) return radius; radius = _ == null || typeof _ === "function" ? _ : +_; return pack; }; pack.padding = function(_) { if (!arguments.length) return padding; padding = +_; return pack; }; return d3_layout_hierarchyRebind(pack, hierarchy); }; function d3_layout_packSort(a, b) { return a.value - b.value; } function d3_layout_packInsert(a, b) { var c = a._pack_next; a._pack_next = b; b._pack_prev = a; b._pack_next = c; c._pack_prev = b; } function d3_layout_packSplice(a, b) { a._pack_next = b; b._pack_prev = a; } function d3_layout_packIntersects(a, b) { var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; return .999 * dr * dr > dx * dx + dy * dy; } function d3_layout_packSiblings(node) { if (!(nodes = node.children) || !(n = nodes.length)) return; var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; function bound(node) { xMin = Math.min(node.x - node.r, xMin); xMax = Math.max(node.x + node.r, xMax); yMin = Math.min(node.y - node.r, yMin); yMax = Math.max(node.y + node.r, yMax); } nodes.forEach(d3_layout_packLink); a = nodes[0]; a.x = -a.r; a.y = 0; bound(a); if (n > 1) { b = nodes[1]; b.x = b.r; b.y = 0; bound(b); if (n > 2) { c = nodes[2]; d3_layout_packPlace(a, b, c); bound(c); d3_layout_packInsert(a, c); a._pack_prev = c; d3_layout_packInsert(c, b); b = a._pack_next; for (i = 3; i < n; i++) { d3_layout_packPlace(a, b, c = nodes[i]); var isect = 0, s1 = 1, s2 = 1; for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { if (d3_layout_packIntersects(j, c)) { isect = 1; break; } } if (isect == 1) { for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { if (d3_layout_packIntersects(k, c)) { break; } } } if (isect) { if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); i--; } else { d3_layout_packInsert(a, c); b = c; bound(c); } } } } var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; for (i = 0; i < n; i++) { c = nodes[i]; c.x -= cx; c.y -= cy; cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); } node.r = cr; nodes.forEach(d3_layout_packUnlink); } function d3_layout_packLink(node) { node._pack_next = node._pack_prev = node; } function d3_layout_packUnlink(node) { delete node._pack_next; delete node._pack_prev; } function d3_layout_packTransform(node, x, y, k) { var children = node.children; node.x = x += k * node.x; node.y = y += k * node.y; node.r *= k; if (children) { var i = -1, n = children.length; while (++i < n) d3_layout_packTransform(children[i], x, y, k); } } function d3_layout_packPlace(a, b, c) { var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; if (db && (dx || dy)) { var da = b.r + c.r, dc = dx * dx + dy * dy; da *= da; db *= db; var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); c.x = a.x + x * dx + y * dy; c.y = a.y + x * dy - y * dx; } else { c.x = a.x + db; c.y = a.y; } } d3.layout.tree = function() { var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; function tree(d, i) { var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; d3_layout_hierarchyVisitBefore(root1, secondWalk); if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { var left = root0, right = root0, bottom = root0; d3_layout_hierarchyVisitBefore(root0, function(node) { if (node.x < left.x) left = node; if (node.x > right.x) right = node; if (node.depth > bottom.depth) bottom = node; }); var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); d3_layout_hierarchyVisitBefore(root0, function(node) { node.x = (node.x + tx) * kx; node.y = node.depth * ky; }); } return nodes; } function wrapTree(root0) { var root1 = { A: null, children: [ root0 ] }, queue = [ root1 ], node1; while ((node1 = queue.pop()) != null) { for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { queue.push((children[i] = child = { _: children[i], parent: node1, children: (child = children[i].children) && child.slice() || [], A: null, a: null, z: 0, m: 0, c: 0, s: 0, t: null, i: i }).a = child); } } return root1.children[0]; } function firstWalk(v) { var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; if (children.length) { d3_layout_treeShift(v); var midpoint = (children[0].z + children[children.length - 1].z) / 2; if (w) { v.z = w.z + separation(v._, w._); v.m = v.z - midpoint; } else { v.z = midpoint; } } else if (w) { v.z = w.z + separation(v._, w._); } v.parent.A = apportion(v, w, v.parent.A || siblings[0]); } function secondWalk(v) { v._.x = v.z + v.parent.m; v.m += v.parent.m; } function apportion(v, w, ancestor) { if (w) { var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { vom = d3_layout_treeLeft(vom); vop = d3_layout_treeRight(vop); vop.a = v; shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); if (shift > 0) { d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); sip += shift; sop += shift; } sim += vim.m; sip += vip.m; som += vom.m; sop += vop.m; } if (vim && !d3_layout_treeRight(vop)) { vop.t = vim; vop.m += sim - sop; } if (vip && !d3_layout_treeLeft(vom)) { vom.t = vip; vom.m += sip - som; ancestor = v; } } return ancestor; } function sizeNode(node) { node.x *= size[0]; node.y = node.depth * size[1]; } tree.separation = function(x) { if (!arguments.length) return separation; separation = x; return tree; }; tree.size = function(x) { if (!arguments.length) return nodeSize ? null : size; nodeSize = (size = x) == null ? sizeNode : null; return tree; }; tree.nodeSize = function(x) { if (!arguments.length) return nodeSize ? size : null; nodeSize = (size = x) == null ? null : sizeNode; return tree; }; return d3_layout_hierarchyRebind(tree, hierarchy); }; function d3_layout_treeSeparation(a, b) { return a.parent == b.parent ? 1 : 2; } function d3_layout_treeLeft(v) { var children = v.children; return children.length ? children[0] : v.t; } function d3_layout_treeRight(v) { var children = v.children, n; return (n = children.length) ? children[n - 1] : v.t; } function d3_layout_treeMove(wm, wp, shift) { var change = shift / (wp.i - wm.i); wp.c -= change; wp.s += shift; wm.c += change; wp.z += shift; wp.m += shift; } function d3_layout_treeShift(v) { var shift = 0, change = 0, children = v.children, i = children.length, w; while (--i >= 0) { w = children[i]; w.z += shift; w.m += shift; shift += w.s + (change += w.c); } } function d3_layout_treeAncestor(vim, v, ancestor) { return vim.a.parent === v.parent ? vim.a : ancestor; } d3.layout.cluster = function() { var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; function cluster(d, i) { var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; d3_layout_hierarchyVisitAfter(root, function(node) { var children = node.children; if (children && children.length) { node.x = d3_layout_clusterX(children); node.y = d3_layout_clusterY(children); } else { node.x = previousNode ? x += separation(node, previousNode) : 0; node.y = 0; previousNode = node; } }); var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { node.x = (node.x - root.x) * size[0]; node.y = (root.y - node.y) * size[1]; } : function(node) { node.x = (node.x - x0) / (x1 - x0) * size[0]; node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; }); return nodes; } cluster.separation = function(x) { if (!arguments.length) return separation; separation = x; return cluster; }; cluster.size = function(x) { if (!arguments.length) return nodeSize ? null : size; nodeSize = (size = x) == null; return cluster; }; cluster.nodeSize = function(x) { if (!arguments.length) return nodeSize ? size : null; nodeSize = (size = x) != null; return cluster; }; return d3_layout_hierarchyRebind(cluster, hierarchy); }; function d3_layout_clusterY(children) { return 1 + d3.max(children, function(child) { return child.y; }); } function d3_layout_clusterX(children) { return children.reduce(function(x, child) { return x + child.x; }, 0) / children.length; } function d3_layout_clusterLeft(node) { var children = node.children; return children && children.length ? d3_layout_clusterLeft(children[0]) : node; } function d3_layout_clusterRight(node) { var children = node.children, n; return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; } d3.layout.treemap = function() { var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); function scale(children, k) { var i = -1, n = children.length, child, area; while (++i < n) { area = (child = children[i]).value * (k < 0 ? 0 : k); child.area = isNaN(area) || area <= 0 ? 0 : area; } } function squarify(node) { var children = node.children; if (children && children.length) { var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; scale(remaining, rect.dx * rect.dy / node.value); row.area = 0; while ((n = remaining.length) > 0) { row.push(child = remaining[n - 1]); row.area += child.area; if (mode !== "squarify" || (score = worst(row, u)) <= best) { remaining.pop(); best = score; } else { row.area -= row.pop().area; position(row, u, rect, false); u = Math.min(rect.dx, rect.dy); row.length = row.area = 0; best = Infinity; } } if (row.length) { position(row, u, rect, true); row.length = row.area = 0; } children.forEach(squarify); } } function stickify(node) { var children = node.children; if (children && children.length) { var rect = pad(node), remaining = children.slice(), child, row = []; scale(remaining, rect.dx * rect.dy / node.value); row.area = 0; while (child = remaining.pop()) { row.push(child); row.area += child.area; if (child.z != null) { position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); row.length = row.area = 0; } } children.forEach(stickify); } } function worst(row, u) { var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; while (++i < n) { if (!(r = row[i].area)) continue; if (r < rmin) rmin = r; if (r > rmax) rmax = r; } s *= s; u *= u; return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; } function position(row, u, rect, flush) { var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; if (u == rect.dx) { if (flush || v > rect.dy) v = rect.dy; while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dy = v; x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); } o.z = true; o.dx += rect.x + rect.dx - x; rect.y += v; rect.dy -= v; } else { if (flush || v > rect.dx) v = rect.dx; while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dx = v; y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); } o.z = false; o.dy += rect.y + rect.dy - y; rect.x += v; rect.dx -= v; } } function treemap(d) { var nodes = stickies || hierarchy(d), root = nodes[0]; root.x = root.y = 0; if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0; if (stickies) hierarchy.revalue(root); scale([ root ], root.dx * root.dy / root.value); (stickies ? stickify : squarify)(root); if (sticky) stickies = nodes; return nodes; } treemap.size = function(x) { if (!arguments.length) return size; size = x; return treemap; }; treemap.padding = function(x) { if (!arguments.length) return padding; function padFunction(node) { var p = x.call(treemap, node, node.depth); return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); } function padConstant(node) { return d3_layout_treemapPad(node, x); } var type; pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], padConstant) : padConstant; return treemap; }; treemap.round = function(x) { if (!arguments.length) return round != Number; round = x ? Math.round : Number; return treemap; }; treemap.sticky = function(x) { if (!arguments.length) return sticky; sticky = x; stickies = null; return treemap; }; treemap.ratio = function(x) { if (!arguments.length) return ratio; ratio = x; return treemap; }; treemap.mode = function(x) { if (!arguments.length) return mode; mode = x + ""; return treemap; }; return d3_layout_hierarchyRebind(treemap, hierarchy); }; function d3_layout_treemapPadNull(node) { return { x: node.x, y: node.y, dx: node.dx, dy: node.dy }; } function d3_layout_treemapPad(node, padding) { var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; if (dx < 0) { x += dx / 2; dx = 0; } if (dy < 0) { y += dy / 2; dy = 0; } return { x: x, y: y, dx: dx, dy: dy }; } d3.random = { normal: function(µ, σ) { var n = arguments.length; if (n < 2) σ = 1; if (n < 1) µ = 0; return function() { var x, y, r; do { x = Math.random() * 2 - 1; y = Math.random() * 2 - 1; r = x * x + y * y; } while (!r || r > 1); return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); }; }, logNormal: function() { var random = d3.random.normal.apply(d3, arguments); return function() { return Math.exp(random()); }; }, bates: function(m) { var random = d3.random.irwinHall(m); return function() { return random() / m; }; }, irwinHall: function(m) { return function() { for (var s = 0, j = 0; j < m; j++) s += Math.random(); return s; }; } }; d3.scale = {}; function d3_scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [ start, stop ] : [ stop, start ]; } function d3_scaleRange(scale) { return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); } function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); return function(x) { return i(u(x)); }; } function d3_scale_nice(domain, nice) { var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; if (x1 < x0) { dx = i0, i0 = i1, i1 = dx; dx = x0, x0 = x1, x1 = dx; } domain[i0] = nice.floor(x0); domain[i1] = nice.ceil(x1); return domain; } function d3_scale_niceStep(step) { return step ? { floor: function(x) { return Math.floor(x / step) * step; }, ceil: function(x) { return Math.ceil(x / step) * step; } } : d3_scale_niceIdentity; } var d3_scale_niceIdentity = { floor: d3_identity, ceil: d3_identity }; function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; if (domain[k] < domain[0]) { domain = domain.slice().reverse(); range = range.slice().reverse(); } while (++j <= k) { u.push(uninterpolate(domain[j - 1], domain[j])); i.push(interpolate(range[j - 1], range[j])); } return function(x) { var j = d3.bisect(domain, x, 1, k) - 1; return i[j](u[j](x)); }; } d3.scale.linear = function() { return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); }; function d3_scale_linear(domain, range, interpolate, clamp) { var output, input; function rescale() { var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; output = linear(domain, range, uninterpolate, interpolate); input = linear(range, domain, uninterpolate, d3_interpolate); return scale; } function scale(x) { return output(x); } scale.invert = function(y) { return input(y); }; scale.domain = function(x) { if (!arguments.length) return domain; domain = x.map(Number); return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.rangeRound = function(x) { return scale.range(x).interpolate(d3_interpolateRound); }; scale.clamp = function(x) { if (!arguments.length) return clamp; clamp = x; return rescale(); }; scale.interpolate = function(x) { if (!arguments.length) return interpolate; interpolate = x; return rescale(); }; scale.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; scale.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; scale.nice = function(m) { d3_scale_linearNice(domain, m); return rescale(); }; scale.copy = function() { return d3_scale_linear(domain, range, interpolate, clamp); }; return rescale(); } function d3_scale_linearRebind(scale, linear) { return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } function d3_scale_linearNice(domain, m) { d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); return domain; } function d3_scale_linearTickRange(domain, m) { if (m == null) m = 10; var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; extent[0] = Math.ceil(extent[0] / step) * step; extent[1] = Math.floor(extent[1] / step) * step + step * .5; extent[2] = step; return extent; } function d3_scale_linearTicks(domain, m) { return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); } function d3_scale_linearTickFormat(domain, m, format) { var range = d3_scale_linearTickRange(domain, m); if (format) { var match = d3_format_re.exec(format); match.shift(); if (match[8] === "s") { var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); match[8] = "f"; format = d3.format(match.join("")); return function(d) { return format(prefix.scale(d)) + prefix.symbol; }; } if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); format = match.join(""); } else { format = ",." + d3_scale_linearPrecision(range[2]) + "f"; } return d3.format(format); } var d3_scale_linearFormatSignificant = { s: 1, g: 1, p: 1, r: 1, e: 1 }; function d3_scale_linearPrecision(value) { return -Math.floor(Math.log(value) / Math.LN10 + .01); } function d3_scale_linearFormatPrecision(type, range) { var p = d3_scale_linearPrecision(range[2]); return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; } d3.scale.log = function() { return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); }; function d3_scale_log(linear, base, positive, domain) { function log(x) { return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); } function pow(x) { return positive ? Math.pow(base, x) : -Math.pow(base, -x); } function scale(x) { return linear(log(x)); } scale.invert = function(x) { return pow(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return domain; positive = x[0] >= 0; linear.domain((domain = x.map(Number)).map(log)); return scale; }; scale.base = function(_) { if (!arguments.length) return base; base = +_; linear.domain(domain.map(log)); return scale; }; scale.nice = function() { var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); linear.domain(niced); domain = niced.map(pow); return scale; }; scale.ticks = function() { var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; if (isFinite(j - i)) { if (positive) { for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); ticks.push(pow(i)); } else { ticks.push(pow(i)); for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); } for (i = 0; ticks[i] < u; i++) {} for (j = ticks.length; ticks[j - 1] > v; j--) {} ticks = ticks.slice(i, j); } return ticks; }; scale.tickFormat = function(n, format) { if (!arguments.length) return d3_scale_logFormat; if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); var k = Math.max(1, base * n / scale.ticks().length); return function(d) { var i = d / pow(Math.round(log(d))); if (i * base < base - .5) i *= base; return i <= k ? format(d) : ""; }; }; scale.copy = function() { return d3_scale_log(linear.copy(), base, positive, domain); }; return d3_scale_linearRebind(scale, linear); } var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { floor: function(x) { return -Math.ceil(-x); }, ceil: function(x) { return -Math.floor(-x); } }; d3.scale.pow = function() { return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); }; function d3_scale_pow(linear, exponent, domain) { var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); function scale(x) { return linear(powp(x)); } scale.invert = function(x) { return powb(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return domain; linear.domain((domain = x.map(Number)).map(powp)); return scale; }; scale.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; scale.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; scale.nice = function(m) { return scale.domain(d3_scale_linearNice(domain, m)); }; scale.exponent = function(x) { if (!arguments.length) return exponent; powp = d3_scale_powPow(exponent = x); powb = d3_scale_powPow(1 / exponent); linear.domain(domain.map(powp)); return scale; }; scale.copy = function() { return d3_scale_pow(linear.copy(), exponent, domain); }; return d3_scale_linearRebind(scale, linear); } function d3_scale_powPow(e) { return function(x) { return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); }; } d3.scale.sqrt = function() { return d3.scale.pow().exponent(.5); }; d3.scale.ordinal = function() { return d3_scale_ordinal([], { t: "range", a: [ [] ] }); }; function d3_scale_ordinal(domain, ranger) { var index, range, rangeBand; function scale(x) { return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; } function steps(start, step) { return d3.range(domain.length).map(function(i) { return start + step * i; }); } scale.domain = function(x) { if (!arguments.length) return domain; domain = []; index = new d3_Map(); var i = -1, n = x.length, xi; while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); return scale[ranger.t].apply(scale, ranger.a); }; scale.range = function(x) { if (!arguments.length) return range; range = x; rangeBand = 0; ranger = { t: "range", a: arguments }; return scale; }; scale.rangePoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain.length - 1 + padding); range = steps(start + step * padding / 2, step); rangeBand = 0; ranger = { t: "rangePoints", a: arguments }; return scale; }; scale.rangeRoundPoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain.length - 1 + padding) | 0; range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); rangeBand = 0; ranger = { t: "rangeRoundPoints", a: arguments }; return scale; }; scale.rangeBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); range = steps(start + step * outerPadding, step); if (reverse) range.reverse(); rangeBand = step * (1 - padding); ranger = { t: "rangeBands", a: arguments }; return scale; }; scale.rangeRoundBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); if (reverse) range.reverse(); rangeBand = Math.round(step * (1 - padding)); ranger = { t: "rangeRoundBands", a: arguments }; return scale; }; scale.rangeBand = function() { return rangeBand; }; scale.rangeExtent = function() { return d3_scaleExtent(ranger.a[0]); }; scale.copy = function() { return d3_scale_ordinal(domain, ranger); }; return scale.domain(domain); } d3.scale.category10 = function() { return d3.scale.ordinal().range(d3_category10); }; d3.scale.category20 = function() { return d3.scale.ordinal().range(d3_category20); }; d3.scale.category20b = function() { return d3.scale.ordinal().range(d3_category20b); }; d3.scale.category20c = function() { return d3.scale.ordinal().range(d3_category20c); }; var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); d3.scale.quantile = function() { return d3_scale_quantile([], []); }; function d3_scale_quantile(domain, range) { var thresholds; function rescale() { var k = 0, q = range.length; thresholds = []; while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); return scale; } function scale(x) { if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; } scale.domain = function(x) { if (!arguments.length) return domain; domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.quantiles = function() { return thresholds; }; scale.invertExtent = function(y) { y = range.indexOf(y); return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; }; scale.copy = function() { return d3_scale_quantile(domain, range); }; return rescale(); } d3.scale.quantize = function() { return d3_scale_quantize(0, 1, [ 0, 1 ]); }; function d3_scale_quantize(x0, x1, range) { var kx, i; function scale(x) { return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; } function rescale() { kx = range.length / (x1 - x0); i = range.length - 1; return scale; } scale.domain = function(x) { if (!arguments.length) return [ x0, x1 ]; x0 = +x[0]; x1 = +x[x.length - 1]; return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.invertExtent = function(y) { y = range.indexOf(y); y = y < 0 ? NaN : y / kx + x0; return [ y, y + 1 / kx ]; }; scale.copy = function() { return d3_scale_quantize(x0, x1, range); }; return rescale(); } d3.scale.threshold = function() { return d3_scale_threshold([ .5 ], [ 0, 1 ]); }; function d3_scale_threshold(domain, range) { function scale(x) { if (x <= x) return range[d3.bisect(domain, x)]; } scale.domain = function(_) { if (!arguments.length) return domain; domain = _; return scale; }; scale.range = function(_) { if (!arguments.length) return range; range = _; return scale; }; scale.invertExtent = function(y) { y = range.indexOf(y); return [ domain[y - 1], domain[y] ]; }; scale.copy = function() { return d3_scale_threshold(domain, range); }; return scale; } d3.scale.identity = function() { return d3_scale_identity([ 0, 1 ]); }; function d3_scale_identity(domain) { function identity(x) { return +x; } identity.invert = identity; identity.domain = identity.range = function(x) { if (!arguments.length) return domain; domain = x.map(identity); return identity; }; identity.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; identity.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; identity.copy = function() { return d3_scale_identity(domain); }; return identity; } d3.svg = {}; function d3_zero() { return 0; } d3.svg.arc = function() { var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; function arc() { var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; if (r1 < r0) rc = r1, r1 = r0, r0 = rc; if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); if (!cw) p1 *= -1; if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); } if (r1) { x0 = r1 * Math.cos(a0 + p1); y0 = r1 * Math.sin(a0 + p1); x1 = r1 * Math.cos(a1 - p1); y1 = r1 * Math.sin(a1 - p1); var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { var h1 = (a0 + a1) / 2; x0 = r1 * Math.cos(h1); y0 = r1 * Math.sin(h1); x1 = y1 = null; } } else { x0 = y0 = 0; } if (r0) { x2 = r0 * Math.cos(a1 - p0); y2 = r0 * Math.sin(a1 - p0); x3 = r0 * Math.cos(a0 + p0); y3 = r0 * Math.sin(a0 + p0); var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { var h0 = (a0 + a1) / 2; x2 = r0 * Math.cos(h0); y2 = r0 * Math.sin(h0); x3 = y3 = null; } } else { x2 = y2 = 0; } if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { cr = r0 < r1 ^ cw ? 0 : 1; var rc1 = rc, rc0 = rc; if (da < π) { var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); } if (x1 != null) { var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); if (rc === rc1) { path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); } else { path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); } } else { path.push("M", x0, ",", y0); } if (x3 != null) { var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); if (rc === rc0) { path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); } else { path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); } } else { path.push("L", x2, ",", y2); } } else { path.push("M", x0, ",", y0); if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); path.push("L", x2, ",", y2); if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); } path.push("Z"); return path.join(""); } function circleSegment(r1, cw) { return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; } arc.innerRadius = function(v) { if (!arguments.length) return innerRadius; innerRadius = d3_functor(v); return arc; }; arc.outerRadius = function(v) { if (!arguments.length) return outerRadius; outerRadius = d3_functor(v); return arc; }; arc.cornerRadius = function(v) { if (!arguments.length) return cornerRadius; cornerRadius = d3_functor(v); return arc; }; arc.padRadius = function(v) { if (!arguments.length) return padRadius; padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); return arc; }; arc.startAngle = function(v) { if (!arguments.length) return startAngle; startAngle = d3_functor(v); return arc; }; arc.endAngle = function(v) { if (!arguments.length) return endAngle; endAngle = d3_functor(v); return arc; }; arc.padAngle = function(v) { if (!arguments.length) return padAngle; padAngle = d3_functor(v); return arc; }; arc.centroid = function() { var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; return [ Math.cos(a) * r, Math.sin(a) * r ]; }; return arc; }; var d3_svg_arcAuto = "auto"; function d3_svg_arcInnerRadius(d) { return d.innerRadius; } function d3_svg_arcOuterRadius(d) { return d.outerRadius; } function d3_svg_arcStartAngle(d) { return d.startAngle; } function d3_svg_arcEndAngle(d) { return d.endAngle; } function d3_svg_arcPadAngle(d) { return d && d.padAngle; } function d3_svg_arcSweep(x0, y0, x1, y1) { return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; } function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; } function d3_svg_line(projection) { var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; function line(data) { var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); function segment() { segments.push("M", interpolate(projection(points), tension)); } while (++i < n) { if (defined.call(this, d = data[i], i)) { points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); } else if (points.length) { segment(); points = []; } } if (points.length) segment(); return segments.length ? segments.join("") : null; } line.x = function(_) { if (!arguments.length) return x; x = _; return line; }; line.y = function(_) { if (!arguments.length) return y; y = _; return line; }; line.defined = function(_) { if (!arguments.length) return defined; defined = _; return line; }; line.interpolate = function(_) { if (!arguments.length) return interpolateKey; if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; return line; }; line.tension = function(_) { if (!arguments.length) return tension; tension = _; return line; }; return line; } d3.svg.line = function() { return d3_svg_line(d3_identity); }; var d3_svg_lineInterpolators = d3.map({ linear: d3_svg_lineLinear, "linear-closed": d3_svg_lineLinearClosed, step: d3_svg_lineStep, "step-before": d3_svg_lineStepBefore, "step-after": d3_svg_lineStepAfter, basis: d3_svg_lineBasis, "basis-open": d3_svg_lineBasisOpen, "basis-closed": d3_svg_lineBasisClosed, bundle: d3_svg_lineBundle, cardinal: d3_svg_lineCardinal, "cardinal-open": d3_svg_lineCardinalOpen, "cardinal-closed": d3_svg_lineCardinalClosed, monotone: d3_svg_lineMonotone }); d3_svg_lineInterpolators.forEach(function(key, value) { value.key = key; value.closed = /-closed$/.test(key); }); function d3_svg_lineLinear(points) { return points.length > 1 ? points.join("L") : points + "Z"; } function d3_svg_lineLinearClosed(points) { return points.join("L") + "Z"; } function d3_svg_lineStep(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); if (n > 1) path.push("H", p[0]); return path.join(""); } function d3_svg_lineStepBefore(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); return path.join(""); } function d3_svg_lineStepAfter(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); return path.join(""); } function d3_svg_lineCardinalOpen(points, tension) { return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); } function d3_svg_lineCardinalClosed(points, tension) { return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); } function d3_svg_lineCardinal(points, tension) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); } function d3_svg_lineHermite(points, tangents) { if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { return d3_svg_lineLinear(points); } var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; if (quad) { path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; p0 = points[1]; pi = 2; } if (tangents.length > 1) { t = tangents[1]; p = points[pi]; pi++; path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; for (var i = 2; i < tangents.length; i++, pi++) { p = points[pi]; t = tangents[i]; path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; } } if (quad) { var lp = points[pi]; path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; } return path; } function d3_svg_lineCardinalTangents(points, tension) { var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; while (++i < n) { p0 = p1; p1 = p2; p2 = points[i]; tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); } return tangents; } function d3_svg_lineBasis(points) { if (points.length < 3) return d3_svg_lineLinear(points); var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; points.push(points[n - 1]); while (++i <= n) { pi = points[i]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } points.pop(); path.push("L", pi); return path.join(""); } function d3_svg_lineBasisOpen(points) { if (points.length < 4) return d3_svg_lineLinear(points); var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; while (++i < 3) { pi = points[i]; px.push(pi[0]); py.push(pi[1]); } path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); --i; while (++i < n) { pi = points[i]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBasisClosed(points) { var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; while (++i < 4) { pi = points[i % n]; px.push(pi[0]); py.push(pi[1]); } path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; --i; while (++i < m) { pi = points[i % n]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBundle(points, tension) { var n = points.length - 1; if (n) { var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; while (++i <= n) { p = points[i]; t = i / n; p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); } } return d3_svg_lineBasis(points); } function d3_svg_lineDot4(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; function d3_svg_lineBasisBezier(path, x, y) { path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); } function d3_svg_lineSlope(p0, p1) { return (p1[1] - p0[1]) / (p1[0] - p0[0]); } function d3_svg_lineFiniteDifferences(points) { var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); while (++i < j) { m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; } m[i] = d; return m; } function d3_svg_lineMonotoneTangents(points) { var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; while (++i < j) { d = d3_svg_lineSlope(points[i], points[i + 1]); if (abs(d) < ε) { m[i] = m[i + 1] = 0; } else { a = m[i] / d; b = m[i + 1] / d; s = a * a + b * b; if (s > 9) { s = d * 3 / Math.sqrt(s); m[i] = s * a; m[i + 1] = s * b; } } } i = -1; while (++i <= j) { s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); tangents.push([ s || 0, m[i] * s || 0 ]); } return tangents; } function d3_svg_lineMonotone(points) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); } d3.svg.line.radial = function() { var line = d3_svg_line(d3_svg_lineRadial); line.radius = line.x, delete line.x; line.angle = line.y, delete line.y; return line; }; function d3_svg_lineRadial(points) { var point, i = -1, n = points.length, r, a; while (++i < n) { point = points[i]; r = point[0]; a = point[1] - halfπ; point[0] = r * Math.cos(a); point[1] = r * Math.sin(a); } return points; } function d3_svg_area(projection) { var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; function area(data) { var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { return x; } : d3_functor(x1), fy1 = y0 === y1 ? function() { return y; } : d3_functor(y1), x, y; function segment() { segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); } while (++i < n) { if (defined.call(this, d = data[i], i)) { points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); } else if (points0.length) { segment(); points0 = []; points1 = []; } } if (points0.length) segment(); return segments.length ? segments.join("") : null; } area.x = function(_) { if (!arguments.length) return x1; x0 = x1 = _; return area; }; area.x0 = function(_) { if (!arguments.length) return x0; x0 = _; return area; }; area.x1 = function(_) { if (!arguments.length) return x1; x1 = _; return area; }; area.y = function(_) { if (!arguments.length) return y1; y0 = y1 = _; return area; }; area.y0 = function(_) { if (!arguments.length) return y0; y0 = _; return area; }; area.y1 = function(_) { if (!arguments.length) return y1; y1 = _; return area; }; area.defined = function(_) { if (!arguments.length) return defined; defined = _; return area; }; area.interpolate = function(_) { if (!arguments.length) return interpolateKey; if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; interpolateReverse = interpolate.reverse || interpolate; L = interpolate.closed ? "M" : "L"; return area; }; area.tension = function(_) { if (!arguments.length) return tension; tension = _; return area; }; return area; } d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; d3.svg.area = function() { return d3_svg_area(d3_identity); }; d3.svg.area.radial = function() { var area = d3_svg_area(d3_svg_lineRadial); area.radius = area.x, delete area.x; area.innerRadius = area.x0, delete area.x0; area.outerRadius = area.x1, delete area.x1; area.angle = area.y, delete area.y; area.startAngle = area.y0, delete area.y0; area.endAngle = area.y1, delete area.y1; return area; }; d3.svg.chord = function() { var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; function chord(d, i) { var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; } function subgroup(self, f, d, i) { var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; return { r: r, a0: a0, a1: a1, p0: [ r * Math.cos(a0), r * Math.sin(a0) ], p1: [ r * Math.cos(a1), r * Math.sin(a1) ] }; } function equals(a, b) { return a.a0 == b.a0 && a.a1 == b.a1; } function arc(r, p, a) { return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; } function curve(r0, p0, r1, p1) { return "Q 0,0 " + p1; } chord.radius = function(v) { if (!arguments.length) return radius; radius = d3_functor(v); return chord; }; chord.source = function(v) { if (!arguments.length) return source; source = d3_functor(v); return chord; }; chord.target = function(v) { if (!arguments.length) return target; target = d3_functor(v); return chord; }; chord.startAngle = function(v) { if (!arguments.length) return startAngle; startAngle = d3_functor(v); return chord; }; chord.endAngle = function(v) { if (!arguments.length) return endAngle; endAngle = d3_functor(v); return chord; }; return chord; }; function d3_svg_chordRadius(d) { return d.radius; } d3.svg.diagonal = function() { var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; function diagonal(d, i) { var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { x: p0.x, y: m }, { x: p3.x, y: m }, p3 ]; p = p.map(projection); return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; } diagonal.source = function(x) { if (!arguments.length) return source; source = d3_functor(x); return diagonal; }; diagonal.target = function(x) { if (!arguments.length) return target; target = d3_functor(x); return diagonal; }; diagonal.projection = function(x) { if (!arguments.length) return projection; projection = x; return diagonal; }; return diagonal; }; function d3_svg_diagonalProjection(d) { return [ d.x, d.y ]; } d3.svg.diagonal.radial = function() { var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; diagonal.projection = function(x) { return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; }; return diagonal; }; function d3_svg_diagonalRadialProjection(projection) { return function() { var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; return [ r * Math.cos(a), r * Math.sin(a) ]; }; } d3.svg.symbol = function() { var type = d3_svg_symbolType, size = d3_svg_symbolSize; function symbol(d, i) { return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); } symbol.type = function(x) { if (!arguments.length) return type; type = d3_functor(x); return symbol; }; symbol.size = function(x) { if (!arguments.length) return size; size = d3_functor(x); return symbol; }; return symbol; }; function d3_svg_symbolSize() { return 64; } function d3_svg_symbolType() { return "circle"; } function d3_svg_symbolCircle(size) { var r = Math.sqrt(size / π); return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; } var d3_svg_symbols = d3.map({ circle: d3_svg_symbolCircle, cross: function(size) { var r = Math.sqrt(size / 5) / 2; return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; }, diamond: function(size) { var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; }, square: function(size) { var r = Math.sqrt(size) / 2; return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; }, "triangle-down": function(size) { var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; }, "triangle-up": function(size) { var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; } }); d3.svg.symbolTypes = d3_svg_symbols.keys(); var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); d3_selectionPrototype.transition = function(name) { var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { time: Date.now(), ease: d3_ease_cubicInOut, delay: 0, duration: 250 }; for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); subgroup.push(node); } } return d3_transition(subgroups, ns, id); }; d3_selectionPrototype.interrupt = function(name) { return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); }; var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); function d3_selection_interruptNS(ns) { return function() { var lock, activeId, active; if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { active.timer.c = null; active.timer.t = NaN; if (--lock.count) delete lock[activeId]; else delete this[ns]; lock.active += .5; active.event && active.event.interrupt.call(this, this.__data__, active.index); } }; } function d3_transition(groups, ns, id) { d3_subclass(groups, d3_transitionPrototype); groups.namespace = ns; groups.id = id; return groups; } var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; d3_transitionPrototype.call = d3_selectionPrototype.call; d3_transitionPrototype.empty = d3_selectionPrototype.empty; d3_transitionPrototype.node = d3_selectionPrototype.node; d3_transitionPrototype.size = d3_selectionPrototype.size; d3.transition = function(selection, name) { return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); }; d3.transition.prototype = d3_transitionPrototype; d3_transitionPrototype.select = function(selector) { var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; selector = d3_selection_selector(selector); for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { if ("__data__" in node) subnode.__data__ = node.__data__; d3_transitionNode(subnode, i, ns, id, node[ns][id]); subgroup.push(subnode); } else { subgroup.push(null); } } } return d3_transition(subgroups, ns, id); }; d3_transitionPrototype.selectAll = function(selector) { var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; selector = d3_selection_selectorAll(selector); for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { transition = node[ns][id]; subnodes = selector.call(node, node.__data__, i, j); subgroups.push(subgroup = []); for (var k = -1, o = subnodes.length; ++k < o; ) { if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); subgroup.push(subnode); } } } } return d3_transition(subgroups, ns, id); }; d3_transitionPrototype.filter = function(filter) { var subgroups = [], subgroup, group, node; if (typeof filter !== "function") filter = d3_selection_filter(filter); for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); for (var group = this[j], i = 0, n = group.length; i < n; i++) { if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { subgroup.push(node); } } } return d3_transition(subgroups, this.namespace, this.id); }; d3_transitionPrototype.tween = function(name, tween) { var id = this.id, ns = this.namespace; if (arguments.length < 2) return this.node()[ns][id].tween.get(name); return d3_selection_each(this, tween == null ? function(node) { node[ns][id].tween.remove(name); } : function(node) { node[ns][id].tween.set(name, tween); }); }; function d3_transition_tween(groups, name, value, tween) { var id = groups.id, ns = groups.namespace; return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); } : (value = tween(value), function(node) { node[ns][id].tween.set(name, value); })); } d3_transitionPrototype.attr = function(nameNS, value) { if (arguments.length < 2) { for (value in nameNS) this.attr(value, nameNS[value]); return this; } var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); function attrNull() { this.removeAttribute(name); } function attrNullNS() { this.removeAttributeNS(name.space, name.local); } function attrTween(b) { return b == null ? attrNull : (b += "", function() { var a = this.getAttribute(name), i; return a !== b && (i = interpolate(a, b), function(t) { this.setAttribute(name, i(t)); }); }); } function attrTweenNS(b) { return b == null ? attrNullNS : (b += "", function() { var a = this.getAttributeNS(name.space, name.local), i; return a !== b && (i = interpolate(a, b), function(t) { this.setAttributeNS(name.space, name.local, i(t)); }); }); } return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); }; d3_transitionPrototype.attrTween = function(nameNS, tween) { var name = d3.ns.qualify(nameNS); function attrTween(d, i) { var f = tween.call(this, d, i, this.getAttribute(name)); return f && function(t) { this.setAttribute(name, f(t)); }; } function attrTweenNS(d, i) { var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); return f && function(t) { this.setAttributeNS(name.space, name.local, f(t)); }; } return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); }; d3_transitionPrototype.style = function(name, value, priority) { var n = arguments.length; if (n < 3) { if (typeof name !== "string") { if (n < 2) value = ""; for (priority in name) this.style(priority, name[priority], value); return this; } priority = ""; } function styleNull() { this.style.removeProperty(name); } function styleString(b) { return b == null ? styleNull : (b += "", function() { var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; return a !== b && (i = d3_interpolate(a, b), function(t) { this.style.setProperty(name, i(t), priority); }); }); } return d3_transition_tween(this, "style." + name, value, styleString); }; d3_transitionPrototype.styleTween = function(name, tween, priority) { if (arguments.length < 3) priority = ""; function styleTween(d, i) { var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); return f && function(t) { this.style.setProperty(name, f(t), priority); }; } return this.tween("style." + name, styleTween); }; d3_transitionPrototype.text = function(value) { return d3_transition_tween(this, "text", value, d3_transition_text); }; function d3_transition_text(b) { if (b == null) b = ""; return function() { this.textContent = b; }; } d3_transitionPrototype.remove = function() { var ns = this.namespace; return this.each("end.transition", function() { var p; if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); }); }; d3_transitionPrototype.ease = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].ease; if (typeof value !== "function") value = d3.ease.apply(d3, arguments); return d3_selection_each(this, function(node) { node[ns][id].ease = value; }); }; d3_transitionPrototype.delay = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].delay; return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { node[ns][id].delay = +value.call(node, node.__data__, i, j); } : (value = +value, function(node) { node[ns][id].delay = value; })); }; d3_transitionPrototype.duration = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].duration; return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); } : (value = Math.max(1, value), function(node) { node[ns][id].duration = value; })); }; d3_transitionPrototype.each = function(type, listener) { var id = this.id, ns = this.namespace; if (arguments.length < 2) { var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; try { d3_transitionInheritId = id; d3_selection_each(this, function(node, i, j) { d3_transitionInherit = node[ns][id]; type.call(node, node.__data__, i, j); }); } finally { d3_transitionInherit = inherit; d3_transitionInheritId = inheritId; } } else { d3_selection_each(this, function(node) { var transition = node[ns][id]; (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); }); } return this; }; d3_transitionPrototype.transition = function() { var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); for (var group = this[j], i = 0, n = group.length; i < n; i++) { if (node = group[i]) { transition = node[ns][id0]; d3_transitionNode(node, i, ns, id1, { time: transition.time, ease: transition.ease, delay: transition.delay + transition.duration, duration: transition.duration }); } subgroup.push(node); } } return d3_transition(subgroups, ns, id1); }; function d3_transitionNamespace(name) { return name == null ? "__transition__" : "__transition_" + name + "__"; } function d3_transitionNode(node, i, ns, id, inherit) { var lock = node[ns] || (node[ns] = { active: 0, count: 0 }), transition = lock[id], time, timer, duration, ease, tweens; function schedule(elapsed) { var delay = transition.delay; timer.t = delay + time; if (delay <= elapsed) return start(elapsed - delay); timer.c = start; } function start(elapsed) { var activeId = lock.active, active = lock[activeId]; if (active) { active.timer.c = null; active.timer.t = NaN; --lock.count; delete lock[activeId]; active.event && active.event.interrupt.call(node, node.__data__, active.index); } for (var cancelId in lock) { if (+cancelId < id) { var cancel = lock[cancelId]; cancel.timer.c = null; cancel.timer.t = NaN; --lock.count; delete lock[cancelId]; } } timer.c = tick; d3_timer(function() { if (timer.c && tick(elapsed || 1)) { timer.c = null; timer.t = NaN; } return 1; }, 0, time); lock.active = id; transition.event && transition.event.start.call(node, node.__data__, i); tweens = []; transition.tween.forEach(function(key, value) { if (value = value.call(node, node.__data__, i)) { tweens.push(value); } }); ease = transition.ease; duration = transition.duration; } function tick(elapsed) { var t = elapsed / duration, e = ease(t), n = tweens.length; while (n > 0) { tweens[--n].call(node, e); } if (t >= 1) { transition.event && transition.event.end.call(node, node.__data__, i); if (--lock.count) delete lock[id]; else delete node[ns]; return 1; } } if (!transition) { time = inherit.time; timer = d3_timer(schedule, 0, time); transition = lock[id] = { tween: new d3_Map(), time: time, timer: timer, delay: inherit.delay, duration: inherit.duration, ease: inherit.ease, index: i }; inherit = null; ++lock.count; } } d3.svg.axis = function() { var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; function axis(g) { g.each(function() { var g = d3.select(this); var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), d3.transition(path)); tickEnter.append("line"); tickEnter.append("text"); var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; if (orient === "bottom" || orient === "top") { tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); } else { tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); } lineEnter.attr(y2, sign * innerTickSize); textEnter.attr(y1, sign * tickSpacing); lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); if (scale1.rangeBand) { var x = scale1, dx = x.rangeBand() / 2; scale0 = scale1 = function(d) { return x(d) + dx; }; } else if (scale0.rangeBand) { scale0 = scale1; } else { tickExit.call(tickTransform, scale1, scale0); } tickEnter.call(tickTransform, scale0, scale1); tickUpdate.call(tickTransform, scale1, scale1); }); } axis.scale = function(x) { if (!arguments.length) return scale; scale = x; return axis; }; axis.orient = function(x) { if (!arguments.length) return orient; orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; return axis; }; axis.ticks = function() { if (!arguments.length) return tickArguments_; tickArguments_ = d3_array(arguments); return axis; }; axis.tickValues = function(x) { if (!arguments.length) return tickValues; tickValues = x; return axis; }; axis.tickFormat = function(x) { if (!arguments.length) return tickFormat_; tickFormat_ = x; return axis; }; axis.tickSize = function(x) { var n = arguments.length; if (!n) return innerTickSize; innerTickSize = +x; outerTickSize = +arguments[n - 1]; return axis; }; axis.innerTickSize = function(x) { if (!arguments.length) return innerTickSize; innerTickSize = +x; return axis; }; axis.outerTickSize = function(x) { if (!arguments.length) return outerTickSize; outerTickSize = +x; return axis; }; axis.tickPadding = function(x) { if (!arguments.length) return tickPadding; tickPadding = +x; return axis; }; axis.tickSubdivide = function() { return arguments.length && axis; }; return axis; }; var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { top: 1, right: 1, bottom: 1, left: 1 }; function d3_svg_axisX(selection, x0, x1) { selection.attr("transform", function(d) { var v0 = x0(d); return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; }); } function d3_svg_axisY(selection, y0, y1) { selection.attr("transform", function(d) { var v0 = y0(d); return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; }); } d3.svg.brush = function() { var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; function brush(g) { g.each(function() { var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); var background = g.selectAll(".background").data([ 0 ]); background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); var resize = g.selectAll(".resize").data(resizes, d3_identity); resize.exit().remove(); resize.enter().append("g").attr("class", function(d) { return "resize " + d; }).style("cursor", function(d) { return d3_svg_brushCursor[d]; }).append("rect").attr("x", function(d) { return /[ew]$/.test(d) ? -3 : null; }).attr("y", function(d) { return /^[ns]/.test(d) ? -3 : null; }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); resize.style("display", brush.empty() ? "none" : null); var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; if (x) { range = d3_scaleRange(x); backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); redrawX(gUpdate); } if (y) { range = d3_scaleRange(y); backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); redrawY(gUpdate); } redraw(gUpdate); }); } brush.event = function(g) { g.each(function() { var event_ = event.of(this, arguments), extent1 = { x: xExtent, y: yExtent, i: xExtentDomain, j: yExtentDomain }, extent0 = this.__chart__ || extent1; this.__chart__ = extent1; if (d3_transitionInheritId) { d3.select(this).transition().each("start.brush", function() { xExtentDomain = extent0.i; yExtentDomain = extent0.j; xExtent = extent0.x; yExtent = extent0.y; event_({ type: "brushstart" }); }).tween("brush:brush", function() { var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); xExtentDomain = yExtentDomain = null; return function(t) { xExtent = extent1.x = xi(t); yExtent = extent1.y = yi(t); event_({ type: "brush", mode: "resize" }); }; }).each("end.brush", function() { xExtentDomain = extent1.i; yExtentDomain = extent1.j; event_({ type: "brush", mode: "resize" }); event_({ type: "brushend" }); }); } else { event_({ type: "brushstart" }); event_({ type: "brush", mode: "resize" }); event_({ type: "brushend" }); } }); }; function redraw(g) { g.selectAll(".resize").attr("transform", function(d) { return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; }); } function redrawX(g) { g.select(".extent").attr("x", xExtent[0]); g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); } function redrawY(g) { g.select(".extent").attr("y", yExtent[0]); g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); } function brushstart() { var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset; var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); if (d3.event.changedTouches) { w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); } else { w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); } g.interrupt().selectAll("*").interrupt(); if (dragging) { origin[0] = xExtent[0] - origin[0]; origin[1] = yExtent[0] - origin[1]; } else if (resizing) { var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; origin[0] = xExtent[ex]; origin[1] = yExtent[ey]; } else if (d3.event.altKey) center = origin.slice(); g.style("pointer-events", "none").selectAll(".resize").style("display", null); d3.select("body").style("cursor", eventTarget.style("cursor")); event_({ type: "brushstart" }); brushmove(); function keydown() { if (d3.event.keyCode == 32) { if (!dragging) { center = null; origin[0] -= xExtent[1]; origin[1] -= yExtent[1]; dragging = 2; } d3_eventPreventDefault(); } } function keyup() { if (d3.event.keyCode == 32 && dragging == 2) { origin[0] += xExtent[1]; origin[1] += yExtent[1]; dragging = 0; d3_eventPreventDefault(); } } function brushmove() { var point = d3.mouse(target), moved = false; if (offset) { point[0] += offset[0]; point[1] += offset[1]; } if (!dragging) { if (d3.event.altKey) { if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; origin[0] = xExtent[+(point[0] < center[0])]; origin[1] = yExtent[+(point[1] < center[1])]; } else center = null; } if (resizingX && move1(point, x, 0)) { redrawX(g); moved = true; } if (resizingY && move1(point, y, 1)) { redrawY(g); moved = true; } if (moved) { redraw(g); event_({ type: "brush", mode: dragging ? "move" : "resize" }); } } function move1(point, scale, i) { var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; if (dragging) { r0 -= position; r1 -= size + position; } min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; if (dragging) { max = (min += position) + size; } else { if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); if (position < min) { max = min; min = position; } else { max = position; } } if (extent[0] != min || extent[1] != max) { if (i) yExtentDomain = null; else xExtentDomain = null; extent[0] = min; extent[1] = max; return true; } } function brushend() { brushmove(); g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); d3.select("body").style("cursor", null); w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); dragRestore(); event_({ type: "brushend" }); } } brush.x = function(z) { if (!arguments.length) return x; x = z; resizes = d3_svg_brushResizes[!x << 1 | !y]; return brush; }; brush.y = function(z) { if (!arguments.length) return y; y = z; resizes = d3_svg_brushResizes[!x << 1 | !y]; return brush; }; brush.clamp = function(z) { if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; return brush; }; brush.extent = function(z) { var x0, x1, y0, y1, t; if (!arguments.length) { if (x) { if (xExtentDomain) { x0 = xExtentDomain[0], x1 = xExtentDomain[1]; } else { x0 = xExtent[0], x1 = xExtent[1]; if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; } } if (y) { if (yExtentDomain) { y0 = yExtentDomain[0], y1 = yExtentDomain[1]; } else { y0 = yExtent[0], y1 = yExtent[1]; if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; } } return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; } if (x) { x0 = z[0], x1 = z[1]; if (y) x0 = x0[0], x1 = x1[0]; xExtentDomain = [ x0, x1 ]; if (x.invert) x0 = x(x0), x1 = x(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; } if (y) { y0 = z[0], y1 = z[1]; if (x) y0 = y0[1], y1 = y1[1]; yExtentDomain = [ y0, y1 ]; if (y.invert) y0 = y(y0), y1 = y(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; } return brush; }; brush.clear = function() { if (!brush.empty()) { xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; xExtentDomain = yExtentDomain = null; } return brush; }; brush.empty = function() { return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; }; return d3.rebind(brush, event, "on"); }; var d3_svg_brushCursor = { n: "ns-resize", e: "ew-resize", s: "ns-resize", w: "ew-resize", nw: "nwse-resize", ne: "nesw-resize", se: "nwse-resize", sw: "nesw-resize" }; var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; var d3_time_formatUtc = d3_time_format.utc; var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; function d3_time_formatIsoNative(date) { return date.toISOString(); } d3_time_formatIsoNative.parse = function(string) { var date = new Date(string); return isNaN(date) ? null : date; }; d3_time_formatIsoNative.toString = d3_time_formatIso.toString; d3_time.second = d3_time_interval(function(date) { return new d3_date(Math.floor(date / 1e3) * 1e3); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 1e3); }, function(date) { return date.getSeconds(); }); d3_time.seconds = d3_time.second.range; d3_time.seconds.utc = d3_time.second.utc.range; d3_time.minute = d3_time_interval(function(date) { return new d3_date(Math.floor(date / 6e4) * 6e4); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 6e4); }, function(date) { return date.getMinutes(); }); d3_time.minutes = d3_time.minute.range; d3_time.minutes.utc = d3_time.minute.utc.range; d3_time.hour = d3_time_interval(function(date) { var timezone = date.getTimezoneOffset() / 60; return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 36e5); }, function(date) { return date.getHours(); }); d3_time.hours = d3_time.hour.range; d3_time.hours.utc = d3_time.hour.utc.range; d3_time.month = d3_time_interval(function(date) { date = d3_time.day(date); date.setDate(1); return date; }, function(date, offset) { date.setMonth(date.getMonth() + offset); }, function(date) { return date.getMonth(); }); d3_time.months = d3_time.month.range; d3_time.months.utc = d3_time.month.utc.range; function d3_time_scale(linear, methods, format) { function scale(x) { return linear(x); } scale.invert = function(x) { return d3_time_scaleDate(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return linear.domain().map(d3_time_scaleDate); linear.domain(x); return scale; }; function tickMethod(extent, count) { var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { return d / 31536e6; }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; } scale.nice = function(interval, skip) { var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); if (method) interval = method[0], skip = method[1]; function skipped(date) { return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; } return scale.domain(d3_scale_nice(domain, skip > 1 ? { floor: function(date) { while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); return date; }, ceil: function(date) { while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); return date; } } : interval)); }; scale.ticks = function(interval, skip) { var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { range: interval }, skip ]; if (method) interval = method[0], skip = method[1]; return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); }; scale.tickFormat = function() { return format; }; scale.copy = function() { return d3_time_scale(linear.copy(), methods, format); }; return d3_scale_linearRebind(scale, linear); } function d3_time_scaleDate(t) { return new Date(t); } var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { return d.getMilliseconds(); } ], [ ":%S", function(d) { return d.getSeconds(); } ], [ "%I:%M", function(d) { return d.getMinutes(); } ], [ "%I %p", function(d) { return d.getHours(); } ], [ "%a %d", function(d) { return d.getDay() && d.getDate() != 1; } ], [ "%b %d", function(d) { return d.getDate() != 1; } ], [ "%B", function(d) { return d.getMonth(); } ], [ "%Y", d3_true ] ]); var d3_time_scaleMilliseconds = { range: function(start, stop, step) { return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); }, floor: d3_identity, ceil: d3_identity }; d3_time_scaleLocalMethods.year = d3_time.year; d3_time.scale = function() { return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); }; var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { return [ m[0].utc, m[1] ]; }); var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { return d.getUTCMilliseconds(); } ], [ ":%S", function(d) { return d.getUTCSeconds(); } ], [ "%I:%M", function(d) { return d.getUTCMinutes(); } ], [ "%I %p", function(d) { return d.getUTCHours(); } ], [ "%a %d", function(d) { return d.getUTCDay() && d.getUTCDate() != 1; } ], [ "%b %d", function(d) { return d.getUTCDate() != 1; } ], [ "%B", function(d) { return d.getUTCMonth(); } ], [ "%Y", d3_true ] ]); d3_time_scaleUtcMethods.year = d3_time.year.utc; d3_time.scale.utc = function() { return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); }; d3.text = d3_xhrType(function(request) { return request.responseText; }); d3.json = function(url, callback) { return d3_xhr(url, "application/json", d3_json, callback); }; function d3_json(request) { return JSON.parse(request.responseText); } d3.html = function(url, callback) { return d3_xhr(url, "text/html", d3_html, callback); }; function d3_html(request) { var range = d3_document.createRange(); range.selectNode(d3_document.body); return range.createContextualFragment(request.responseText); } d3.xml = d3_xhrType(function(request) { return request.responseXML; }); if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; }(); // UMD (Universal Module Definition) // See https://github.com/umdjs/umd for reference // // This file uses the following specific UMD implementation: // https://github.com/umdjs/umd/blob/master/returnExports.js (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.computeLayout = factory(); } }(this, function() { /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ var computeLayout = (function() { var CSS_UNDEFINED; var CSS_DIRECTION_INHERIT = 'inherit'; var CSS_DIRECTION_LTR = 'ltr'; var CSS_DIRECTION_RTL = 'rtl'; var CSS_FLEX_DIRECTION_ROW = 'row'; var CSS_FLEX_DIRECTION_ROW_REVERSE = 'row-reverse'; var CSS_FLEX_DIRECTION_COLUMN = 'column'; var CSS_FLEX_DIRECTION_COLUMN_REVERSE = 'column-reverse'; var CSS_JUSTIFY_FLEX_START = 'flex-start'; var CSS_JUSTIFY_CENTER = 'center'; var CSS_JUSTIFY_FLEX_END = 'flex-end'; var CSS_JUSTIFY_SPACE_BETWEEN = 'space-between'; var CSS_JUSTIFY_SPACE_AROUND = 'space-around'; var CSS_ALIGN_FLEX_START = 'flex-start'; var CSS_ALIGN_CENTER = 'center'; var CSS_ALIGN_FLEX_END = 'flex-end'; var CSS_ALIGN_STRETCH = 'stretch'; var CSS_POSITION_RELATIVE = 'relative'; var CSS_POSITION_ABSOLUTE = 'absolute'; var leading = { 'row': 'left', 'row-reverse': 'right', 'column': 'top', 'column-reverse': 'bottom' }; var trailing = { 'row': 'right', 'row-reverse': 'left', 'column': 'bottom', 'column-reverse': 'top' }; var pos = { 'row': 'left', 'row-reverse': 'right', 'column': 'top', 'column-reverse': 'bottom' }; var dim = { 'row': 'width', 'row-reverse': 'width', 'column': 'height', 'column-reverse': 'height' }; // When transpiled to Java / C the node type has layout, children and style // properties. For the JavaScript version this function adds these properties // if they don't already exist. function fillNodes(node) { if (!node.layout || node.isDirty) { node.layout = { width: undefined, height: undefined, top: 0, left: 0, right: 0, bottom: 0 }; } if (!node.style) { node.style = {}; } if (!node.children) { node.children = []; } node.children.forEach(fillNodes); return node; } function isUndefined(value) { return value === undefined; } function isRowDirection(flexDirection) { return flexDirection === CSS_FLEX_DIRECTION_ROW || flexDirection === CSS_FLEX_DIRECTION_ROW_REVERSE; } function isColumnDirection(flexDirection) { return flexDirection === CSS_FLEX_DIRECTION_COLUMN || flexDirection === CSS_FLEX_DIRECTION_COLUMN_REVERSE; } function getLeadingMargin(node, axis) { if (node.style.marginStart !== undefined && isRowDirection(axis)) { return node.style.marginStart; } var value = null; switch (axis) { case 'row': value = node.style.marginLeft; break; case 'row-reverse': value = node.style.marginRight; break; case 'column': value = node.style.marginTop; break; case 'column-reverse': value = node.style.marginBottom; break; } if (value !== undefined) { return value; } if (node.style.margin !== undefined) { return node.style.margin; } return 0; } function getTrailingMargin(node, axis) { if (node.style.marginEnd !== undefined && isRowDirection(axis)) { return node.style.marginEnd; } var value = null; switch (axis) { case 'row': value = node.style.marginRight; break; case 'row-reverse': value = node.style.marginLeft; break; case 'column': value = node.style.marginBottom; break; case 'column-reverse': value = node.style.marginTop; break; } if (value != null) { return value; } if (node.style.margin !== undefined) { return node.style.margin; } return 0; } function getLeadingPadding(node, axis) { if (node.style.paddingStart !== undefined && node.style.paddingStart >= 0 && isRowDirection(axis)) { return node.style.paddingStart; } var value = null; switch (axis) { case 'row': value = node.style.paddingLeft; break; case 'row-reverse': value = node.style.paddingRight; break; case 'column': value = node.style.paddingTop; break; case 'column-reverse': value = node.style.paddingBottom; break; } if (value != null && value >= 0) { return value; } if (node.style.padding !== undefined && node.style.padding >= 0) { return node.style.padding; } return 0; } function getTrailingPadding(node, axis) { if (node.style.paddingEnd !== undefined && node.style.paddingEnd >= 0 && isRowDirection(axis)) { return node.style.paddingEnd; } var value = null; switch (axis) { case 'row': value = node.style.paddingRight; break; case 'row-reverse': value = node.style.paddingLeft; break; case 'column': value = node.style.paddingBottom; break; case 'column-reverse': value = node.style.paddingTop; break; } if (value != null && value >= 0) { return value; } if (node.style.padding !== undefined && node.style.padding >= 0) { return node.style.padding; } return 0; } function getLeadingBorder(node, axis) { if (node.style.borderStartWidth !== undefined && node.style.borderStartWidth >= 0 && isRowDirection(axis)) { return node.style.borderStartWidth; } var value = null; switch (axis) { case 'row': value = node.style.borderLeftWidth; break; case 'row-reverse': value = node.style.borderRightWidth; break; case 'column': value = node.style.borderTopWidth; break; case 'column-reverse': value = node.style.borderBottomWidth; break; } if (value != null && value >= 0) { return value; } if (node.style.borderWidth !== undefined && node.style.borderWidth >= 0) { return node.style.borderWidth; } return 0; } function getTrailingBorder(node, axis) { if (node.style.borderEndWidth !== undefined && node.style.borderEndWidth >= 0 && isRowDirection(axis)) { return node.style.borderEndWidth; } var value = null; switch (axis) { case 'row': value = node.style.borderRightWidth; break; case 'row-reverse': value = node.style.borderLeftWidth; break; case 'column': value = node.style.borderBottomWidth; break; case 'column-reverse': value = node.style.borderTopWidth; break; } if (value != null && value >= 0) { return value; } if (node.style.borderWidth !== undefined && node.style.borderWidth >= 0) { return node.style.borderWidth; } return 0; } function getLeadingPaddingAndBorder(node, axis) { return getLeadingPadding(node, axis) + getLeadingBorder(node, axis); } function getTrailingPaddingAndBorder(node, axis) { return getTrailingPadding(node, axis) + getTrailingBorder(node, axis); } function getBorderAxis(node, axis) { return getLeadingBorder(node, axis) + getTrailingBorder(node, axis); } function getMarginAxis(node, axis) { return getLeadingMargin(node, axis) + getTrailingMargin(node, axis); } function getPaddingAndBorderAxis(node, axis) { return getLeadingPaddingAndBorder(node, axis) + getTrailingPaddingAndBorder(node, axis); } function getJustifyContent(node) { if (node.style.justifyContent) { return node.style.justifyContent; } return 'flex-start'; } function getAlignContent(node) { if (node.style.alignContent) { return node.style.alignContent; } return 'flex-start'; } function getAlignItem(node, child) { if (child.style.alignSelf) { return child.style.alignSelf; } if (node.style.alignItems) { return node.style.alignItems; } return 'stretch'; } function resolveAxis(axis, direction) { if (direction === CSS_DIRECTION_RTL) { if (axis === CSS_FLEX_DIRECTION_ROW) { return CSS_FLEX_DIRECTION_ROW_REVERSE; } else if (axis === CSS_FLEX_DIRECTION_ROW_REVERSE) { return CSS_FLEX_DIRECTION_ROW; } } return axis; } function resolveDirection(node, parentDirection) { var direction; if (node.style.direction) { direction = node.style.direction; } else { direction = CSS_DIRECTION_INHERIT; } if (direction === CSS_DIRECTION_INHERIT) { direction = (parentDirection === undefined ? CSS_DIRECTION_LTR : parentDirection); } return direction; } function getFlexDirection(node) { if (node.style.flexDirection) { return node.style.flexDirection; } return CSS_FLEX_DIRECTION_COLUMN; } function getCrossFlexDirection(flexDirection, direction) { if (isColumnDirection(flexDirection)) { return resolveAxis(CSS_FLEX_DIRECTION_ROW, direction); } else { return CSS_FLEX_DIRECTION_COLUMN; } } function getPositionType(node) { if (node.style.position) { return node.style.position; } return 'relative'; } function isFlex(node) { return ( getPositionType(node) === CSS_POSITION_RELATIVE && node.style.flex > 0 ); } function isFlexWrap(node) { return node.style.flexWrap === 'wrap'; } function getDimWithMargin(node, axis) { return node.layout[dim[axis]] + getMarginAxis(node, axis); } function isDimDefined(node, axis) { return node.style[dim[axis]] !== undefined && node.style[dim[axis]] >= 0; } function isPosDefined(node, pos) { return node.style[pos] !== undefined; } function isMeasureDefined(node) { return node.style.measure !== undefined; } function getPosition(node, pos) { if (node.style[pos] !== undefined) { return node.style[pos]; } return 0; } function boundAxis(node, axis, value) { var min = { 'row': node.style.minWidth, 'row-reverse': node.style.minWidth, 'column': node.style.minHeight, 'column-reverse': node.style.minHeight }[axis]; var max = { 'row': node.style.maxWidth, 'row-reverse': node.style.maxWidth, 'column': node.style.maxHeight, 'column-reverse': node.style.maxHeight }[axis]; var boundValue = value; if (max !== undefined && max >= 0 && boundValue > max) { boundValue = max; } if (min !== undefined && min >= 0 && boundValue < min) { boundValue = min; } return boundValue; } function fmaxf(a, b) { if (a > b) { return a; } return b; } // When the user specifically sets a value for width or height function setDimensionFromStyle(node, axis) { // The parent already computed us a width or height. We just skip it if (node.layout[dim[axis]] !== undefined) { return; } // We only run if there's a width or height defined if (!isDimDefined(node, axis)) { return; } // The dimensions can never be smaller than the padding and border node.layout[dim[axis]] = fmaxf( boundAxis(node, axis, node.style[dim[axis]]), getPaddingAndBorderAxis(node, axis) ); } function setTrailingPosition(node, child, axis) { child.layout[trailing[axis]] = node.layout[dim[axis]] - child.layout[dim[axis]] - child.layout[pos[axis]]; } // If both left and right are defined, then use left. Otherwise return // +left or -right depending on which is defined. function getRelativePosition(node, axis) { if (node.style[leading[axis]] !== undefined) { return getPosition(node, leading[axis]); } return -getPosition(node, trailing[axis]); } function layoutNodeImpl(node, parentMaxWidth, /*css_direction_t*/parentDirection) { var/*css_direction_t*/ direction = resolveDirection(node, parentDirection); var/*(c)!css_flex_direction_t*//*(java)!int*/ mainAxis = resolveAxis(getFlexDirection(node), direction); var/*(c)!css_flex_direction_t*//*(java)!int*/ crossAxis = getCrossFlexDirection(mainAxis, direction); var/*(c)!css_flex_direction_t*//*(java)!int*/ resolvedRowAxis = resolveAxis(CSS_FLEX_DIRECTION_ROW, direction); // Handle width and height style attributes setDimensionFromStyle(node, mainAxis); setDimensionFromStyle(node, crossAxis); // Set the resolved resolution in the node's layout node.layout.direction = direction; // The position is set by the parent, but we need to complete it with a // delta composed of the margin and left/top/right/bottom node.layout[leading[mainAxis]] += getLeadingMargin(node, mainAxis) + getRelativePosition(node, mainAxis); node.layout[trailing[mainAxis]] += getTrailingMargin(node, mainAxis) + getRelativePosition(node, mainAxis); node.layout[leading[crossAxis]] += getLeadingMargin(node, crossAxis) + getRelativePosition(node, crossAxis); node.layout[trailing[crossAxis]] += getTrailingMargin(node, crossAxis) + getRelativePosition(node, crossAxis); // Inline immutable values from the target node to avoid excessive method // invocations during the layout calculation. var/*int*/ childCount = node.children.length; var/*float*/ paddingAndBorderAxisResolvedRow = getPaddingAndBorderAxis(node, resolvedRowAxis); if (isMeasureDefined(node)) { var/*bool*/ isResolvedRowDimDefined = !isUndefined(node.layout[dim[resolvedRowAxis]]); var/*float*/ width = CSS_UNDEFINED; if (isDimDefined(node, resolvedRowAxis)) { width = node.style.width; } else if (isResolvedRowDimDefined) { width = node.layout[dim[resolvedRowAxis]]; } else { width = parentMaxWidth - getMarginAxis(node, resolvedRowAxis); } width -= paddingAndBorderAxisResolvedRow; // We only need to give a dimension for the text if we haven't got any // for it computed yet. It can either be from the style attribute or because // the element is flexible. var/*bool*/ isRowUndefined = !isDimDefined(node, resolvedRowAxis) && !isResolvedRowDimDefined; var/*bool*/ isColumnUndefined = !isDimDefined(node, CSS_FLEX_DIRECTION_COLUMN) && isUndefined(node.layout[dim[CSS_FLEX_DIRECTION_COLUMN]]); // Let's not measure the text if we already know both dimensions if (isRowUndefined || isColumnUndefined) { var/*css_dim_t*/ measureDim = node.style.measure( /*(c)!node->context,*/ /*(java)!layoutContext.measureOutput,*/ width ); if (isRowUndefined) { node.layout.width = measureDim.width + paddingAndBorderAxisResolvedRow; } if (isColumnUndefined) { node.layout.height = measureDim.height + getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_COLUMN); } } if (childCount === 0) { return; } } var/*bool*/ isNodeFlexWrap = isFlexWrap(node); var/*css_justify_t*/ justifyContent = getJustifyContent(node); var/*float*/ leadingPaddingAndBorderMain = getLeadingPaddingAndBorder(node, mainAxis); var/*float*/ leadingPaddingAndBorderCross = getLeadingPaddingAndBorder(node, crossAxis); var/*float*/ paddingAndBorderAxisMain = getPaddingAndBorderAxis(node, mainAxis); var/*float*/ paddingAndBorderAxisCross = getPaddingAndBorderAxis(node, crossAxis); var/*bool*/ isMainDimDefined = !isUndefined(node.layout[dim[mainAxis]]); var/*bool*/ isCrossDimDefined = !isUndefined(node.layout[dim[crossAxis]]); var/*bool*/ isMainRowDirection = isRowDirection(mainAxis); var/*int*/ i; var/*int*/ ii; var/*css_node_t**/ child; var/*(c)!css_flex_direction_t*//*(java)!int*/ axis; var/*css_node_t**/ firstAbsoluteChild = null; var/*css_node_t**/ currentAbsoluteChild = null; var/*float*/ definedMainDim = CSS_UNDEFINED; if (isMainDimDefined) { definedMainDim = node.layout[dim[mainAxis]] - paddingAndBorderAxisMain; } // We want to execute the next two loops one per line with flex-wrap var/*int*/ startLine = 0; var/*int*/ endLine = 0; // var/*int*/ nextOffset = 0; var/*int*/ alreadyComputedNextLayout = 0; // We aggregate the total dimensions of the container in those two variables var/*float*/ linesCrossDim = 0; var/*float*/ linesMainDim = 0; var/*int*/ linesCount = 0; while (endLine < childCount) { // <Loop A> Layout non flexible children and count children by type // mainContentDim is accumulation of the dimensions and margin of all the // non flexible children. This will be used in order to either set the // dimensions of the node if none already exist, or to compute the // remaining space left for the flexible children. var/*float*/ mainContentDim = 0; // There are three kind of children, non flexible, flexible and absolute. // We need to know how many there are in order to distribute the space. var/*int*/ flexibleChildrenCount = 0; var/*float*/ totalFlexible = 0; var/*int*/ nonFlexibleChildrenCount = 0; // Use the line loop to position children in the main axis for as long // as they are using a simple stacking behaviour. Children that are // immediately stacked in the initial loop will not be touched again // in <Loop C>. var/*bool*/ isSimpleStackMain = (isMainDimDefined && justifyContent === CSS_JUSTIFY_FLEX_START) || (!isMainDimDefined && justifyContent !== CSS_JUSTIFY_CENTER); var/*int*/ firstComplexMain = (isSimpleStackMain ? childCount : startLine); // Use the initial line loop to position children in the cross axis for // as long as they are relatively positioned with alignment STRETCH or // FLEX_START. Children that are immediately stacked in the initial loop // will not be touched again in <Loop D>. var/*bool*/ isSimpleStackCross = true; var/*int*/ firstComplexCross = childCount; var/*css_node_t**/ firstFlexChild = null; var/*css_node_t**/ currentFlexChild = null; var/*float*/ mainDim = leadingPaddingAndBorderMain; var/*float*/ crossDim = 0; var/*float*/ maxWidth; for (i = startLine; i < childCount; ++i) { child = node.children[i]; child.lineIndex = linesCount; child.nextAbsoluteChild = null; child.nextFlexChild = null; var/*css_align_t*/ alignItem = getAlignItem(node, child); // Pre-fill cross axis dimensions when the child is using stretch before // we call the recursive layout pass if (alignItem === CSS_ALIGN_STRETCH && getPositionType(child) === CSS_POSITION_RELATIVE && isCrossDimDefined && !isDimDefined(child, crossAxis)) { child.layout[dim[crossAxis]] = fmaxf( boundAxis(child, crossAxis, node.layout[dim[crossAxis]] - paddingAndBorderAxisCross - getMarginAxis(child, crossAxis)), // You never want to go smaller than padding getPaddingAndBorderAxis(child, crossAxis) ); } else if (getPositionType(child) === CSS_POSITION_ABSOLUTE) { // Store a private linked list of absolutely positioned children // so that we can efficiently traverse them later. if (firstAbsoluteChild === null) { firstAbsoluteChild = child; } if (currentAbsoluteChild !== null) { currentAbsoluteChild.nextAbsoluteChild = child; } currentAbsoluteChild = child; // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both // left and right or top and bottom). for (ii = 0; ii < 2; ii++) { axis = (ii !== 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN; if (!isUndefined(node.layout[dim[axis]]) && !isDimDefined(child, axis) && isPosDefined(child, leading[axis]) && isPosDefined(child, trailing[axis])) { child.layout[dim[axis]] = fmaxf( boundAxis(child, axis, node.layout[dim[axis]] - getPaddingAndBorderAxis(node, axis) - getMarginAxis(child, axis) - getPosition(child, leading[axis]) - getPosition(child, trailing[axis])), // You never want to go smaller than padding getPaddingAndBorderAxis(child, axis) ); } } } var/*float*/ nextContentDim = 0; // It only makes sense to consider a child flexible if we have a computed // dimension for the node. if (isMainDimDefined && isFlex(child)) { flexibleChildrenCount++; totalFlexible += child.style.flex; // Store a private linked list of flexible children so that we can // efficiently traverse them later. if (firstFlexChild === null) { firstFlexChild = child; } if (currentFlexChild !== null) { currentFlexChild.nextFlexChild = child; } currentFlexChild = child; // Even if we don't know its exact size yet, we already know the padding, // border and margin. We'll use this partial information, which represents // the smallest possible size for the child, to compute the remaining // available space. nextContentDim = getPaddingAndBorderAxis(child, mainAxis) + getMarginAxis(child, mainAxis); } else { maxWidth = CSS_UNDEFINED; if (!isMainRowDirection) { if (isDimDefined(node, resolvedRowAxis)) { maxWidth = node.layout[dim[resolvedRowAxis]] - paddingAndBorderAxisResolvedRow; } else { maxWidth = parentMaxWidth - getMarginAxis(node, resolvedRowAxis) - paddingAndBorderAxisResolvedRow; } } // This is the main recursive call. We layout non flexible children. if (alreadyComputedNextLayout === 0) { layoutNode(/*(java)!layoutContext, */child, maxWidth, direction); } // Absolute positioned elements do not take part of the layout, so we // don't use them to compute mainContentDim if (getPositionType(child) === CSS_POSITION_RELATIVE) { nonFlexibleChildrenCount++; // At this point we know the final size and margin of the element. nextContentDim = getDimWithMargin(child, mainAxis); } } // The element we are about to add would make us go to the next line if (isNodeFlexWrap && isMainDimDefined && mainContentDim + nextContentDim > definedMainDim && // If there's only one element, then it's bigger than the content // and needs its own line i !== startLine) { nonFlexibleChildrenCount--; alreadyComputedNextLayout = 1; break; } // Disable simple stacking in the main axis for the current line as // we found a non-trivial child. The remaining children will be laid out // in <Loop C>. if (isSimpleStackMain && (getPositionType(child) !== CSS_POSITION_RELATIVE || isFlex(child))) { isSimpleStackMain = false; firstComplexMain = i; } // Disable simple stacking in the cross axis for the current line as // we found a non-trivial child. The remaining children will be laid out // in <Loop D>. if (isSimpleStackCross && (getPositionType(child) !== CSS_POSITION_RELATIVE || (alignItem !== CSS_ALIGN_STRETCH && alignItem !== CSS_ALIGN_FLEX_START) || isUndefined(child.layout[dim[crossAxis]]))) { isSimpleStackCross = false; firstComplexCross = i; } if (isSimpleStackMain) { child.layout[pos[mainAxis]] += mainDim; if (isMainDimDefined) { setTrailingPosition(node, child, mainAxis); } mainDim += getDimWithMargin(child, mainAxis); crossDim = fmaxf(crossDim, boundAxis(child, crossAxis, getDimWithMargin(child, crossAxis))); } if (isSimpleStackCross) { child.layout[pos[crossAxis]] += linesCrossDim + leadingPaddingAndBorderCross; if (isCrossDimDefined) { setTrailingPosition(node, child, crossAxis); } } alreadyComputedNextLayout = 0; mainContentDim += nextContentDim; endLine = i + 1; } // <Loop B> Layout flexible children and allocate empty space // In order to position the elements in the main axis, we have two // controls. The space between the beginning and the first element // and the space between each two elements. var/*float*/ leadingMainDim = 0; var/*float*/ betweenMainDim = 0; // The remaining available space that needs to be allocated var/*float*/ remainingMainDim = 0; if (isMainDimDefined) { remainingMainDim = definedMainDim - mainContentDim; } else { remainingMainDim = fmaxf(mainContentDim, 0) - mainContentDim; } // If there are flexible children in the mix, they are going to fill the // remaining space if (flexibleChildrenCount !== 0) { var/*float*/ flexibleMainDim = remainingMainDim / totalFlexible; var/*float*/ baseMainDim; var/*float*/ boundMainDim; // If the flex share of remaining space doesn't meet min/max bounds, // remove this child from flex calculations. currentFlexChild = firstFlexChild; while (currentFlexChild !== null) { baseMainDim = flexibleMainDim * currentFlexChild.style.flex + getPaddingAndBorderAxis(currentFlexChild, mainAxis); boundMainDim = boundAxis(currentFlexChild, mainAxis, baseMainDim); if (baseMainDim !== boundMainDim) { remainingMainDim -= boundMainDim; totalFlexible -= currentFlexChild.style.flex; } currentFlexChild = currentFlexChild.nextFlexChild; } flexibleMainDim = remainingMainDim / totalFlexible; // The non flexible children can overflow the container, in this case // we should just assume that there is no space available. if (flexibleMainDim < 0) { flexibleMainDim = 0; } currentFlexChild = firstFlexChild; while (currentFlexChild !== null) { // At this point we know the final size of the element in the main // dimension currentFlexChild.layout[dim[mainAxis]] = boundAxis(currentFlexChild, mainAxis, flexibleMainDim * currentFlexChild.style.flex + getPaddingAndBorderAxis(currentFlexChild, mainAxis) ); maxWidth = CSS_UNDEFINED; if (isDimDefined(node, resolvedRowAxis)) { maxWidth = node.layout[dim[resolvedRowAxis]] - paddingAndBorderAxisResolvedRow; } else if (!isMainRowDirection) { maxWidth = parentMaxWidth - getMarginAxis(node, resolvedRowAxis) - paddingAndBorderAxisResolvedRow; } // And we recursively call the layout algorithm for this child layoutNode(/*(java)!layoutContext, */currentFlexChild, maxWidth, direction); child = currentFlexChild; currentFlexChild = currentFlexChild.nextFlexChild; child.nextFlexChild = null; } // We use justifyContent to figure out how to allocate the remaining // space available } else if (justifyContent !== CSS_JUSTIFY_FLEX_START) { if (justifyContent === CSS_JUSTIFY_CENTER) { leadingMainDim = remainingMainDim / 2; } else if (justifyContent === CSS_JUSTIFY_FLEX_END) { leadingMainDim = remainingMainDim; } else if (justifyContent === CSS_JUSTIFY_SPACE_BETWEEN) { remainingMainDim = fmaxf(remainingMainDim, 0); if (flexibleChildrenCount + nonFlexibleChildrenCount - 1 !== 0) { betweenMainDim = remainingMainDim / (flexibleChildrenCount + nonFlexibleChildrenCount - 1); } else { betweenMainDim = 0; } } else if (justifyContent === CSS_JUSTIFY_SPACE_AROUND) { // Space on the edges is half of the space between elements betweenMainDim = remainingMainDim / (flexibleChildrenCount + nonFlexibleChildrenCount); leadingMainDim = betweenMainDim / 2; } } // <Loop C> Position elements in the main axis and compute dimensions // At this point, all the children have their dimensions set. We need to // find their position. In order to do that, we accumulate data in // variables that are also useful to compute the total dimensions of the // container! mainDim += leadingMainDim; for (i = firstComplexMain; i < endLine; ++i) { child = node.children[i]; if (getPositionType(child) === CSS_POSITION_ABSOLUTE && isPosDefined(child, leading[mainAxis])) { // In case the child is position absolute and has left/top being // defined, we override the position to whatever the user said // (and margin/border). child.layout[pos[mainAxis]] = getPosition(child, leading[mainAxis]) + getLeadingBorder(node, mainAxis) + getLeadingMargin(child, mainAxis); } else { // If the child is position absolute (without top/left) or relative, // we put it at the current accumulated offset. child.layout[pos[mainAxis]] += mainDim; // Define the trailing position accordingly. if (isMainDimDefined) { setTrailingPosition(node, child, mainAxis); } // Now that we placed the element, we need to update the variables // We only need to do that for relative elements. Absolute elements // do not take part in that phase. if (getPositionType(child) === CSS_POSITION_RELATIVE) { // The main dimension is the sum of all the elements dimension plus // the spacing. mainDim += betweenMainDim + getDimWithMargin(child, mainAxis); // The cross dimension is the max of the elements dimension since there // can only be one element in that cross dimension. crossDim = fmaxf(crossDim, boundAxis(child, crossAxis, getDimWithMargin(child, crossAxis))); } } } var/*float*/ containerCrossAxis = node.layout[dim[crossAxis]]; if (!isCrossDimDefined) { containerCrossAxis = fmaxf( // For the cross dim, we add both sides at the end because the value // is aggregate via a max function. Intermediate negative values // can mess this computation otherwise boundAxis(node, crossAxis, crossDim + paddingAndBorderAxisCross), paddingAndBorderAxisCross ); } // <Loop D> Position elements in the cross axis for (i = firstComplexCross; i < endLine; ++i) { child = node.children[i]; if (getPositionType(child) === CSS_POSITION_ABSOLUTE && isPosDefined(child, leading[crossAxis])) { // In case the child is absolutely positionned and has a // top/left/bottom/right being set, we override all the previously // computed positions to set it correctly. child.layout[pos[crossAxis]] = getPosition(child, leading[crossAxis]) + getLeadingBorder(node, crossAxis) + getLeadingMargin(child, crossAxis); } else { var/*float*/ leadingCrossDim = leadingPaddingAndBorderCross; // For a relative children, we're either using alignItems (parent) or // alignSelf (child) in order to determine the position in the cross axis if (getPositionType(child) === CSS_POSITION_RELATIVE) { /*eslint-disable */ // This variable is intentionally re-defined as the code is transpiled to a block scope language var/*css_align_t*/ alignItem = getAlignItem(node, child); /*eslint-enable */ if (alignItem === CSS_ALIGN_STRETCH) { // You can only stretch if the dimension has not already been set // previously. if (isUndefined(child.layout[dim[crossAxis]])) { child.layout[dim[crossAxis]] = fmaxf( boundAxis(child, crossAxis, containerCrossAxis - paddingAndBorderAxisCross - getMarginAxis(child, crossAxis)), // You never want to go smaller than padding getPaddingAndBorderAxis(child, crossAxis) ); } } else if (alignItem !== CSS_ALIGN_FLEX_START) { // The remaining space between the parent dimensions+padding and child // dimensions+margin. var/*float*/ remainingCrossDim = containerCrossAxis - paddingAndBorderAxisCross - getDimWithMargin(child, crossAxis); if (alignItem === CSS_ALIGN_CENTER) { leadingCrossDim += remainingCrossDim / 2; } else { // CSS_ALIGN_FLEX_END leadingCrossDim += remainingCrossDim; } } } // And we apply the position child.layout[pos[crossAxis]] += linesCrossDim + leadingCrossDim; // Define the trailing position accordingly. if (isCrossDimDefined) { setTrailingPosition(node, child, crossAxis); } } } linesCrossDim += crossDim; linesMainDim = fmaxf(linesMainDim, mainDim); linesCount += 1; startLine = endLine; } // <Loop E> // // Note(prenaux): More than one line, we need to layout the crossAxis // according to alignContent. // // Note that we could probably remove <Loop D> and handle the one line case // here too, but for the moment this is safer since it won't interfere with // previously working code. // // See specs: // http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#layout-algorithm // section 9.4 // if (linesCount > 1 && isCrossDimDefined) { var/*float*/ nodeCrossAxisInnerSize = node.layout[dim[crossAxis]] - paddingAndBorderAxisCross; var/*float*/ remainingAlignContentDim = nodeCrossAxisInnerSize - linesCrossDim; var/*float*/ crossDimLead = 0; var/*float*/ currentLead = leadingPaddingAndBorderCross; var/*css_align_t*/ alignContent = getAlignContent(node); if (alignContent === CSS_ALIGN_FLEX_END) { currentLead += remainingAlignContentDim; } else if (alignContent === CSS_ALIGN_CENTER) { currentLead += remainingAlignContentDim / 2; } else if (alignContent === CSS_ALIGN_STRETCH) { if (nodeCrossAxisInnerSize > linesCrossDim) { crossDimLead = (remainingAlignContentDim / linesCount); } } var/*int*/ endIndex = 0; for (i = 0; i < linesCount; ++i) { var/*int*/ startIndex = endIndex; // compute the line's height and find the endIndex var/*float*/ lineHeight = 0; for (ii = startIndex; ii < childCount; ++ii) { child = node.children[ii]; if (getPositionType(child) !== CSS_POSITION_RELATIVE) { continue; } if (child.lineIndex !== i) { break; } if (!isUndefined(child.layout[dim[crossAxis]])) { lineHeight = fmaxf( lineHeight, child.layout[dim[crossAxis]] + getMarginAxis(child, crossAxis) ); } } endIndex = ii; lineHeight += crossDimLead; for (ii = startIndex; ii < endIndex; ++ii) { child = node.children[ii]; if (getPositionType(child) !== CSS_POSITION_RELATIVE) { continue; } var/*css_align_t*/ alignContentAlignItem = getAlignItem(node, child); if (alignContentAlignItem === CSS_ALIGN_FLEX_START) { child.layout[pos[crossAxis]] = currentLead + getLeadingMargin(child, crossAxis); } else if (alignContentAlignItem === CSS_ALIGN_FLEX_END) { child.layout[pos[crossAxis]] = currentLead + lineHeight - getTrailingMargin(child, crossAxis) - child.layout[dim[crossAxis]]; } else if (alignContentAlignItem === CSS_ALIGN_CENTER) { var/*float*/ childHeight = child.layout[dim[crossAxis]]; child.layout[pos[crossAxis]] = currentLead + (lineHeight - childHeight) / 2; } else if (alignContentAlignItem === CSS_ALIGN_STRETCH) { child.layout[pos[crossAxis]] = currentLead + getLeadingMargin(child, crossAxis); // TODO(prenaux): Correctly set the height of items with undefined // (auto) crossAxis dimension. } } currentLead += lineHeight; } } var/*bool*/ needsMainTrailingPos = false; var/*bool*/ needsCrossTrailingPos = false; // If the user didn't specify a width or height, and it has not been set // by the container, then we set it via the children. if (!isMainDimDefined) { node.layout[dim[mainAxis]] = fmaxf( // We're missing the last padding at this point to get the final // dimension boundAxis(node, mainAxis, linesMainDim + getTrailingPaddingAndBorder(node, mainAxis)), // We can never assign a width smaller than the padding and borders paddingAndBorderAxisMain ); if (mainAxis === CSS_FLEX_DIRECTION_ROW_REVERSE || mainAxis === CSS_FLEX_DIRECTION_COLUMN_REVERSE) { needsMainTrailingPos = true; } } if (!isCrossDimDefined) { node.layout[dim[crossAxis]] = fmaxf( // For the cross dim, we add both sides at the end because the value // is aggregate via a max function. Intermediate negative values // can mess this computation otherwise boundAxis(node, crossAxis, linesCrossDim + paddingAndBorderAxisCross), paddingAndBorderAxisCross ); if (crossAxis === CSS_FLEX_DIRECTION_ROW_REVERSE || crossAxis === CSS_FLEX_DIRECTION_COLUMN_REVERSE) { needsCrossTrailingPos = true; } } // <Loop F> Set trailing position if necessary if (needsMainTrailingPos || needsCrossTrailingPos) { for (i = 0; i < childCount; ++i) { child = node.children[i]; if (needsMainTrailingPos) { setTrailingPosition(node, child, mainAxis); } if (needsCrossTrailingPos) { setTrailingPosition(node, child, crossAxis); } } } // <Loop G> Calculate dimensions for absolutely positioned elements currentAbsoluteChild = firstAbsoluteChild; while (currentAbsoluteChild !== null) { // Pre-fill dimensions when using absolute position and both offsets for // the axis are defined (either both left and right or top and bottom). for (ii = 0; ii < 2; ii++) { axis = (ii !== 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN; if (!isUndefined(node.layout[dim[axis]]) && !isDimDefined(currentAbsoluteChild, axis) && isPosDefined(currentAbsoluteChild, leading[axis]) && isPosDefined(currentAbsoluteChild, trailing[axis])) { currentAbsoluteChild.layout[dim[axis]] = fmaxf( boundAxis(currentAbsoluteChild, axis, node.layout[dim[axis]] - getBorderAxis(node, axis) - getMarginAxis(currentAbsoluteChild, axis) - getPosition(currentAbsoluteChild, leading[axis]) - getPosition(currentAbsoluteChild, trailing[axis]) ), // You never want to go smaller than padding getPaddingAndBorderAxis(currentAbsoluteChild, axis) ); } if (isPosDefined(currentAbsoluteChild, trailing[axis]) && !isPosDefined(currentAbsoluteChild, leading[axis])) { currentAbsoluteChild.layout[leading[axis]] = node.layout[dim[axis]] - currentAbsoluteChild.layout[dim[axis]] - getPosition(currentAbsoluteChild, trailing[axis]); } } child = currentAbsoluteChild; currentAbsoluteChild = currentAbsoluteChild.nextAbsoluteChild; child.nextAbsoluteChild = null; } } function layoutNode(node, parentMaxWidth, parentDirection) { node.shouldUpdate = true; var direction = node.style.direction || CSS_DIRECTION_LTR; var skipLayout = !node.isDirty && node.lastLayout && node.lastLayout.requestedHeight === node.layout.height && node.lastLayout.requestedWidth === node.layout.width && node.lastLayout.parentMaxWidth === parentMaxWidth && node.lastLayout.direction === direction; if (skipLayout) { node.layout.width = node.lastLayout.width; node.layout.height = node.lastLayout.height; node.layout.top = node.lastLayout.top; node.layout.left = node.lastLayout.left; } else { if (!node.lastLayout) { node.lastLayout = {}; } node.lastLayout.requestedWidth = node.layout.width; node.lastLayout.requestedHeight = node.layout.height; node.lastLayout.parentMaxWidth = parentMaxWidth; node.lastLayout.direction = direction; // Reset child layouts node.children.forEach(function(child) { child.layout.width = undefined; child.layout.height = undefined; child.layout.top = 0; child.layout.left = 0; }); layoutNodeImpl(node, parentMaxWidth, parentDirection); node.lastLayout.width = node.layout.width; node.lastLayout.height = node.layout.height; node.lastLayout.top = node.layout.top; node.lastLayout.left = node.layout.left; } } return { layoutNodeImpl: layoutNodeImpl, computeLayout: layoutNode, fillNodes: fillNodes }; })(); // This module export is only used for the purposes of unit testing this file. When // the library is packaged this file is included within css-layout.js which forms // the public API. if (typeof exports === 'object') { module.exports = computeLayout; } return function(node) { /*eslint-disable */ // disabling ESLint because this code relies on the above include computeLayout.fillNodes(node); computeLayout.computeLayout(node); /*eslint-enable */ }; })); (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){ var helper = require('./legend'); module.exports = function(){ var scale = d3.scale.linear(), shape = "rect", shapeWidth = 15, shapeHeight = 15, shapeRadius = 10, shapePadding = 2, cells = [5], labels = [], classPrefix = "", useClass = false, title = "", labelFormat = d3.format(".01f"), labelOffset = 10, labelAlign = "middle", labelDelimiter = "to", orient = "vertical", ascending = false, path, legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick"); function legend(svg){ var type = helper.d3_calcType(scale, ascending, cells, labels, labelFormat, labelDelimiter), legendG = svg.selectAll('g').data([scale]); legendG.enter().append('g').attr('class', classPrefix + 'legendCells'); var cell = legendG.selectAll("." + classPrefix + "cell").data(type.data), cellEnter = cell.enter().append("g", ".cell").attr("class", classPrefix + "cell").style("opacity", 1e-6); shapeEnter = cellEnter.append(shape).attr("class", classPrefix + "swatch"), shapes = cell.select("g." + classPrefix + "cell " + shape); //add event handlers helper.d3_addEvents(cellEnter, legendDispatcher); cell.exit().transition().style("opacity", 0).remove(); helper.d3_drawShapes(shape, shapes, shapeHeight, shapeWidth, shapeRadius, path); helper.d3_addText(legendG, cellEnter, type.labels, classPrefix) // sets placement var text = cell.select("text"), shapeSize = shapes[0].map( function(d){ return d.getBBox(); }); //sets scale //everything is fill except for line which is stroke, if (!useClass){ if (shape == "line"){ shapes.style("stroke", type.feature); } else { shapes.style("fill", type.feature); } } else { shapes.attr("class", function(d){ return classPrefix + "swatch " + type.feature(d); }); } var cellTrans, textTrans, textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1; //positions cells and text if (orient === "vertical"){ cellTrans = function(d,i) { return "translate(0, " + (i * (shapeSize[i].height + shapePadding)) + ")"; }; textTrans = function(d,i) { return "translate(" + (shapeSize[i].width + shapeSize[i].x + labelOffset) + "," + (shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; }; } else if (orient === "horizontal"){ cellTrans = function(d,i) { return "translate(" + (i * (shapeSize[i].width + shapePadding)) + ",0)"; } textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign + shapeSize[i].x) + "," + (shapeSize[i].height + shapeSize[i].y + labelOffset + 8) + ")"; }; } helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign); helper.d3_title(svg, legendG, title, classPrefix); cell.transition().style("opacity", 1); } legend.scale = function(_) { if (!arguments.length) return scale; scale = _; return legend; }; legend.cells = function(_) { if (!arguments.length) return cells; if (_.length > 1 || _ >= 2 ){ cells = _; } return legend; }; legend.shape = function(_, d) { if (!arguments.length) return shape; if (_ == "rect" || _ == "circle" || _ == "line" || (_ == "path" && (typeof d === 'string')) ){ shape = _; path = d; } return legend; }; legend.shapeWidth = function(_) { if (!arguments.length) return shapeWidth; shapeWidth = +_; return legend; }; legend.shapeHeight = function(_) { if (!arguments.length) return shapeHeight; shapeHeight = +_; return legend; }; legend.shapeRadius = function(_) { if (!arguments.length) return shapeRadius; shapeRadius = +_; return legend; }; legend.shapePadding = function(_) { if (!arguments.length) return shapePadding; shapePadding = +_; return legend; }; legend.labels = function(_) { if (!arguments.length) return labels; labels = _; return legend; }; legend.labelAlign = function(_) { if (!arguments.length) return labelAlign; if (_ == "start" || _ == "end" || _ == "middle") { labelAlign = _; } return legend; }; legend.labelFormat = function(_) { if (!arguments.length) return labelFormat; labelFormat = _; return legend; }; legend.labelOffset = function(_) { if (!arguments.length) return labelOffset; labelOffset = +_; return legend; }; legend.labelDelimiter = function(_) { if (!arguments.length) return labelDelimiter; labelDelimiter = _; return legend; }; legend.useClass = function(_) { if (!arguments.length) return useClass; if (_ === true || _ === false){ useClass = _; } return legend; }; legend.orient = function(_){ if (!arguments.length) return orient; _ = _.toLowerCase(); if (_ == "horizontal" || _ == "vertical") { orient = _; } return legend; }; legend.ascending = function(_) { if (!arguments.length) return ascending; ascending = !!_; return legend; }; legend.classPrefix = function(_) { if (!arguments.length) return classPrefix; classPrefix = _; return legend; }; legend.title = function(_) { if (!arguments.length) return title; title = _; return legend; }; d3.rebind(legend, legendDispatcher, "on"); return legend; }; },{"./legend":2}],2:[function(require,module,exports){ module.exports = { d3_identity: function (d) { return d; }, d3_mergeLabels: function (gen, labels) { if(labels.length === 0) return gen; gen = (gen) ? gen : []; var i = labels.length; for (; i < gen.length; i++) { labels.push(gen[i]); } return labels; }, d3_linearLegend: function (scale, cells, labelFormat) { var data = []; if (cells.length > 1){ data = cells; } else { var domain = scale.domain(), increment = (domain[domain.length - 1] - domain[0])/(cells - 1), i = 0; for (; i < cells; i++){ data.push(domain[0] + i*increment); } } var labels = data.map(labelFormat); return {data: data, labels: labels, feature: function(d){ return scale(d); }}; }, d3_quantLegend: function (scale, labelFormat, labelDelimiter) { var labels = scale.range().map(function(d){ var invert = scale.invertExtent(d), a = labelFormat(invert[0]), b = labelFormat(invert[1]); // if (( (a) && (a.isNan()) && b){ // console.log("in initial statement") return labelFormat(invert[0]) + " " + labelDelimiter + " " + labelFormat(invert[1]); // } else if (a || b) { // console.log('in else statement') // return (a) ? a : b; // } }); return {data: scale.range(), labels: labels, feature: this.d3_identity }; }, d3_ordinalLegend: function (scale) { return {data: scale.domain(), labels: scale.domain(), feature: function(d){ return scale(d); }}; }, d3_drawShapes: function (shape, shapes, shapeHeight, shapeWidth, shapeRadius, path) { if (shape === "rect"){ shapes.attr("height", shapeHeight).attr("width", shapeWidth); } else if (shape === "circle") { shapes.attr("r", shapeRadius)//.attr("cx", shapeRadius).attr("cy", shapeRadius); } else if (shape === "line") { shapes.attr("x1", 0).attr("x2", shapeWidth).attr("y1", 0).attr("y2", 0); } else if (shape === "path") { shapes.attr("d", path); } }, d3_addText: function (svg, enter, labels, classPrefix){ enter.append("text").attr("class", classPrefix + "label"); svg.selectAll("g." + classPrefix + "cell text").data(labels).text(this.d3_identity); }, d3_calcType: function (scale, ascending, cells, labels, labelFormat, labelDelimiter){ var type = scale.ticks ? this.d3_linearLegend(scale, cells, labelFormat) : scale.invertExtent ? this.d3_quantLegend(scale, labelFormat, labelDelimiter) : this.d3_ordinalLegend(scale); type.labels = this.d3_mergeLabels(type.labels, labels); if (ascending) { type.labels = this.d3_reverse(type.labels); type.data = this.d3_reverse(type.data); } return type; }, d3_reverse: function(arr) { var mirror = []; for (var i = 0, l = arr.length; i < l; i++) { mirror[i] = arr[l-i-1]; } return mirror; }, d3_placement: function (orient, cell, cellTrans, text, textTrans, labelAlign) { cell.attr("transform", cellTrans); text.attr("transform", textTrans); if (orient === "horizontal"){ text.style("text-anchor", labelAlign); } }, d3_addEvents: function(cells, dispatcher){ var _ = this; cells.on("mouseover.legend", function (d) { _.d3_cellOver(dispatcher, d, this); }) .on("mouseout.legend", function (d) { _.d3_cellOut(dispatcher, d, this); }) .on("click.legend", function (d) { _.d3_cellClick(dispatcher, d, this); }); }, d3_cellOver: function(cellDispatcher, d, obj){ cellDispatcher.cellover.call(obj, d); }, d3_cellOut: function(cellDispatcher, d, obj){ cellDispatcher.cellout.call(obj, d); }, d3_cellClick: function(cellDispatcher, d, obj){ cellDispatcher.cellclick.call(obj, d); }, d3_title: function(svg, cellsSvg, title, classPrefix){ if (title !== ""){ var titleText = svg.selectAll('text.' + classPrefix + 'legendTitle'); titleText.data([title]) .enter() .append('text') .attr('class', classPrefix + 'legendTitle'); svg.selectAll('text.' + classPrefix + 'legendTitle') .text(title) var yOffset = svg.select('.' + classPrefix + 'legendTitle') .map(function(d) { return d[0].getBBox().height})[0], xOffset = -cellsSvg.map(function(d) { return d[0].getBBox().x})[0]; cellsSvg.attr('transform', 'translate(' + xOffset + ',' + (yOffset + 10) + ')'); } } } },{}],3:[function(require,module,exports){ var helper = require('./legend'); module.exports = function(){ var scale = d3.scale.linear(), shape = "rect", shapeWidth = 15, shapePadding = 2, cells = [5], labels = [], useStroke = false, classPrefix = "", title = "", labelFormat = d3.format(".01f"), labelOffset = 10, labelAlign = "middle", labelDelimiter = "to", orient = "vertical", ascending = false, path, legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick"); function legend(svg){ var type = helper.d3_calcType(scale, ascending, cells, labels, labelFormat, labelDelimiter), legendG = svg.selectAll('g').data([scale]); legendG.enter().append('g').attr('class', classPrefix + 'legendCells'); var cell = legendG.selectAll("." + classPrefix + "cell").data(type.data), cellEnter = cell.enter().append("g", ".cell").attr("class", classPrefix + "cell").style("opacity", 1e-6); shapeEnter = cellEnter.append(shape).attr("class", classPrefix + "swatch"), shapes = cell.select("g." + classPrefix + "cell " + shape); //add event handlers helper.d3_addEvents(cellEnter, legendDispatcher); cell.exit().transition().style("opacity", 0).remove(); //creates shape if (shape === "line"){ helper.d3_drawShapes(shape, shapes, 0, shapeWidth); shapes.attr("stroke-width", type.feature); } else { helper.d3_drawShapes(shape, shapes, type.feature, type.feature, type.feature, path); } helper.d3_addText(legendG, cellEnter, type.labels, classPrefix) //sets placement var text = cell.select("text"), shapeSize = shapes[0].map( function(d, i){ var bbox = d.getBBox() var stroke = scale(type.data[i]); if (shape === "line" && orient === "horizontal") { bbox.height = bbox.height + stroke; } else if (shape === "line" && orient === "vertical"){ bbox.width = bbox.width; } return bbox; }); var maxH = d3.max(shapeSize, function(d){ return d.height + d.y; }), maxW = d3.max(shapeSize, function(d){ return d.width + d.x; }); var cellTrans, textTrans, textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1; //positions cells and text if (orient === "vertical"){ cellTrans = function(d,i) { var height = d3.sum(shapeSize.slice(0, i + 1 ), function(d){ return d.height; }); return "translate(0, " + (height + i*shapePadding) + ")"; }; textTrans = function(d,i) { return "translate(" + (maxW + labelOffset) + "," + (shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; }; } else if (orient === "horizontal"){ cellTrans = function(d,i) { var width = d3.sum(shapeSize.slice(0, i + 1 ), function(d){ return d.width; }); return "translate(" + (width + i*shapePadding) + ",0)"; }; textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign + shapeSize[i].x) + "," + (maxH + labelOffset ) + ")"; }; } helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign); helper.d3_title(svg, legendG, title, classPrefix); cell.transition().style("opacity", 1); } legend.scale = function(_) { if (!arguments.length) return scale; scale = _; return legend; }; legend.cells = function(_) { if (!arguments.length) return cells; if (_.length > 1 || _ >= 2 ){ cells = _; } return legend; }; legend.shape = function(_, d) { if (!arguments.length) return shape; if (_ == "rect" || _ == "circle" || _ == "line" ){ shape = _; path = d; } return legend; }; legend.shapeWidth = function(_) { if (!arguments.length) return shapeWidth; shapeWidth = +_; return legend; }; legend.shapePadding = function(_) { if (!arguments.length) return shapePadding; shapePadding = +_; return legend; }; legend.labels = function(_) { if (!arguments.length) return labels; labels = _; return legend; }; legend.labelAlign = function(_) { if (!arguments.length) return labelAlign; if (_ == "start" || _ == "end" || _ == "middle") { labelAlign = _; } return legend; }; legend.labelFormat = function(_) { if (!arguments.length) return labelFormat; labelFormat = _; return legend; }; legend.labelOffset = function(_) { if (!arguments.length) return labelOffset; labelOffset = +_; return legend; }; legend.labelDelimiter = function(_) { if (!arguments.length) return labelDelimiter; labelDelimiter = _; return legend; }; legend.orient = function(_){ if (!arguments.length) return orient; _ = _.toLowerCase(); if (_ == "horizontal" || _ == "vertical") { orient = _; } return legend; }; legend.ascending = function(_) { if (!arguments.length) return ascending; ascending = !!_; return legend; }; legend.classPrefix = function(_) { if (!arguments.length) return classPrefix; classPrefix = _; return legend; }; legend.title = function(_) { if (!arguments.length) return title; title = _; return legend; }; d3.rebind(legend, legendDispatcher, "on"); return legend; }; },{"./legend":2}],4:[function(require,module,exports){ var helper = require('./legend'); module.exports = function(){ var scale = d3.scale.linear(), shape = "path", shapeWidth = 15, shapeHeight = 15, shapeRadius = 10, shapePadding = 5, cells = [5], labels = [], classPrefix = "", useClass = false, title = "", labelFormat = d3.format(".01f"), labelAlign = "middle", labelOffset = 10, labelDelimiter = "to", orient = "vertical", ascending = false, legendDispatcher = d3.dispatch("cellover", "cellout", "cellclick"); function legend(svg){ var type = helper.d3_calcType(scale, ascending, cells, labels, labelFormat, labelDelimiter), legendG = svg.selectAll('g').data([scale]); legendG.enter().append('g').attr('class', classPrefix + 'legendCells'); var cell = legendG.selectAll("." + classPrefix + "cell").data(type.data), cellEnter = cell.enter().append("g", ".cell").attr("class", classPrefix + "cell").style("opacity", 1e-6); shapeEnter = cellEnter.append(shape).attr("class", classPrefix + "swatch"), shapes = cell.select("g." + classPrefix + "cell " + shape); //add event handlers helper.d3_addEvents(cellEnter, legendDispatcher); //remove old shapes cell.exit().transition().style("opacity", 0).remove(); helper.d3_drawShapes(shape, shapes, shapeHeight, shapeWidth, shapeRadius, type.feature); helper.d3_addText(legendG, cellEnter, type.labels, classPrefix) // sets placement var text = cell.select("text"), shapeSize = shapes[0].map( function(d){ return d.getBBox(); }); var maxH = d3.max(shapeSize, function(d){ return d.height; }), maxW = d3.max(shapeSize, function(d){ return d.width; }); var cellTrans, textTrans, textAlign = (labelAlign == "start") ? 0 : (labelAlign == "middle") ? 0.5 : 1; //positions cells and text if (orient === "vertical"){ cellTrans = function(d,i) { return "translate(0, " + (i * (maxH + shapePadding)) + ")"; }; textTrans = function(d,i) { return "translate(" + (maxW + labelOffset) + "," + (shapeSize[i].y + shapeSize[i].height/2 + 5) + ")"; }; } else if (orient === "horizontal"){ cellTrans = function(d,i) { return "translate(" + (i * (maxW + shapePadding)) + ",0)"; }; textTrans = function(d,i) { return "translate(" + (shapeSize[i].width*textAlign + shapeSize[i].x) + "," + (maxH + labelOffset ) + ")"; }; } helper.d3_placement(orient, cell, cellTrans, text, textTrans, labelAlign); helper.d3_title(svg, legendG, title, classPrefix); cell.transition().style("opacity", 1); } legend.scale = function(_) { if (!arguments.length) return scale; scale = _; return legend; }; legend.cells = function(_) { if (!arguments.length) return cells; if (_.length > 1 || _ >= 2 ){ cells = _; } return legend; }; legend.shapePadding = function(_) { if (!arguments.length) return shapePadding; shapePadding = +_; return legend; }; legend.labels = function(_) { if (!arguments.length) return labels; labels = _; return legend; }; legend.labelAlign = function(_) { if (!arguments.length) return labelAlign; if (_ == "start" || _ == "end" || _ == "middle") { labelAlign = _; } return legend; }; legend.labelFormat = function(_) { if (!arguments.length) return labelFormat; labelFormat = _; return legend; }; legend.labelOffset = function(_) { if (!arguments.length) return labelOffset; labelOffset = +_; return legend; }; legend.labelDelimiter = function(_) { if (!arguments.length) return labelDelimiter; labelDelimiter = _; return legend; }; legend.orient = function(_){ if (!arguments.length) return orient; _ = _.toLowerCase(); if (_ == "horizontal" || _ == "vertical") { orient = _; } return legend; }; legend.ascending = function(_) { if (!arguments.length) return ascending; ascending = !!_; return legend; }; legend.classPrefix = function(_) { if (!arguments.length) return classPrefix; classPrefix = _; return legend; }; legend.title = function(_) { if (!arguments.length) return title; title = _; return legend; }; d3.rebind(legend, legendDispatcher, "on"); return legend; }; },{"./legend":2}],5:[function(require,module,exports){ d3.legend = { color: require('./color'), size: require('./size'), symbol: require('./symbol') }; },{"./color":1,"./size":3,"./symbol":4}]},{},[5]); (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ (function (global){ "use strict"; _dereq_(296); _dereq_(297); _dereq_(2); /* eslint max-len: 0 */ if (global._babelPolyfill) { throw new Error("only one instance of babel-polyfill is allowed"); } global._babelPolyfill = true; // Should be removed in the next major release: var DEFINE_PROPERTY = "defineProperty"; function define(O, key, value) { O[key] || Object[DEFINE_PROPERTY](O, key, { writable: true, configurable: true, value: value }); } define(String.prototype, "padLeft", "".padStart); define(String.prototype, "padRight", "".padEnd); "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { [][key] && define(Array, key, Function.call.bind([][key])); }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"2":2,"296":296,"297":297}],2:[function(_dereq_,module,exports){ _dereq_(120); module.exports = _dereq_(23).RegExp.escape; },{"120":120,"23":23}],3:[function(_dereq_,module,exports){ module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; },{}],4:[function(_dereq_,module,exports){ var cof = _dereq_(18); module.exports = function(it, msg){ if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg); return +it; }; },{"18":18}],5:[function(_dereq_,module,exports){ // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = _dereq_(117)('unscopables') , ArrayProto = Array.prototype; if(ArrayProto[UNSCOPABLES] == undefined)_dereq_(40)(ArrayProto, UNSCOPABLES, {}); module.exports = function(key){ ArrayProto[UNSCOPABLES][key] = true; }; },{"117":117,"40":40}],6:[function(_dereq_,module,exports){ module.exports = function(it, Constructor, name, forbiddenField){ if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ throw TypeError(name + ': incorrect invocation!'); } return it; }; },{}],7:[function(_dereq_,module,exports){ var isObject = _dereq_(49); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; },{"49":49}],8:[function(_dereq_,module,exports){ // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) 'use strict'; var toObject = _dereq_(109) , toIndex = _dereq_(105) , toLength = _dereq_(108); module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){ var O = toObject(this) , len = toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments.length > 2 ? arguments[2] : undefined , count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from += count - 1; to += count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }; },{"105":105,"108":108,"109":109}],9:[function(_dereq_,module,exports){ // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) 'use strict'; var toObject = _dereq_(109) , toIndex = _dereq_(105) , toLength = _dereq_(108); module.exports = function fill(value /*, start = 0, end = @length */){ var O = toObject(this) , length = toLength(O.length) , aLen = arguments.length , index = toIndex(aLen > 1 ? arguments[1] : undefined, length) , end = aLen > 2 ? arguments[2] : undefined , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; }; },{"105":105,"108":108,"109":109}],10:[function(_dereq_,module,exports){ var forOf = _dereq_(37); module.exports = function(iter, ITERATOR){ var result = []; forOf(iter, false, result.push, result, ITERATOR); return result; }; },{"37":37}],11:[function(_dereq_,module,exports){ // false -> Array#indexOf // true -> Array#includes var toIObject = _dereq_(107) , toLength = _dereq_(108) , toIndex = _dereq_(105); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; },{"105":105,"107":107,"108":108}],12:[function(_dereq_,module,exports){ // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var ctx = _dereq_(25) , IObject = _dereq_(45) , toObject = _dereq_(109) , toLength = _dereq_(108) , asc = _dereq_(15); module.exports = function(TYPE, $create){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX , create = $create || asc; return function($this, callbackfn, that){ var O = toObject($this) , self = IObject(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; },{"108":108,"109":109,"15":15,"25":25,"45":45}],13:[function(_dereq_,module,exports){ var aFunction = _dereq_(3) , toObject = _dereq_(109) , IObject = _dereq_(45) , toLength = _dereq_(108); module.exports = function(that, callbackfn, aLen, memo, isRight){ aFunction(callbackfn); var O = toObject(that) , self = IObject(O) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(aLen < 2)for(;;){ if(index in self){ memo = self[index]; index += i; break; } index += i; if(isRight ? index < 0 : length <= index){ throw TypeError('Reduce of empty array with no initial value'); } } for(;isRight ? index >= 0 : length > index; index += i)if(index in self){ memo = callbackfn(memo, self[index], index, O); } return memo; }; },{"108":108,"109":109,"3":3,"45":45}],14:[function(_dereq_,module,exports){ var isObject = _dereq_(49) , isArray = _dereq_(47) , SPECIES = _dereq_(117)('species'); module.exports = function(original){ var C; if(isArray(original)){ C = original.constructor; // cross-realm fallback if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined; if(isObject(C)){ C = C[SPECIES]; if(C === null)C = undefined; } } return C === undefined ? Array : C; }; },{"117":117,"47":47,"49":49}],15:[function(_dereq_,module,exports){ // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var speciesConstructor = _dereq_(14); module.exports = function(original, length){ return new (speciesConstructor(original))(length); }; },{"14":14}],16:[function(_dereq_,module,exports){ 'use strict'; var aFunction = _dereq_(3) , isObject = _dereq_(49) , invoke = _dereq_(44) , arraySlice = [].slice , factories = {}; var construct = function(F, len, args){ if(!(len in factories)){ for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']'; factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); } return factories[len](F, args); }; module.exports = Function.bind || function bind(that /*, args... */){ var fn = aFunction(this) , partArgs = arraySlice.call(arguments, 1); var bound = function(/* args... */){ var args = partArgs.concat(arraySlice.call(arguments)); return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); }; if(isObject(fn.prototype))bound.prototype = fn.prototype; return bound; }; },{"3":3,"44":44,"49":49}],17:[function(_dereq_,module,exports){ // getting tag from 19.1.3.6 Object.prototype.toString() var cof = _dereq_(18) , TAG = _dereq_(117)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; },{"117":117,"18":18}],18:[function(_dereq_,module,exports){ var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; },{}],19:[function(_dereq_,module,exports){ 'use strict'; var dP = _dereq_(67).f , create = _dereq_(66) , hide = _dereq_(40) , redefineAll = _dereq_(86) , ctx = _dereq_(25) , anInstance = _dereq_(6) , defined = _dereq_(27) , forOf = _dereq_(37) , $iterDefine = _dereq_(53) , step = _dereq_(55) , setSpecies = _dereq_(91) , DESCRIPTORS = _dereq_(28) , fastKey = _dereq_(62).fastKey , SIZE = DESCRIPTORS ? '_s' : 'size'; var getEntry = function(that, key){ // fast case var index = fastKey(key), entry; if(index !== 'F')return that._i[index]; // frozen object case for(entry = that._f; entry; entry = entry.n){ if(entry.k == key)return entry; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ anInstance(that, C, NAME, '_i'); that._i = create(null); // index that._f = undefined; // first entry that._l = undefined; // last entry that[SIZE] = 0; // size if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that._f = that._l = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that._i[entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that._f == entry)that._f = next; if(that._l == entry)that._l = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ anInstance(this, C, 'forEach'); var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) , entry; while(entry = entry ? entry.n : this._f){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if(DESCRIPTORS)dP(C.prototype, 'size', { get: function(){ return defined(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that._l = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that._l, // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that._f)that._f = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index !== 'F')that._i[index] = entry; } return that; }, getEntry: getEntry, setStrong: function(C, NAME, IS_MAP){ // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 $iterDefine(C, NAME, function(iterated, kind){ this._t = iterated; // target this._k = kind; // kind this._l = undefined; // previous }, function(){ var that = this , kind = that._k , entry = that._l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ // or finish the iteration that._t = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(NAME); } }; },{"25":25,"27":27,"28":28,"37":37,"40":40,"53":53,"55":55,"6":6,"62":62,"66":66,"67":67,"86":86,"91":91}],20:[function(_dereq_,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var classof = _dereq_(17) , from = _dereq_(10); module.exports = function(NAME){ return function toJSON(){ if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); return from(this); }; }; },{"10":10,"17":17}],21:[function(_dereq_,module,exports){ 'use strict'; var redefineAll = _dereq_(86) , getWeak = _dereq_(62).getWeak , anObject = _dereq_(7) , isObject = _dereq_(49) , anInstance = _dereq_(6) , forOf = _dereq_(37) , createArrayMethod = _dereq_(12) , $has = _dereq_(39) , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , id = 0; // fallback for uncaught frozen keys var uncaughtFrozenStore = function(that){ return that._l || (that._l = new UncaughtFrozenStore); }; var UncaughtFrozenStore = function(){ this.a = []; }; var findUncaughtFrozen = function(store, key){ return arrayFind(store.a, function(it){ return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function(key){ var entry = findUncaughtFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findUncaughtFrozen(this, key); }, set: function(key, value){ var entry = findUncaughtFrozen(this, key); if(entry)entry[1] = value; else this.a.push([key, value]); }, 'delete': function(key){ var index = arrayFindIndex(this.a, function(it){ return it[0] === key; }); if(~index)this.a.splice(index, 1); return !!~index; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ anInstance(that, C, NAME, '_i'); that._i = id++; // collection id that._l = undefined; // leak store for uncaught frozen objects if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this)['delete'](key); return data && $has(data, this._i) && delete data[this._i]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).has(key); return data && $has(data, this._i); } }); return C; }, def: function(that, key, value){ var data = getWeak(anObject(key), true); if(data === true)uncaughtFrozenStore(that).set(key, value); else data[that._i] = value; return that; }, ufstore: uncaughtFrozenStore }; },{"12":12,"37":37,"39":39,"49":49,"6":6,"62":62,"7":7,"86":86}],22:[function(_dereq_,module,exports){ 'use strict'; var global = _dereq_(38) , $export = _dereq_(32) , redefine = _dereq_(87) , redefineAll = _dereq_(86) , meta = _dereq_(62) , forOf = _dereq_(37) , anInstance = _dereq_(6) , isObject = _dereq_(49) , fails = _dereq_(34) , $iterDetect = _dereq_(54) , setToStringTag = _dereq_(92) , inheritIfRequired = _dereq_(43); module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ var Base = global[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; var fixMethod = function(KEY){ var fn = proto[KEY]; redefine(proto, KEY, KEY == 'delete' ? function(a){ return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); } : KEY == 'has' ? function has(a){ return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); } : KEY == 'get' ? function get(a){ return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); } : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; } : function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; } ); }; if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ new C().entries().next(); }))){ // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); redefineAll(C.prototype, methods); meta.NEED = true; } else { var instance = new C // early implementations not supports chaining , HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false , THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); }) // most early implementations doesn't supports iterables, most modern - not close it correctly , ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new // for early implementations -0 and +0 not the same , BUGGY_ZERO = !IS_WEAK && fails(function(){ // V8 ~ Chromium 42- fails only with 5+ elements var $instance = new C() , index = 5; while(index--)$instance[ADDER](index, index); return !$instance.has(-0); }); if(!ACCEPT_ITERABLES){ C = wrapper(function(target, iterable){ anInstance(target, C, NAME); var that = inheritIfRequired(new Base, target, C); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); return that; }); C.prototype = proto; proto.constructor = C; } if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){ fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER); // weak collections should not contains .clear method if(IS_WEAK && proto.clear)delete proto.clear; } setToStringTag(C, NAME); O[NAME] = C; $export($export.G + $export.W + $export.F * (C != Base), O); if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); return C; }; },{"32":32,"34":34,"37":37,"38":38,"43":43,"49":49,"54":54,"6":6,"62":62,"86":86,"87":87,"92":92}],23:[function(_dereq_,module,exports){ var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef },{}],24:[function(_dereq_,module,exports){ 'use strict'; var $defineProperty = _dereq_(67) , createDesc = _dereq_(85); module.exports = function(object, index, value){ if(index in object)$defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; },{"67":67,"85":85}],25:[function(_dereq_,module,exports){ // optional / simple context binding var aFunction = _dereq_(3); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; },{"3":3}],26:[function(_dereq_,module,exports){ 'use strict'; var anObject = _dereq_(7) , toPrimitive = _dereq_(110) , NUMBER = 'number'; module.exports = function(hint){ if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint'); return toPrimitive(anObject(this), hint != NUMBER); }; },{"110":110,"7":7}],27:[function(_dereq_,module,exports){ // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; },{}],28:[function(_dereq_,module,exports){ // Thank's IE8 for his funny defineProperty module.exports = !_dereq_(34)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); },{"34":34}],29:[function(_dereq_,module,exports){ var isObject = _dereq_(49) , document = _dereq_(38).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; },{"38":38,"49":49}],30:[function(_dereq_,module,exports){ // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); },{}],31:[function(_dereq_,module,exports){ // all enumerable object keys, includes symbols var getKeys = _dereq_(76) , gOPS = _dereq_(73) , pIE = _dereq_(77); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; },{"73":73,"76":76,"77":77}],32:[function(_dereq_,module,exports){ var global = _dereq_(38) , core = _dereq_(23) , hide = _dereq_(40) , redefine = _dereq_(87) , ctx = _dereq_(25) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE] , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}) , key, own, out, exp; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // extend global if(target)redefine(target, key, out, type & $export.U); // export if(exports[key] != out)hide(exports, key, exp); if(IS_PROTO && expProto[key] != out)expProto[key] = out; } }; global.core = core; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; },{"23":23,"25":25,"38":38,"40":40,"87":87}],33:[function(_dereq_,module,exports){ var MATCH = _dereq_(117)('match'); module.exports = function(KEY){ var re = /./; try { '/./'[KEY](re); } catch(e){ try { re[MATCH] = false; return !'/./'[KEY](re); } catch(f){ /* empty */ } } return true; }; },{"117":117}],34:[function(_dereq_,module,exports){ module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; },{}],35:[function(_dereq_,module,exports){ 'use strict'; var hide = _dereq_(40) , redefine = _dereq_(87) , fails = _dereq_(34) , defined = _dereq_(27) , wks = _dereq_(117); module.exports = function(KEY, length, exec){ var SYMBOL = wks(KEY) , fns = exec(defined, SYMBOL, ''[KEY]) , strfn = fns[0] , rxfn = fns[1]; if(fails(function(){ var O = {}; O[SYMBOL] = function(){ return 7; }; return ''[KEY](O) != 7; })){ redefine(String.prototype, KEY, strfn); hide(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) // 21.2.5.11 RegExp.prototype[@@split](string, limit) ? function(string, arg){ return rxfn.call(string, this, arg); } // 21.2.5.6 RegExp.prototype[@@match](string) // 21.2.5.9 RegExp.prototype[@@search](string) : function(string){ return rxfn.call(string, this); } ); } }; },{"117":117,"27":27,"34":34,"40":40,"87":87}],36:[function(_dereq_,module,exports){ 'use strict'; // 21.2.5.3 get RegExp.prototype.flags var anObject = _dereq_(7); module.exports = function(){ var that = anObject(this) , result = ''; if(that.global) result += 'g'; if(that.ignoreCase) result += 'i'; if(that.multiline) result += 'm'; if(that.unicode) result += 'u'; if(that.sticky) result += 'y'; return result; }; },{"7":7}],37:[function(_dereq_,module,exports){ var ctx = _dereq_(25) , call = _dereq_(51) , isArrayIter = _dereq_(46) , anObject = _dereq_(7) , toLength = _dereq_(108) , getIterFn = _dereq_(118) , BREAK = {} , RETURN = {}; var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) , f = ctx(fn, that, entries ? 2 : 1) , index = 0 , length, step, iterator, result; if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if(result === BREAK || result === RETURN)return result; } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ result = call(iterator, f, step.value, entries); if(result === BREAK || result === RETURN)return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; },{"108":108,"118":118,"25":25,"46":46,"51":51,"7":7}],38:[function(_dereq_,module,exports){ // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef },{}],39:[function(_dereq_,module,exports){ var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; },{}],40:[function(_dereq_,module,exports){ var dP = _dereq_(67) , createDesc = _dereq_(85); module.exports = _dereq_(28) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; },{"28":28,"67":67,"85":85}],41:[function(_dereq_,module,exports){ module.exports = _dereq_(38).document && document.documentElement; },{"38":38}],42:[function(_dereq_,module,exports){ module.exports = !_dereq_(28) && !_dereq_(34)(function(){ return Object.defineProperty(_dereq_(29)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); },{"28":28,"29":29,"34":34}],43:[function(_dereq_,module,exports){ var isObject = _dereq_(49) , setPrototypeOf = _dereq_(90).set; module.exports = function(that, target, C){ var P, S = target.constructor; if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){ setPrototypeOf(that, P); } return that; }; },{"49":49,"90":90}],44:[function(_dereq_,module,exports){ // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; },{}],45:[function(_dereq_,module,exports){ // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = _dereq_(18); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; },{"18":18}],46:[function(_dereq_,module,exports){ // check on default Array iterator var Iterators = _dereq_(56) , ITERATOR = _dereq_(117)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; },{"117":117,"56":56}],47:[function(_dereq_,module,exports){ // 7.2.2 IsArray(argument) var cof = _dereq_(18); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; },{"18":18}],48:[function(_dereq_,module,exports){ // 20.1.2.3 Number.isInteger(number) var isObject = _dereq_(49) , floor = Math.floor; module.exports = function isInteger(it){ return !isObject(it) && isFinite(it) && floor(it) === it; }; },{"49":49}],49:[function(_dereq_,module,exports){ module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; },{}],50:[function(_dereq_,module,exports){ // 7.2.8 IsRegExp(argument) var isObject = _dereq_(49) , cof = _dereq_(18) , MATCH = _dereq_(117)('match'); module.exports = function(it){ var isRegExp; return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); }; },{"117":117,"18":18,"49":49}],51:[function(_dereq_,module,exports){ // call something on iterator step with safe closing on error var anObject = _dereq_(7); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; },{"7":7}],52:[function(_dereq_,module,exports){ 'use strict'; var create = _dereq_(66) , descriptor = _dereq_(85) , setToStringTag = _dereq_(92) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() _dereq_(40)(IteratorPrototype, _dereq_(117)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; },{"117":117,"40":40,"66":66,"85":85,"92":92}],53:[function(_dereq_,module,exports){ 'use strict'; var LIBRARY = _dereq_(58) , $export = _dereq_(32) , redefine = _dereq_(87) , hide = _dereq_(40) , has = _dereq_(39) , Iterators = _dereq_(56) , $iterCreate = _dereq_(52) , setToStringTag = _dereq_(92) , getPrototypeOf = _dereq_(74) , ITERATOR = _dereq_(117)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; },{"117":117,"32":32,"39":39,"40":40,"52":52,"56":56,"58":58,"74":74,"87":87,"92":92}],54:[function(_dereq_,module,exports){ var ITERATOR = _dereq_(117)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; },{"117":117}],55:[function(_dereq_,module,exports){ module.exports = function(done, value){ return {value: value, done: !!done}; }; },{}],56:[function(_dereq_,module,exports){ module.exports = {}; },{}],57:[function(_dereq_,module,exports){ var getKeys = _dereq_(76) , toIObject = _dereq_(107); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; },{"107":107,"76":76}],58:[function(_dereq_,module,exports){ module.exports = false; },{}],59:[function(_dereq_,module,exports){ // 20.2.2.14 Math.expm1(x) var $expm1 = Math.expm1; module.exports = (!$expm1 // Old FF bug || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 // Tor Browser bug || $expm1(-2e-17) != -2e-17 ) ? function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; } : $expm1; },{}],60:[function(_dereq_,module,exports){ // 20.2.2.20 Math.log1p(x) module.exports = Math.log1p || function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); }; },{}],61:[function(_dereq_,module,exports){ // 20.2.2.28 Math.sign(x) module.exports = Math.sign || function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; },{}],62:[function(_dereq_,module,exports){ var META = _dereq_(114)('meta') , isObject = _dereq_(49) , has = _dereq_(39) , setDesc = _dereq_(67).f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !_dereq_(34)(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; },{"114":114,"34":34,"39":39,"49":49,"67":67}],63:[function(_dereq_,module,exports){ var Map = _dereq_(150) , $export = _dereq_(32) , shared = _dereq_(94)('metadata') , store = shared.store || (shared.store = new (_dereq_(256))); var getOrCreateMetadataMap = function(target, targetKey, create){ var targetMetadata = store.get(target); if(!targetMetadata){ if(!create)return undefined; store.set(target, targetMetadata = new Map); } var keyMetadata = targetMetadata.get(targetKey); if(!keyMetadata){ if(!create)return undefined; targetMetadata.set(targetKey, keyMetadata = new Map); } return keyMetadata; }; var ordinaryHasOwnMetadata = function(MetadataKey, O, P){ var metadataMap = getOrCreateMetadataMap(O, P, false); return metadataMap === undefined ? false : metadataMap.has(MetadataKey); }; var ordinaryGetOwnMetadata = function(MetadataKey, O, P){ var metadataMap = getOrCreateMetadataMap(O, P, false); return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); }; var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){ getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); }; var ordinaryOwnMetadataKeys = function(target, targetKey){ var metadataMap = getOrCreateMetadataMap(target, targetKey, false) , keys = []; if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); }); return keys; }; var toMetaKey = function(it){ return it === undefined || typeof it == 'symbol' ? it : String(it); }; var exp = function(O){ $export($export.S, 'Reflect', O); }; module.exports = { store: store, map: getOrCreateMetadataMap, has: ordinaryHasOwnMetadata, get: ordinaryGetOwnMetadata, set: ordinaryDefineOwnMetadata, keys: ordinaryOwnMetadataKeys, key: toMetaKey, exp: exp }; },{"150":150,"256":256,"32":32,"94":94}],64:[function(_dereq_,module,exports){ var global = _dereq_(38) , macrotask = _dereq_(104).set , Observer = global.MutationObserver || global.WebKitMutationObserver , process = global.process , Promise = global.Promise , isNode = _dereq_(18)(process) == 'process'; module.exports = function(){ var head, last, notify; var flush = function(){ var parent, fn; if(isNode && (parent = process.domain))parent.exit(); while(head){ fn = head.fn; head = head.next; try { fn(); } catch(e){ if(head)notify(); else last = undefined; throw e; } } last = undefined; if(parent)parent.enter(); }; // Node.js if(isNode){ notify = function(){ process.nextTick(flush); }; // browsers with MutationObserver } else if(Observer){ var toggle = true , node = document.createTextNode(''); new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new notify = function(){ node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if(Promise && Promise.resolve){ var promise = Promise.resolve(); notify = function(){ promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function(){ // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function(fn){ var task = {fn: fn, next: undefined}; if(last)last.next = task; if(!head){ head = task; notify(); } last = task; }; }; },{"104":104,"18":18,"38":38}],65:[function(_dereq_,module,exports){ 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = _dereq_(76) , gOPS = _dereq_(73) , pIE = _dereq_(77) , toObject = _dereq_(109) , IObject = _dereq_(45) , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || _dereq_(34)(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , aLen = arguments.length , index = 1 , getSymbols = gOPS.f , isEnum = pIE.f; while(aLen > index){ var S = IObject(arguments[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; },{"109":109,"34":34,"45":45,"73":73,"76":76,"77":77}],66:[function(_dereq_,module,exports){ // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = _dereq_(7) , dPs = _dereq_(68) , enumBugKeys = _dereq_(30) , IE_PROTO = _dereq_(93)('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = _dereq_(29)('iframe') , i = enumBugKeys.length , gt = '>' , iframeDocument; iframe.style.display = 'none'; _dereq_(41).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; },{"29":29,"30":30,"41":41,"68":68,"7":7,"93":93}],67:[function(_dereq_,module,exports){ var anObject = _dereq_(7) , IE8_DOM_DEFINE = _dereq_(42) , toPrimitive = _dereq_(110) , dP = Object.defineProperty; exports.f = _dereq_(28) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; },{"110":110,"28":28,"42":42,"7":7}],68:[function(_dereq_,module,exports){ var dP = _dereq_(67) , anObject = _dereq_(7) , getKeys = _dereq_(76); module.exports = _dereq_(28) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; },{"28":28,"67":67,"7":7,"76":76}],69:[function(_dereq_,module,exports){ // Forced replacement prototype accessors methods module.exports = _dereq_(58)|| !_dereq_(34)(function(){ var K = Math.random(); // In FF throws only define methods __defineSetter__.call(null, K, function(){ /* empty */}); delete _dereq_(38)[K]; }); },{"34":34,"38":38,"58":58}],70:[function(_dereq_,module,exports){ var pIE = _dereq_(77) , createDesc = _dereq_(85) , toIObject = _dereq_(107) , toPrimitive = _dereq_(110) , has = _dereq_(39) , IE8_DOM_DEFINE = _dereq_(42) , gOPD = Object.getOwnPropertyDescriptor; exports.f = _dereq_(28) ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; },{"107":107,"110":110,"28":28,"39":39,"42":42,"77":77,"85":85}],71:[function(_dereq_,module,exports){ // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = _dereq_(107) , gOPN = _dereq_(72).f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; },{"107":107,"72":72}],72:[function(_dereq_,module,exports){ // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = _dereq_(75) , hiddenKeys = _dereq_(30).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; },{"30":30,"75":75}],73:[function(_dereq_,module,exports){ exports.f = Object.getOwnPropertySymbols; },{}],74:[function(_dereq_,module,exports){ // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = _dereq_(39) , toObject = _dereq_(109) , IE_PROTO = _dereq_(93)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; },{"109":109,"39":39,"93":93}],75:[function(_dereq_,module,exports){ var has = _dereq_(39) , toIObject = _dereq_(107) , arrayIndexOf = _dereq_(11)(false) , IE_PROTO = _dereq_(93)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; },{"107":107,"11":11,"39":39,"93":93}],76:[function(_dereq_,module,exports){ // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = _dereq_(75) , enumBugKeys = _dereq_(30); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; },{"30":30,"75":75}],77:[function(_dereq_,module,exports){ exports.f = {}.propertyIsEnumerable; },{}],78:[function(_dereq_,module,exports){ // most Object methods by ES6 should accept primitives var $export = _dereq_(32) , core = _dereq_(23) , fails = _dereq_(34); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; },{"23":23,"32":32,"34":34}],79:[function(_dereq_,module,exports){ var getKeys = _dereq_(76) , toIObject = _dereq_(107) , isEnum = _dereq_(77).f; module.exports = function(isEntries){ return function(it){ var O = toIObject(it) , keys = getKeys(O) , length = keys.length , i = 0 , result = [] , key; while(length > i)if(isEnum.call(O, key = keys[i++])){ result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; },{"107":107,"76":76,"77":77}],80:[function(_dereq_,module,exports){ // all object keys, includes non-enumerable and symbols var gOPN = _dereq_(72) , gOPS = _dereq_(73) , anObject = _dereq_(7) , Reflect = _dereq_(38).Reflect; module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){ var keys = gOPN.f(anObject(it)) , getSymbols = gOPS.f; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; },{"38":38,"7":7,"72":72,"73":73}],81:[function(_dereq_,module,exports){ var $parseFloat = _dereq_(38).parseFloat , $trim = _dereq_(102).trim; module.exports = 1 / $parseFloat(_dereq_(103) + '-0') !== -Infinity ? function parseFloat(str){ var string = $trim(String(str), 3) , result = $parseFloat(string); return result === 0 && string.charAt(0) == '-' ? -0 : result; } : $parseFloat; },{"102":102,"103":103,"38":38}],82:[function(_dereq_,module,exports){ var $parseInt = _dereq_(38).parseInt , $trim = _dereq_(102).trim , ws = _dereq_(103) , hex = /^[\-+]?0[xX]/; module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){ var string = $trim(String(str), 3); return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); } : $parseInt; },{"102":102,"103":103,"38":38}],83:[function(_dereq_,module,exports){ 'use strict'; var path = _dereq_(84) , invoke = _dereq_(44) , aFunction = _dereq_(3); module.exports = function(/* ...pargs */){ var fn = aFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , aLen = arguments.length , j = 0, k = 0, args; if(!holder && !aLen)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; while(aLen > k)args.push(arguments[k++]); return invoke(fn, args, that); }; }; },{"3":3,"44":44,"84":84}],84:[function(_dereq_,module,exports){ module.exports = _dereq_(38); },{"38":38}],85:[function(_dereq_,module,exports){ module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; },{}],86:[function(_dereq_,module,exports){ var redefine = _dereq_(87); module.exports = function(target, src, safe){ for(var key in src)redefine(target, key, src[key], safe); return target; }; },{"87":87}],87:[function(_dereq_,module,exports){ var global = _dereq_(38) , hide = _dereq_(40) , has = _dereq_(39) , SRC = _dereq_(114)('src') , TO_STRING = 'toString' , $toString = Function[TO_STRING] , TPL = ('' + $toString).split(TO_STRING); _dereq_(23).inspectSource = function(it){ return $toString.call(it); }; (module.exports = function(O, key, val, safe){ var isFunction = typeof val == 'function'; if(isFunction)has(val, 'name') || hide(val, 'name', key); if(O[key] === val)return; if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if(O === global){ O[key] = val; } else { if(!safe){ delete O[key]; hide(O, key, val); } else { if(O[key])O[key] = val; else hide(O, key, val); } } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString(){ return typeof this == 'function' && this[SRC] || $toString.call(this); }); },{"114":114,"23":23,"38":38,"39":39,"40":40}],88:[function(_dereq_,module,exports){ module.exports = function(regExp, replace){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(it).replace(regExp, replacer); }; }; },{}],89:[function(_dereq_,module,exports){ // 7.2.9 SameValue(x, y) module.exports = Object.is || function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; },{}],90:[function(_dereq_,module,exports){ // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = _dereq_(49) , anObject = _dereq_(7); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = _dereq_(25)(Function.call, _dereq_(70).f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; },{"25":25,"49":49,"7":7,"70":70}],91:[function(_dereq_,module,exports){ 'use strict'; var global = _dereq_(38) , dP = _dereq_(67) , DESCRIPTORS = _dereq_(28) , SPECIES = _dereq_(117)('species'); module.exports = function(KEY){ var C = global[KEY]; if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { configurable: true, get: function(){ return this; } }); }; },{"117":117,"28":28,"38":38,"67":67}],92:[function(_dereq_,module,exports){ var def = _dereq_(67).f , has = _dereq_(39) , TAG = _dereq_(117)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; },{"117":117,"39":39,"67":67}],93:[function(_dereq_,module,exports){ var shared = _dereq_(94)('keys') , uid = _dereq_(114); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; },{"114":114,"94":94}],94:[function(_dereq_,module,exports){ var global = _dereq_(38) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; },{"38":38}],95:[function(_dereq_,module,exports){ // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = _dereq_(7) , aFunction = _dereq_(3) , SPECIES = _dereq_(117)('species'); module.exports = function(O, D){ var C = anObject(O).constructor, S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; },{"117":117,"3":3,"7":7}],96:[function(_dereq_,module,exports){ var fails = _dereq_(34); module.exports = function(method, arg){ return !!method && fails(function(){ arg ? method.call(null, function(){}, 1) : method.call(null); }); }; },{"34":34}],97:[function(_dereq_,module,exports){ var toInteger = _dereq_(106) , defined = _dereq_(27); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; },{"106":106,"27":27}],98:[function(_dereq_,module,exports){ // helper for String#{startsWith, endsWith, includes} var isRegExp = _dereq_(50) , defined = _dereq_(27); module.exports = function(that, searchString, NAME){ if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!"); return String(defined(that)); }; },{"27":27,"50":50}],99:[function(_dereq_,module,exports){ var $export = _dereq_(32) , fails = _dereq_(34) , defined = _dereq_(27) , quot = /"/g; // B.2.3.2.1 CreateHTML(string, tag, attribute, value) var createHTML = function(string, tag, attribute, value) { var S = String(defined(string)) , p1 = '<' + tag; if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '&quot;') + '"'; return p1 + '>' + S + '</' + tag + '>'; }; module.exports = function(NAME, exec){ var O = {}; O[NAME] = exec(createHTML); $export($export.P + $export.F * fails(function(){ var test = ''[NAME]('"'); return test !== test.toLowerCase() || test.split('"').length > 3; }), 'String', O); }; },{"27":27,"32":32,"34":34}],100:[function(_dereq_,module,exports){ // https://github.com/tc39/proposal-string-pad-start-end var toLength = _dereq_(108) , repeat = _dereq_(101) , defined = _dereq_(27); module.exports = function(that, maxLength, fillString, left){ var S = String(defined(that)) , stringLength = S.length , fillStr = fillString === undefined ? ' ' : String(fillString) , intMaxLength = toLength(maxLength); if(intMaxLength <= stringLength || fillStr == '')return S; var fillLen = intMaxLength - stringLength , stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen); return left ? stringFiller + S : S + stringFiller; }; },{"101":101,"108":108,"27":27}],101:[function(_dereq_,module,exports){ 'use strict'; var toInteger = _dereq_(106) , defined = _dereq_(27); module.exports = function repeat(count){ var str = String(defined(this)) , res = '' , n = toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }; },{"106":106,"27":27}],102:[function(_dereq_,module,exports){ var $export = _dereq_(32) , defined = _dereq_(27) , fails = _dereq_(34) , spaces = _dereq_(103) , space = '[' + spaces + ']' , non = '\u200b\u0085' , ltrim = RegExp('^' + space + space + '*') , rtrim = RegExp(space + space + '*$'); var exporter = function(KEY, exec, ALIAS){ var exp = {}; var FORCE = fails(function(){ return !!spaces[KEY]() || non[KEY]() != non; }); var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; if(ALIAS)exp[ALIAS] = fn; $export($export.P + $export.F * FORCE, 'String', exp); }; // 1 -> String#trimLeft // 2 -> String#trimRight // 3 -> String#trim var trim = exporter.trim = function(string, TYPE){ string = String(defined(string)); if(TYPE & 1)string = string.replace(ltrim, ''); if(TYPE & 2)string = string.replace(rtrim, ''); return string; }; module.exports = exporter; },{"103":103,"27":27,"32":32,"34":34}],103:[function(_dereq_,module,exports){ module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; },{}],104:[function(_dereq_,module,exports){ var ctx = _dereq_(25) , invoke = _dereq_(44) , html = _dereq_(41) , cel = _dereq_(29) , global = _dereq_(38) , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; var run = function(){ var id = +this; if(queue.hasOwnProperty(id)){ var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function(event){ run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!setTask || !clearTask){ setTask = function setImmediate(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id){ delete queue[id]; }; // Node.js 0.8- if(_dereq_(18)(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if(MessageChannel){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ defer = function(id){ global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if(ONREADYSTATECHANGE in cel('script')){ defer = function(id){ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; },{"18":18,"25":25,"29":29,"38":38,"41":41,"44":44}],105:[function(_dereq_,module,exports){ var toInteger = _dereq_(106) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; },{"106":106}],106:[function(_dereq_,module,exports){ // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; },{}],107:[function(_dereq_,module,exports){ // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = _dereq_(45) , defined = _dereq_(27); module.exports = function(it){ return IObject(defined(it)); }; },{"27":27,"45":45}],108:[function(_dereq_,module,exports){ // 7.1.15 ToLength var toInteger = _dereq_(106) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; },{"106":106}],109:[function(_dereq_,module,exports){ // 7.1.13 ToObject(argument) var defined = _dereq_(27); module.exports = function(it){ return Object(defined(it)); }; },{"27":27}],110:[function(_dereq_,module,exports){ // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = _dereq_(49); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; },{"49":49}],111:[function(_dereq_,module,exports){ 'use strict'; if(_dereq_(28)){ var LIBRARY = _dereq_(58) , global = _dereq_(38) , fails = _dereq_(34) , $export = _dereq_(32) , $typed = _dereq_(113) , $buffer = _dereq_(112) , ctx = _dereq_(25) , anInstance = _dereq_(6) , propertyDesc = _dereq_(85) , hide = _dereq_(40) , redefineAll = _dereq_(86) , isInteger = _dereq_(48) , toInteger = _dereq_(106) , toLength = _dereq_(108) , toIndex = _dereq_(105) , toPrimitive = _dereq_(110) , has = _dereq_(39) , same = _dereq_(89) , classof = _dereq_(17) , isObject = _dereq_(49) , toObject = _dereq_(109) , isArrayIter = _dereq_(46) , create = _dereq_(66) , getPrototypeOf = _dereq_(74) , gOPN = _dereq_(72).f , isIterable = _dereq_(119) , getIterFn = _dereq_(118) , uid = _dereq_(114) , wks = _dereq_(117) , createArrayMethod = _dereq_(12) , createArrayIncludes = _dereq_(11) , speciesConstructor = _dereq_(95) , ArrayIterators = _dereq_(131) , Iterators = _dereq_(56) , $iterDetect = _dereq_(54) , setSpecies = _dereq_(91) , arrayFill = _dereq_(9) , arrayCopyWithin = _dereq_(8) , $DP = _dereq_(67) , $GOPD = _dereq_(70) , dP = $DP.f , gOPD = $GOPD.f , RangeError = global.RangeError , TypeError = global.TypeError , Uint8Array = global.Uint8Array , ARRAY_BUFFER = 'ArrayBuffer' , SHARED_BUFFER = 'Shared' + ARRAY_BUFFER , BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT' , PROTOTYPE = 'prototype' , ArrayProto = Array[PROTOTYPE] , $ArrayBuffer = $buffer.ArrayBuffer , $DataView = $buffer.DataView , arrayForEach = createArrayMethod(0) , arrayFilter = createArrayMethod(2) , arraySome = createArrayMethod(3) , arrayEvery = createArrayMethod(4) , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , arrayIncludes = createArrayIncludes(true) , arrayIndexOf = createArrayIncludes(false) , arrayValues = ArrayIterators.values , arrayKeys = ArrayIterators.keys , arrayEntries = ArrayIterators.entries , arrayLastIndexOf = ArrayProto.lastIndexOf , arrayReduce = ArrayProto.reduce , arrayReduceRight = ArrayProto.reduceRight , arrayJoin = ArrayProto.join , arraySort = ArrayProto.sort , arraySlice = ArrayProto.slice , arrayToString = ArrayProto.toString , arrayToLocaleString = ArrayProto.toLocaleString , ITERATOR = wks('iterator') , TAG = wks('toStringTag') , TYPED_CONSTRUCTOR = uid('typed_constructor') , DEF_CONSTRUCTOR = uid('def_constructor') , ALL_CONSTRUCTORS = $typed.CONSTR , TYPED_ARRAY = $typed.TYPED , VIEW = $typed.VIEW , WRONG_LENGTH = 'Wrong length!'; var $map = createArrayMethod(1, function(O, length){ return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); }); var LITTLE_ENDIAN = fails(function(){ return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; }); var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){ new Uint8Array(1).set({}); }); var strictToLength = function(it, SAME){ if(it === undefined)throw TypeError(WRONG_LENGTH); var number = +it , length = toLength(it); if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH); return length; }; var toOffset = function(it, BYTES){ var offset = toInteger(it); if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!'); return offset; }; var validate = function(it){ if(isObject(it) && TYPED_ARRAY in it)return it; throw TypeError(it + ' is not a typed array!'); }; var allocate = function(C, length){ if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){ throw TypeError('It is not a typed array constructor!'); } return new C(length); }; var speciesFromList = function(O, list){ return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); }; var fromList = function(C, list){ var index = 0 , length = list.length , result = allocate(C, length); while(length > index)result[index] = list[index++]; return result; }; var addGetter = function(it, key, internal){ dP(it, key, {get: function(){ return this._d[internal]; }}); }; var $from = function from(source /*, mapfn, thisArg */){ var O = toObject(source) , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , iterFn = getIterFn(O) , i, length, values, result, step, iterator; if(iterFn != undefined && !isArrayIter(iterFn)){ for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){ values.push(step.value); } O = values; } if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2); for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){ result[i] = mapping ? mapfn(O[i], i) : O[i]; } return result; }; var $of = function of(/*...items*/){ var index = 0 , length = arguments.length , result = allocate(this, length); while(length > index)result[index] = arguments[index++]; return result; }; // iOS Safari 6.x fails here var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); }); var $toLocaleString = function toLocaleString(){ return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); }; var proto = { copyWithin: function copyWithin(target, start /*, end */){ return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); }, every: function every(callbackfn /*, thisArg */){ return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars return arrayFill.apply(validate(this), arguments); }, filter: function filter(callbackfn /*, thisArg */){ return speciesFromList(this, arrayFilter(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined)); }, find: function find(predicate /*, thisArg */){ return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }, findIndex: function findIndex(predicate /*, thisArg */){ return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }, forEach: function forEach(callbackfn /*, thisArg */){ arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, indexOf: function indexOf(searchElement /*, fromIndex */){ return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }, includes: function includes(searchElement /*, fromIndex */){ return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }, join: function join(separator){ // eslint-disable-line no-unused-vars return arrayJoin.apply(validate(this), arguments); }, lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars return arrayLastIndexOf.apply(validate(this), arguments); }, map: function map(mapfn /*, thisArg */){ return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); }, reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars return arrayReduce.apply(validate(this), arguments); }, reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars return arrayReduceRight.apply(validate(this), arguments); }, reverse: function reverse(){ var that = this , length = validate(that).length , middle = Math.floor(length / 2) , index = 0 , value; while(index < middle){ value = that[index]; that[index++] = that[--length]; that[length] = value; } return that; }, some: function some(callbackfn /*, thisArg */){ return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, sort: function sort(comparefn){ return arraySort.call(validate(this), comparefn); }, subarray: function subarray(begin, end){ var O = validate(this) , length = O.length , $begin = toIndex(begin, length); return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( O.buffer, O.byteOffset + $begin * O.BYTES_PER_ELEMENT, toLength((end === undefined ? length : toIndex(end, length)) - $begin) ); } }; var $slice = function slice(start, end){ return speciesFromList(this, arraySlice.call(validate(this), start, end)); }; var $set = function set(arrayLike /*, offset */){ validate(this); var offset = toOffset(arguments[1], 1) , length = this.length , src = toObject(arrayLike) , len = toLength(src.length) , index = 0; if(len + offset > length)throw RangeError(WRONG_LENGTH); while(index < len)this[offset + index] = src[index++]; }; var $iterators = { entries: function entries(){ return arrayEntries.call(validate(this)); }, keys: function keys(){ return arrayKeys.call(validate(this)); }, values: function values(){ return arrayValues.call(validate(this)); } }; var isTAIndex = function(target, key){ return isObject(target) && target[TYPED_ARRAY] && typeof key != 'symbol' && key in target && String(+key) == String(key); }; var $getDesc = function getOwnPropertyDescriptor(target, key){ return isTAIndex(target, key = toPrimitive(key, true)) ? propertyDesc(2, target[key]) : gOPD(target, key); }; var $setDesc = function defineProperty(target, key, desc){ if(isTAIndex(target, key = toPrimitive(key, true)) && isObject(desc) && has(desc, 'value') && !has(desc, 'get') && !has(desc, 'set') // TODO: add validation descriptor w/o calling accessors && !desc.configurable && (!has(desc, 'writable') || desc.writable) && (!has(desc, 'enumerable') || desc.enumerable) ){ target[key] = desc.value; return target; } else return dP(target, key, desc); }; if(!ALL_CONSTRUCTORS){ $GOPD.f = $getDesc; $DP.f = $setDesc; } $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { getOwnPropertyDescriptor: $getDesc, defineProperty: $setDesc }); if(fails(function(){ arrayToString.call({}); })){ arrayToString = arrayToLocaleString = function toString(){ return arrayJoin.call(this); } } var $TypedArrayPrototype$ = redefineAll({}, proto); redefineAll($TypedArrayPrototype$, $iterators); hide($TypedArrayPrototype$, ITERATOR, $iterators.values); redefineAll($TypedArrayPrototype$, { slice: $slice, set: $set, constructor: function(){ /* noop */ }, toString: arrayToString, toLocaleString: $toLocaleString }); addGetter($TypedArrayPrototype$, 'buffer', 'b'); addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); addGetter($TypedArrayPrototype$, 'byteLength', 'l'); addGetter($TypedArrayPrototype$, 'length', 'e'); dP($TypedArrayPrototype$, TAG, { get: function(){ return this[TYPED_ARRAY]; } }); module.exports = function(KEY, BYTES, wrapper, CLAMPED){ CLAMPED = !!CLAMPED; var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array' , ISNT_UINT8 = NAME != 'Uint8Array' , GETTER = 'get' + KEY , SETTER = 'set' + KEY , TypedArray = global[NAME] , Base = TypedArray || {} , TAC = TypedArray && getPrototypeOf(TypedArray) , FORCED = !TypedArray || !$typed.ABV , O = {} , TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; var getter = function(that, index){ var data = that._d; return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); }; var setter = function(that, index, value){ var data = that._d; if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); }; var addElement = function(that, index){ dP(that, index, { get: function(){ return getter(this, index); }, set: function(value){ return setter(this, index, value); }, enumerable: true }); }; if(FORCED){ TypedArray = wrapper(function(that, data, $offset, $length){ anInstance(that, TypedArray, NAME, '_d'); var index = 0 , offset = 0 , buffer, byteLength, length, klass; if(!isObject(data)){ length = strictToLength(data, true) byteLength = length * BYTES; buffer = new $ArrayBuffer(byteLength); } else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ buffer = data; offset = toOffset($offset, BYTES); var $len = data.byteLength; if($length === undefined){ if($len % BYTES)throw RangeError(WRONG_LENGTH); byteLength = $len - offset; if(byteLength < 0)throw RangeError(WRONG_LENGTH); } else { byteLength = toLength($length) * BYTES; if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH); } length = byteLength / BYTES; } else if(TYPED_ARRAY in data){ return fromList(TypedArray, data); } else { return $from.call(TypedArray, data); } hide(that, '_d', { b: buffer, o: offset, l: byteLength, e: length, v: new $DataView(buffer) }); while(index < length)addElement(that, index++); }); TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); hide(TypedArrayPrototype, 'constructor', TypedArray); } else if(!$iterDetect(function(iter){ // V8 works with iterators, but fails in many other cases // https://code.google.com/p/v8/issues/detail?id=4552 new TypedArray(null); // eslint-disable-line no-new new TypedArray(iter); // eslint-disable-line no-new }, true)){ TypedArray = wrapper(function(that, data, $offset, $length){ anInstance(that, TypedArray, NAME); var klass; // `ws` module bug, temporarily remove validation length for Uint8Array // https://github.com/websockets/ws/pull/645 if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8)); if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ return $length !== undefined ? new Base(data, toOffset($offset, BYTES), $length) : $offset !== undefined ? new Base(data, toOffset($offset, BYTES)) : new Base(data); } if(TYPED_ARRAY in data)return fromList(TypedArray, data); return $from.call(TypedArray, data); }); arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){ if(!(key in TypedArray))hide(TypedArray, key, Base[key]); }); TypedArray[PROTOTYPE] = TypedArrayPrototype; if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray; } var $nativeIterator = TypedArrayPrototype[ITERATOR] , CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined) , $iterator = $iterators.values; hide(TypedArray, TYPED_CONSTRUCTOR, true); hide(TypedArrayPrototype, TYPED_ARRAY, NAME); hide(TypedArrayPrototype, VIEW, true); hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){ dP(TypedArrayPrototype, TAG, { get: function(){ return NAME; } }); } O[NAME] = TypedArray; $export($export.G + $export.W + $export.F * (TypedArray != Base), O); $export($export.S, NAME, { BYTES_PER_ELEMENT: BYTES, from: $from, of: $of }); if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); $export($export.P, NAME, proto); setSpecies(NAME); $export($export.P + $export.F * FORCED_SET, NAME, {set: $set}); $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); $export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString}); $export($export.P + $export.F * fails(function(){ new TypedArray(1).slice(); }), NAME, {slice: $slice}); $export($export.P + $export.F * (fails(function(){ return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString() }) || !fails(function(){ TypedArrayPrototype.toLocaleString.call([1, 2]); })), NAME, {toLocaleString: $toLocaleString}); Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator); }; } else module.exports = function(){ /* empty */ }; },{"105":105,"106":106,"108":108,"109":109,"11":11,"110":110,"112":112,"113":113,"114":114,"117":117,"118":118,"119":119,"12":12,"131":131,"17":17,"25":25,"28":28,"32":32,"34":34,"38":38,"39":39,"40":40,"46":46,"48":48,"49":49,"54":54,"56":56,"58":58,"6":6,"66":66,"67":67,"70":70,"72":72,"74":74,"8":8,"85":85,"86":86,"89":89,"9":9,"91":91,"95":95}],112:[function(_dereq_,module,exports){ 'use strict'; var global = _dereq_(38) , DESCRIPTORS = _dereq_(28) , LIBRARY = _dereq_(58) , $typed = _dereq_(113) , hide = _dereq_(40) , redefineAll = _dereq_(86) , fails = _dereq_(34) , anInstance = _dereq_(6) , toInteger = _dereq_(106) , toLength = _dereq_(108) , gOPN = _dereq_(72).f , dP = _dereq_(67).f , arrayFill = _dereq_(9) , setToStringTag = _dereq_(92) , ARRAY_BUFFER = 'ArrayBuffer' , DATA_VIEW = 'DataView' , PROTOTYPE = 'prototype' , WRONG_LENGTH = 'Wrong length!' , WRONG_INDEX = 'Wrong index!' , $ArrayBuffer = global[ARRAY_BUFFER] , $DataView = global[DATA_VIEW] , Math = global.Math , parseInt = global.parseInt , RangeError = global.RangeError , Infinity = global.Infinity , BaseBuffer = $ArrayBuffer , abs = Math.abs , pow = Math.pow , min = Math.min , floor = Math.floor , log = Math.log , LN2 = Math.LN2 , BUFFER = 'buffer' , BYTE_LENGTH = 'byteLength' , BYTE_OFFSET = 'byteOffset' , $BUFFER = DESCRIPTORS ? '_b' : BUFFER , $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH , $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; // IEEE754 conversions based on https://github.com/feross/ieee754 var packIEEE754 = function(value, mLen, nBytes){ var buffer = Array(nBytes) , eLen = nBytes * 8 - mLen - 1 , eMax = (1 << eLen) - 1 , eBias = eMax >> 1 , rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0 , i = 0 , s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0 , e, m, c; value = abs(value) if(value != value || value === Infinity){ m = value != value ? 1 : 0; e = eMax; } else { e = floor(log(value) / LN2); if(value * (c = pow(2, -e)) < 1){ e--; c *= 2; } if(e + eBias >= 1){ value += rt / c; } else { value += rt * pow(2, 1 - eBias); } if(value * c >= 2){ e++; c /= 2; } if(e + eBias >= eMax){ m = 0; e = eMax; } else if(e + eBias >= 1){ m = (value * c - 1) * pow(2, mLen); e = e + eBias; } else { m = value * pow(2, eBias - 1) * pow(2, mLen); e = 0; } } for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); e = e << mLen | m; eLen += mLen; for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); buffer[--i] |= s * 128; return buffer; }; var unpackIEEE754 = function(buffer, mLen, nBytes){ var eLen = nBytes * 8 - mLen - 1 , eMax = (1 << eLen) - 1 , eBias = eMax >> 1 , nBits = eLen - 7 , i = nBytes - 1 , s = buffer[i--] , e = s & 127 , m; s >>= 7; for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); if(e === 0){ e = 1 - eBias; } else if(e === eMax){ return m ? NaN : s ? -Infinity : Infinity; } else { m = m + pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * pow(2, e - mLen); }; var unpackI32 = function(bytes){ return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; }; var packI8 = function(it){ return [it & 0xff]; }; var packI16 = function(it){ return [it & 0xff, it >> 8 & 0xff]; }; var packI32 = function(it){ return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; }; var packF64 = function(it){ return packIEEE754(it, 52, 8); }; var packF32 = function(it){ return packIEEE754(it, 23, 4); }; var addGetter = function(C, key, internal){ dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }}); }; var get = function(view, bytes, index, isLittleEndian){ var numIndex = +index , intIndex = toInteger(numIndex); if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); var store = view[$BUFFER]._b , start = intIndex + view[$OFFSET] , pack = store.slice(start, start + bytes); return isLittleEndian ? pack : pack.reverse(); }; var set = function(view, bytes, index, conversion, value, isLittleEndian){ var numIndex = +index , intIndex = toInteger(numIndex); if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); var store = view[$BUFFER]._b , start = intIndex + view[$OFFSET] , pack = conversion(+value); for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; }; var validateArrayBufferArguments = function(that, length){ anInstance(that, $ArrayBuffer, ARRAY_BUFFER); var numberLength = +length , byteLength = toLength(numberLength); if(numberLength != byteLength)throw RangeError(WRONG_LENGTH); return byteLength; }; if(!$typed.ABV){ $ArrayBuffer = function ArrayBuffer(length){ var byteLength = validateArrayBufferArguments(this, length); this._b = arrayFill.call(Array(byteLength), 0); this[$LENGTH] = byteLength; }; $DataView = function DataView(buffer, byteOffset, byteLength){ anInstance(this, $DataView, DATA_VIEW); anInstance(buffer, $ArrayBuffer, DATA_VIEW); var bufferLength = buffer[$LENGTH] , offset = toInteger(byteOffset); if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!'); byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH); this[$BUFFER] = buffer; this[$OFFSET] = offset; this[$LENGTH] = byteLength; }; if(DESCRIPTORS){ addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); addGetter($DataView, BUFFER, '_b'); addGetter($DataView, BYTE_LENGTH, '_l'); addGetter($DataView, BYTE_OFFSET, '_o'); } redefineAll($DataView[PROTOTYPE], { getInt8: function getInt8(byteOffset){ return get(this, 1, byteOffset)[0] << 24 >> 24; }, getUint8: function getUint8(byteOffset){ return get(this, 1, byteOffset)[0]; }, getInt16: function getInt16(byteOffset /*, littleEndian */){ var bytes = get(this, 2, byteOffset, arguments[1]); return (bytes[1] << 8 | bytes[0]) << 16 >> 16; }, getUint16: function getUint16(byteOffset /*, littleEndian */){ var bytes = get(this, 2, byteOffset, arguments[1]); return bytes[1] << 8 | bytes[0]; }, getInt32: function getInt32(byteOffset /*, littleEndian */){ return unpackI32(get(this, 4, byteOffset, arguments[1])); }, getUint32: function getUint32(byteOffset /*, littleEndian */){ return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; }, getFloat32: function getFloat32(byteOffset /*, littleEndian */){ return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); }, getFloat64: function getFloat64(byteOffset /*, littleEndian */){ return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); }, setInt8: function setInt8(byteOffset, value){ set(this, 1, byteOffset, packI8, value); }, setUint8: function setUint8(byteOffset, value){ set(this, 1, byteOffset, packI8, value); }, setInt16: function setInt16(byteOffset, value /*, littleEndian */){ set(this, 2, byteOffset, packI16, value, arguments[2]); }, setUint16: function setUint16(byteOffset, value /*, littleEndian */){ set(this, 2, byteOffset, packI16, value, arguments[2]); }, setInt32: function setInt32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packI32, value, arguments[2]); }, setUint32: function setUint32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packI32, value, arguments[2]); }, setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packF32, value, arguments[2]); }, setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){ set(this, 8, byteOffset, packF64, value, arguments[2]); } }); } else { if(!fails(function(){ new $ArrayBuffer; // eslint-disable-line no-new }) || !fails(function(){ new $ArrayBuffer(.5); // eslint-disable-line no-new })){ $ArrayBuffer = function ArrayBuffer(length){ return new BaseBuffer(validateArrayBufferArguments(this, length)); }; var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){ if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]); }; if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer; } // iOS Safari 7.x bug var view = new $DataView(new $ArrayBuffer(2)) , $setInt8 = $DataView[PROTOTYPE].setInt8; view.setInt8(0, 2147483648); view.setInt8(1, 2147483649); if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], { setInt8: function setInt8(byteOffset, value){ $setInt8.call(this, byteOffset, value << 24 >> 24); }, setUint8: function setUint8(byteOffset, value){ $setInt8.call(this, byteOffset, value << 24 >> 24); } }, true); } setToStringTag($ArrayBuffer, ARRAY_BUFFER); setToStringTag($DataView, DATA_VIEW); hide($DataView[PROTOTYPE], $typed.VIEW, true); exports[ARRAY_BUFFER] = $ArrayBuffer; exports[DATA_VIEW] = $DataView; },{"106":106,"108":108,"113":113,"28":28,"34":34,"38":38,"40":40,"58":58,"6":6,"67":67,"72":72,"86":86,"9":9,"92":92}],113:[function(_dereq_,module,exports){ var global = _dereq_(38) , hide = _dereq_(40) , uid = _dereq_(114) , TYPED = uid('typed_array') , VIEW = uid('view') , ABV = !!(global.ArrayBuffer && global.DataView) , CONSTR = ABV , i = 0, l = 9, Typed; var TypedArrayConstructors = ( 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' ).split(','); while(i < l){ if(Typed = global[TypedArrayConstructors[i++]]){ hide(Typed.prototype, TYPED, true); hide(Typed.prototype, VIEW, true); } else CONSTR = false; } module.exports = { ABV: ABV, CONSTR: CONSTR, TYPED: TYPED, VIEW: VIEW }; },{"114":114,"38":38,"40":40}],114:[function(_dereq_,module,exports){ var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; },{}],115:[function(_dereq_,module,exports){ var global = _dereq_(38) , core = _dereq_(23) , LIBRARY = _dereq_(58) , wksExt = _dereq_(116) , defineProperty = _dereq_(67).f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; },{"116":116,"23":23,"38":38,"58":58,"67":67}],116:[function(_dereq_,module,exports){ exports.f = _dereq_(117); },{"117":117}],117:[function(_dereq_,module,exports){ var store = _dereq_(94)('wks') , uid = _dereq_(114) , Symbol = _dereq_(38).Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; },{"114":114,"38":38,"94":94}],118:[function(_dereq_,module,exports){ var classof = _dereq_(17) , ITERATOR = _dereq_(117)('iterator') , Iterators = _dereq_(56); module.exports = _dereq_(23).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; },{"117":117,"17":17,"23":23,"56":56}],119:[function(_dereq_,module,exports){ var classof = _dereq_(17) , ITERATOR = _dereq_(117)('iterator') , Iterators = _dereq_(56); module.exports = _dereq_(23).isIterable = function(it){ var O = Object(it); return O[ITERATOR] !== undefined || '@@iterator' in O || Iterators.hasOwnProperty(classof(O)); }; },{"117":117,"17":17,"23":23,"56":56}],120:[function(_dereq_,module,exports){ // https://github.com/benjamingr/RexExp.escape var $export = _dereq_(32) , $re = _dereq_(88)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); $export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }}); },{"32":32,"88":88}],121:[function(_dereq_,module,exports){ // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) var $export = _dereq_(32); $export($export.P, 'Array', {copyWithin: _dereq_(8)}); _dereq_(5)('copyWithin'); },{"32":32,"5":5,"8":8}],122:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $every = _dereq_(12)(4); $export($export.P + $export.F * !_dereq_(96)([].every, true), 'Array', { // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: function every(callbackfn /* , thisArg */){ return $every(this, callbackfn, arguments[1]); } }); },{"12":12,"32":32,"96":96}],123:[function(_dereq_,module,exports){ // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) var $export = _dereq_(32); $export($export.P, 'Array', {fill: _dereq_(9)}); _dereq_(5)('fill'); },{"32":32,"5":5,"9":9}],124:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $filter = _dereq_(12)(2); $export($export.P + $export.F * !_dereq_(96)([].filter, true), 'Array', { // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: function filter(callbackfn /* , thisArg */){ return $filter(this, callbackfn, arguments[1]); } }); },{"12":12,"32":32,"96":96}],125:[function(_dereq_,module,exports){ 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var $export = _dereq_(32) , $find = _dereq_(12)(6) , KEY = 'findIndex' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { findIndex: function findIndex(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); _dereq_(5)(KEY); },{"12":12,"32":32,"5":5}],126:[function(_dereq_,module,exports){ 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var $export = _dereq_(32) , $find = _dereq_(12)(5) , KEY = 'find' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { find: function find(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); _dereq_(5)(KEY); },{"12":12,"32":32,"5":5}],127:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $forEach = _dereq_(12)(0) , STRICT = _dereq_(96)([].forEach, true); $export($export.P + $export.F * !STRICT, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: function forEach(callbackfn /* , thisArg */){ return $forEach(this, callbackfn, arguments[1]); } }); },{"12":12,"32":32,"96":96}],128:[function(_dereq_,module,exports){ 'use strict'; var ctx = _dereq_(25) , $export = _dereq_(32) , toObject = _dereq_(109) , call = _dereq_(51) , isArrayIter = _dereq_(46) , toLength = _dereq_(108) , createProperty = _dereq_(24) , getIterFn = _dereq_(118); $export($export.S + $export.F * !_dereq_(54)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); },{"108":108,"109":109,"118":118,"24":24,"25":25,"32":32,"46":46,"51":51,"54":54}],129:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $indexOf = _dereq_(11)(false) , $native = [].indexOf , NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; $export($export.P + $export.F * (NEGATIVE_ZERO || !_dereq_(96)($native)), 'Array', { // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: function indexOf(searchElement /*, fromIndex = 0 */){ return NEGATIVE_ZERO // convert -0 to +0 ? $native.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments[1]); } }); },{"11":11,"32":32,"96":96}],130:[function(_dereq_,module,exports){ // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = _dereq_(32); $export($export.S, 'Array', {isArray: _dereq_(47)}); },{"32":32,"47":47}],131:[function(_dereq_,module,exports){ 'use strict'; var addToUnscopables = _dereq_(5) , step = _dereq_(55) , Iterators = _dereq_(56) , toIObject = _dereq_(107); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = _dereq_(53)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); },{"107":107,"5":5,"53":53,"55":55,"56":56}],132:[function(_dereq_,module,exports){ 'use strict'; // 22.1.3.13 Array.prototype.join(separator) var $export = _dereq_(32) , toIObject = _dereq_(107) , arrayJoin = [].join; // fallback for not array-like strings $export($export.P + $export.F * (_dereq_(45) != Object || !_dereq_(96)(arrayJoin)), 'Array', { join: function join(separator){ return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); } }); },{"107":107,"32":32,"45":45,"96":96}],133:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , toIObject = _dereq_(107) , toInteger = _dereq_(106) , toLength = _dereq_(108) , $native = [].lastIndexOf , NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; $export($export.P + $export.F * (NEGATIVE_ZERO || !_dereq_(96)($native)), 'Array', { // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){ // convert -0 to +0 if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0; var O = toIObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1])); if(index < 0)index = length + index; for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0; return -1; } }); },{"106":106,"107":107,"108":108,"32":32,"96":96}],134:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $map = _dereq_(12)(1); $export($export.P + $export.F * !_dereq_(96)([].map, true), 'Array', { // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: function map(callbackfn /* , thisArg */){ return $map(this, callbackfn, arguments[1]); } }); },{"12":12,"32":32,"96":96}],135:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , createProperty = _dereq_(24); // WebKit Array.of isn't generic $export($export.S + $export.F * _dereq_(34)(function(){ function F(){} return !(Array.of.call(F) instanceof F); }), 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , aLen = arguments.length , result = new (typeof this == 'function' ? this : Array)(aLen); while(aLen > index)createProperty(result, index, arguments[index++]); result.length = aLen; return result; } }); },{"24":24,"32":32,"34":34}],136:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $reduce = _dereq_(13); $export($export.P + $export.F * !_dereq_(96)([].reduceRight, true), 'Array', { // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: function reduceRight(callbackfn /* , initialValue */){ return $reduce(this, callbackfn, arguments.length, arguments[1], true); } }); },{"13":13,"32":32,"96":96}],137:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $reduce = _dereq_(13); $export($export.P + $export.F * !_dereq_(96)([].reduce, true), 'Array', { // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: function reduce(callbackfn /* , initialValue */){ return $reduce(this, callbackfn, arguments.length, arguments[1], false); } }); },{"13":13,"32":32,"96":96}],138:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , html = _dereq_(41) , cof = _dereq_(18) , toIndex = _dereq_(105) , toLength = _dereq_(108) , arraySlice = [].slice; // fallback for not array-like ES3 strings and DOM objects $export($export.P + $export.F * _dereq_(34)(function(){ if(html)arraySlice.call(html); }), 'Array', { slice: function slice(begin, end){ var len = toLength(this.length) , klass = cof(this); end = end === undefined ? len : end; if(klass == 'Array')return arraySlice.call(this, begin, end); var start = toIndex(begin, len) , upTo = toIndex(end, len) , size = toLength(upTo - start) , cloned = Array(size) , i = 0; for(; i < size; i++)cloned[i] = klass == 'String' ? this.charAt(start + i) : this[start + i]; return cloned; } }); },{"105":105,"108":108,"18":18,"32":32,"34":34,"41":41}],139:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $some = _dereq_(12)(3); $export($export.P + $export.F * !_dereq_(96)([].some, true), 'Array', { // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: function some(callbackfn /* , thisArg */){ return $some(this, callbackfn, arguments[1]); } }); },{"12":12,"32":32,"96":96}],140:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , aFunction = _dereq_(3) , toObject = _dereq_(109) , fails = _dereq_(34) , $sort = [].sort , test = [1, 2, 3]; $export($export.P + $export.F * (fails(function(){ // IE8- test.sort(undefined); }) || !fails(function(){ // V8 bug test.sort(null); // Old WebKit }) || !_dereq_(96)($sort)), 'Array', { // 22.1.3.25 Array.prototype.sort(comparefn) sort: function sort(comparefn){ return comparefn === undefined ? $sort.call(toObject(this)) : $sort.call(toObject(this), aFunction(comparefn)); } }); },{"109":109,"3":3,"32":32,"34":34,"96":96}],141:[function(_dereq_,module,exports){ _dereq_(91)('Array'); },{"91":91}],142:[function(_dereq_,module,exports){ // 20.3.3.1 / 15.9.4.4 Date.now() var $export = _dereq_(32); $export($export.S, 'Date', {now: function(){ return new Date().getTime(); }}); },{"32":32}],143:[function(_dereq_,module,exports){ 'use strict'; // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() var $export = _dereq_(32) , fails = _dereq_(34) , getTime = Date.prototype.getTime; var lz = function(num){ return num > 9 ? num : '0' + num; }; // PhantomJS / old WebKit has a broken implementations $export($export.P + $export.F * (fails(function(){ return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z'; }) || !fails(function(){ new Date(NaN).toISOString(); })), 'Date', { toISOString: function toISOString(){ if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; } }); },{"32":32,"34":34}],144:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , toObject = _dereq_(109) , toPrimitive = _dereq_(110); $export($export.P + $export.F * _dereq_(34)(function(){ return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1; }), 'Date', { toJSON: function toJSON(key){ var O = toObject(this) , pv = toPrimitive(O); return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); } }); },{"109":109,"110":110,"32":32,"34":34}],145:[function(_dereq_,module,exports){ var TO_PRIMITIVE = _dereq_(117)('toPrimitive') , proto = Date.prototype; if(!(TO_PRIMITIVE in proto))_dereq_(40)(proto, TO_PRIMITIVE, _dereq_(26)); },{"117":117,"26":26,"40":40}],146:[function(_dereq_,module,exports){ var DateProto = Date.prototype , INVALID_DATE = 'Invalid Date' , TO_STRING = 'toString' , $toString = DateProto[TO_STRING] , getTime = DateProto.getTime; if(new Date(NaN) + '' != INVALID_DATE){ _dereq_(87)(DateProto, TO_STRING, function toString(){ var value = getTime.call(this); return value === value ? $toString.call(this) : INVALID_DATE; }); } },{"87":87}],147:[function(_dereq_,module,exports){ // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) var $export = _dereq_(32); $export($export.P, 'Function', {bind: _dereq_(16)}); },{"16":16,"32":32}],148:[function(_dereq_,module,exports){ 'use strict'; var isObject = _dereq_(49) , getPrototypeOf = _dereq_(74) , HAS_INSTANCE = _dereq_(117)('hasInstance') , FunctionProto = Function.prototype; // 19.2.3.6 Function.prototype[@@hasInstance](V) if(!(HAS_INSTANCE in FunctionProto))_dereq_(67).f(FunctionProto, HAS_INSTANCE, {value: function(O){ if(typeof this != 'function' || !isObject(O))return false; if(!isObject(this.prototype))return O instanceof this; // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: while(O = getPrototypeOf(O))if(this.prototype === O)return true; return false; }}); },{"117":117,"49":49,"67":67,"74":74}],149:[function(_dereq_,module,exports){ var dP = _dereq_(67).f , createDesc = _dereq_(85) , has = _dereq_(39) , FProto = Function.prototype , nameRE = /^\s*function ([^ (]*)/ , NAME = 'name'; var isExtensible = Object.isExtensible || function(){ return true; }; // 19.2.4.2 name NAME in FProto || _dereq_(28) && dP(FProto, NAME, { configurable: true, get: function(){ try { var that = this , name = ('' + that).match(nameRE)[1]; has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name)); return name; } catch(e){ return ''; } } }); },{"28":28,"39":39,"67":67,"85":85}],150:[function(_dereq_,module,exports){ 'use strict'; var strong = _dereq_(19); // 23.1 Map Objects module.exports = _dereq_(22)('Map', function(get){ return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); },{"19":19,"22":22}],151:[function(_dereq_,module,exports){ // 20.2.2.3 Math.acosh(x) var $export = _dereq_(32) , log1p = _dereq_(60) , sqrt = Math.sqrt , $acosh = Math.acosh; $export($export.S + $export.F * !($acosh // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 && Math.floor($acosh(Number.MAX_VALUE)) == 710 // Tor Browser bug: Math.acosh(Infinity) -> NaN && $acosh(Infinity) == Infinity ), 'Math', { acosh: function acosh(x){ return (x = +x) < 1 ? NaN : x > 94906265.62425156 ? Math.log(x) + Math.LN2 : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); } }); },{"32":32,"60":60}],152:[function(_dereq_,module,exports){ // 20.2.2.5 Math.asinh(x) var $export = _dereq_(32) , $asinh = Math.asinh; function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); } // Tor Browser bug: Math.asinh(0) -> -0 $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh}); },{"32":32}],153:[function(_dereq_,module,exports){ // 20.2.2.7 Math.atanh(x) var $export = _dereq_(32) , $atanh = Math.atanh; // Tor Browser bug: Math.atanh(-0) -> 0 $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { atanh: function atanh(x){ return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; } }); },{"32":32}],154:[function(_dereq_,module,exports){ // 20.2.2.9 Math.cbrt(x) var $export = _dereq_(32) , sign = _dereq_(61); $export($export.S, 'Math', { cbrt: function cbrt(x){ return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); } }); },{"32":32,"61":61}],155:[function(_dereq_,module,exports){ // 20.2.2.11 Math.clz32(x) var $export = _dereq_(32); $export($export.S, 'Math', { clz32: function clz32(x){ return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; } }); },{"32":32}],156:[function(_dereq_,module,exports){ // 20.2.2.12 Math.cosh(x) var $export = _dereq_(32) , exp = Math.exp; $export($export.S, 'Math', { cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; } }); },{"32":32}],157:[function(_dereq_,module,exports){ // 20.2.2.14 Math.expm1(x) var $export = _dereq_(32) , $expm1 = _dereq_(59); $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1}); },{"32":32,"59":59}],158:[function(_dereq_,module,exports){ // 20.2.2.16 Math.fround(x) var $export = _dereq_(32) , sign = _dereq_(61) , pow = Math.pow , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); var roundTiesToEven = function(n){ return n + 1 / EPSILON - 1 / EPSILON; }; $export($export.S, 'Math', { fround: function fround(x){ var $abs = Math.abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; } }); },{"32":32,"61":61}],159:[function(_dereq_,module,exports){ // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) var $export = _dereq_(32) , abs = Math.abs; $export($export.S, 'Math', { hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , i = 0 , aLen = arguments.length , larg = 0 , arg, div; while(i < aLen){ arg = abs(arguments[i++]); if(larg < arg){ div = larg / arg; sum = sum * div * div + 1; larg = arg; } else if(arg > 0){ div = arg / larg; sum += div * div; } else sum += arg; } return larg === Infinity ? Infinity : larg * Math.sqrt(sum); } }); },{"32":32}],160:[function(_dereq_,module,exports){ // 20.2.2.18 Math.imul(x, y) var $export = _dereq_(32) , $imul = Math.imul; // some WebKit versions fails with big numbers, some has wrong arity $export($export.S + $export.F * _dereq_(34)(function(){ return $imul(0xffffffff, 5) != -5 || $imul.length != 2; }), 'Math', { imul: function imul(x, y){ var UINT16 = 0xffff , xn = +x , yn = +y , xl = UINT16 & xn , yl = UINT16 & yn; return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); } }); },{"32":32,"34":34}],161:[function(_dereq_,module,exports){ // 20.2.2.21 Math.log10(x) var $export = _dereq_(32); $export($export.S, 'Math', { log10: function log10(x){ return Math.log(x) / Math.LN10; } }); },{"32":32}],162:[function(_dereq_,module,exports){ // 20.2.2.20 Math.log1p(x) var $export = _dereq_(32); $export($export.S, 'Math', {log1p: _dereq_(60)}); },{"32":32,"60":60}],163:[function(_dereq_,module,exports){ // 20.2.2.22 Math.log2(x) var $export = _dereq_(32); $export($export.S, 'Math', { log2: function log2(x){ return Math.log(x) / Math.LN2; } }); },{"32":32}],164:[function(_dereq_,module,exports){ // 20.2.2.28 Math.sign(x) var $export = _dereq_(32); $export($export.S, 'Math', {sign: _dereq_(61)}); },{"32":32,"61":61}],165:[function(_dereq_,module,exports){ // 20.2.2.30 Math.sinh(x) var $export = _dereq_(32) , expm1 = _dereq_(59) , exp = Math.exp; // V8 near Chromium 38 has a problem with very small numbers $export($export.S + $export.F * _dereq_(34)(function(){ return !Math.sinh(-2e-17) != -2e-17; }), 'Math', { sinh: function sinh(x){ return Math.abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); } }); },{"32":32,"34":34,"59":59}],166:[function(_dereq_,module,exports){ // 20.2.2.33 Math.tanh(x) var $export = _dereq_(32) , expm1 = _dereq_(59) , exp = Math.exp; $export($export.S, 'Math', { tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); } }); },{"32":32,"59":59}],167:[function(_dereq_,module,exports){ // 20.2.2.34 Math.trunc(x) var $export = _dereq_(32); $export($export.S, 'Math', { trunc: function trunc(it){ return (it > 0 ? Math.floor : Math.ceil)(it); } }); },{"32":32}],168:[function(_dereq_,module,exports){ 'use strict'; var global = _dereq_(38) , has = _dereq_(39) , cof = _dereq_(18) , inheritIfRequired = _dereq_(43) , toPrimitive = _dereq_(110) , fails = _dereq_(34) , gOPN = _dereq_(72).f , gOPD = _dereq_(70).f , dP = _dereq_(67).f , $trim = _dereq_(102).trim , NUMBER = 'Number' , $Number = global[NUMBER] , Base = $Number , proto = $Number.prototype // Opera ~12 has broken Object#toString , BROKEN_COF = cof(_dereq_(66)(proto)) == NUMBER , TRIM = 'trim' in String.prototype; // 7.1.3 ToNumber(argument) var toNumber = function(argument){ var it = toPrimitive(argument, false); if(typeof it == 'string' && it.length > 2){ it = TRIM ? it.trim() : $trim(it, 3); var first = it.charCodeAt(0) , third, radix, maxCode; if(first === 43 || first === 45){ third = it.charCodeAt(2); if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix } else if(first === 48){ switch(it.charCodeAt(1)){ case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i default : return +it; } for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){ code = digits.charCodeAt(i); // parseInt parses a string to a first unavailable symbol // but ToNumber should return NaN if a string contains unavailable symbols if(code < 48 || code > maxCode)return NaN; } return parseInt(digits, radix); } } return +it; }; if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){ $Number = function Number(value){ var it = arguments.length < 1 ? 0 : value , that = this; return that instanceof $Number // check on 1..constructor(foo) case && (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER) ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); }; for(var keys = _dereq_(28) ? gOPN(Base) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES6 (in case, if modules with ES6 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' ).split(','), j = 0, key; keys.length > j; j++){ if(has(Base, key = keys[j]) && !has($Number, key)){ dP($Number, key, gOPD(Base, key)); } } $Number.prototype = proto; proto.constructor = $Number; _dereq_(87)(global, NUMBER, $Number); } },{"102":102,"110":110,"18":18,"28":28,"34":34,"38":38,"39":39,"43":43,"66":66,"67":67,"70":70,"72":72,"87":87}],169:[function(_dereq_,module,exports){ // 20.1.2.1 Number.EPSILON var $export = _dereq_(32); $export($export.S, 'Number', {EPSILON: Math.pow(2, -52)}); },{"32":32}],170:[function(_dereq_,module,exports){ // 20.1.2.2 Number.isFinite(number) var $export = _dereq_(32) , _isFinite = _dereq_(38).isFinite; $export($export.S, 'Number', { isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); } }); },{"32":32,"38":38}],171:[function(_dereq_,module,exports){ // 20.1.2.3 Number.isInteger(number) var $export = _dereq_(32); $export($export.S, 'Number', {isInteger: _dereq_(48)}); },{"32":32,"48":48}],172:[function(_dereq_,module,exports){ // 20.1.2.4 Number.isNaN(number) var $export = _dereq_(32); $export($export.S, 'Number', { isNaN: function isNaN(number){ return number != number; } }); },{"32":32}],173:[function(_dereq_,module,exports){ // 20.1.2.5 Number.isSafeInteger(number) var $export = _dereq_(32) , isInteger = _dereq_(48) , abs = Math.abs; $export($export.S, 'Number', { isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= 0x1fffffffffffff; } }); },{"32":32,"48":48}],174:[function(_dereq_,module,exports){ // 20.1.2.6 Number.MAX_SAFE_INTEGER var $export = _dereq_(32); $export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff}); },{"32":32}],175:[function(_dereq_,module,exports){ // 20.1.2.10 Number.MIN_SAFE_INTEGER var $export = _dereq_(32); $export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff}); },{"32":32}],176:[function(_dereq_,module,exports){ var $export = _dereq_(32) , $parseFloat = _dereq_(81); // 20.1.2.12 Number.parseFloat(string) $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat}); },{"32":32,"81":81}],177:[function(_dereq_,module,exports){ var $export = _dereq_(32) , $parseInt = _dereq_(82); // 20.1.2.13 Number.parseInt(string, radix) $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt}); },{"32":32,"82":82}],178:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , anInstance = _dereq_(6) , toInteger = _dereq_(106) , aNumberValue = _dereq_(4) , repeat = _dereq_(101) , $toFixed = 1..toFixed , floor = Math.floor , data = [0, 0, 0, 0, 0, 0] , ERROR = 'Number.toFixed: incorrect invocation!' , ZERO = '0'; var multiply = function(n, c){ var i = -1 , c2 = c; while(++i < 6){ c2 += n * data[i]; data[i] = c2 % 1e7; c2 = floor(c2 / 1e7); } }; var divide = function(n){ var i = 6 , c = 0; while(--i >= 0){ c += data[i]; data[i] = floor(c / n); c = (c % n) * 1e7; } }; var numToString = function(){ var i = 6 , s = ''; while(--i >= 0){ if(s !== '' || i === 0 || data[i] !== 0){ var t = String(data[i]); s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; } } return s; }; var pow = function(x, n, acc){ return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); }; var log = function(x){ var n = 0 , x2 = x; while(x2 >= 4096){ n += 12; x2 /= 4096; } while(x2 >= 2){ n += 1; x2 /= 2; } return n; }; $export($export.P + $export.F * (!!$toFixed && ( 0.00008.toFixed(3) !== '0.000' || 0.9.toFixed(0) !== '1' || 1.255.toFixed(2) !== '1.25' || 1000000000000000128..toFixed(0) !== '1000000000000000128' ) || !_dereq_(34)(function(){ // V8 ~ Android 4.3- $toFixed.call({}); })), 'Number', { toFixed: function toFixed(fractionDigits){ var x = aNumberValue(this, ERROR) , f = toInteger(fractionDigits) , s = '' , m = ZERO , e, z, j, k; if(f < 0 || f > 20)throw RangeError(ERROR); if(x != x)return 'NaN'; if(x <= -1e21 || x >= 1e21)return String(x); if(x < 0){ s = '-'; x = -x; } if(x > 1e-21){ e = log(x * pow(2, 69, 1)) - 69; z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); z *= 0x10000000000000; e = 52 - e; if(e > 0){ multiply(0, z); j = f; while(j >= 7){ multiply(1e7, 0); j -= 7; } multiply(pow(10, j, 1), 0); j = e - 1; while(j >= 23){ divide(1 << 23); j -= 23; } divide(1 << j); multiply(1, 1); divide(2); m = numToString(); } else { multiply(0, z); multiply(1 << -e, 0); m = numToString() + repeat.call(ZERO, f); } } if(f > 0){ k = m.length; m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); } else { m = s + m; } return m; } }); },{"101":101,"106":106,"32":32,"34":34,"4":4,"6":6}],179:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $fails = _dereq_(34) , aNumberValue = _dereq_(4) , $toPrecision = 1..toPrecision; $export($export.P + $export.F * ($fails(function(){ // IE7- return $toPrecision.call(1, undefined) !== '1'; }) || !$fails(function(){ // V8 ~ Android 4.3- $toPrecision.call({}); })), 'Number', { toPrecision: function toPrecision(precision){ var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); } }); },{"32":32,"34":34,"4":4}],180:[function(_dereq_,module,exports){ // 19.1.3.1 Object.assign(target, source) var $export = _dereq_(32); $export($export.S + $export.F, 'Object', {assign: _dereq_(65)}); },{"32":32,"65":65}],181:[function(_dereq_,module,exports){ var $export = _dereq_(32) // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', {create: _dereq_(66)}); },{"32":32,"66":66}],182:[function(_dereq_,module,exports){ var $export = _dereq_(32); // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) $export($export.S + $export.F * !_dereq_(28), 'Object', {defineProperties: _dereq_(68)}); },{"28":28,"32":32,"68":68}],183:[function(_dereq_,module,exports){ var $export = _dereq_(32); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !_dereq_(28), 'Object', {defineProperty: _dereq_(67).f}); },{"28":28,"32":32,"67":67}],184:[function(_dereq_,module,exports){ // 19.1.2.5 Object.freeze(O) var isObject = _dereq_(49) , meta = _dereq_(62).onFreeze; _dereq_(78)('freeze', function($freeze){ return function freeze(it){ return $freeze && isObject(it) ? $freeze(meta(it)) : it; }; }); },{"49":49,"62":62,"78":78}],185:[function(_dereq_,module,exports){ // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = _dereq_(107) , $getOwnPropertyDescriptor = _dereq_(70).f; _dereq_(78)('getOwnPropertyDescriptor', function(){ return function getOwnPropertyDescriptor(it, key){ return $getOwnPropertyDescriptor(toIObject(it), key); }; }); },{"107":107,"70":70,"78":78}],186:[function(_dereq_,module,exports){ // 19.1.2.7 Object.getOwnPropertyNames(O) _dereq_(78)('getOwnPropertyNames', function(){ return _dereq_(71).f; }); },{"71":71,"78":78}],187:[function(_dereq_,module,exports){ // 19.1.2.9 Object.getPrototypeOf(O) var toObject = _dereq_(109) , $getPrototypeOf = _dereq_(74); _dereq_(78)('getPrototypeOf', function(){ return function getPrototypeOf(it){ return $getPrototypeOf(toObject(it)); }; }); },{"109":109,"74":74,"78":78}],188:[function(_dereq_,module,exports){ // 19.1.2.11 Object.isExtensible(O) var isObject = _dereq_(49); _dereq_(78)('isExtensible', function($isExtensible){ return function isExtensible(it){ return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; }; }); },{"49":49,"78":78}],189:[function(_dereq_,module,exports){ // 19.1.2.12 Object.isFrozen(O) var isObject = _dereq_(49); _dereq_(78)('isFrozen', function($isFrozen){ return function isFrozen(it){ return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; }; }); },{"49":49,"78":78}],190:[function(_dereq_,module,exports){ // 19.1.2.13 Object.isSealed(O) var isObject = _dereq_(49); _dereq_(78)('isSealed', function($isSealed){ return function isSealed(it){ return isObject(it) ? $isSealed ? $isSealed(it) : false : true; }; }); },{"49":49,"78":78}],191:[function(_dereq_,module,exports){ // 19.1.3.10 Object.is(value1, value2) var $export = _dereq_(32); $export($export.S, 'Object', {is: _dereq_(89)}); },{"32":32,"89":89}],192:[function(_dereq_,module,exports){ // 19.1.2.14 Object.keys(O) var toObject = _dereq_(109) , $keys = _dereq_(76); _dereq_(78)('keys', function(){ return function keys(it){ return $keys(toObject(it)); }; }); },{"109":109,"76":76,"78":78}],193:[function(_dereq_,module,exports){ // 19.1.2.15 Object.preventExtensions(O) var isObject = _dereq_(49) , meta = _dereq_(62).onFreeze; _dereq_(78)('preventExtensions', function($preventExtensions){ return function preventExtensions(it){ return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; }; }); },{"49":49,"62":62,"78":78}],194:[function(_dereq_,module,exports){ // 19.1.2.17 Object.seal(O) var isObject = _dereq_(49) , meta = _dereq_(62).onFreeze; _dereq_(78)('seal', function($seal){ return function seal(it){ return $seal && isObject(it) ? $seal(meta(it)) : it; }; }); },{"49":49,"62":62,"78":78}],195:[function(_dereq_,module,exports){ // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = _dereq_(32); $export($export.S, 'Object', {setPrototypeOf: _dereq_(90).set}); },{"32":32,"90":90}],196:[function(_dereq_,module,exports){ 'use strict'; // 19.1.3.6 Object.prototype.toString() var classof = _dereq_(17) , test = {}; test[_dereq_(117)('toStringTag')] = 'z'; if(test + '' != '[object z]'){ _dereq_(87)(Object.prototype, 'toString', function toString(){ return '[object ' + classof(this) + ']'; }, true); } },{"117":117,"17":17,"87":87}],197:[function(_dereq_,module,exports){ var $export = _dereq_(32) , $parseFloat = _dereq_(81); // 18.2.4 parseFloat(string) $export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat}); },{"32":32,"81":81}],198:[function(_dereq_,module,exports){ var $export = _dereq_(32) , $parseInt = _dereq_(82); // 18.2.5 parseInt(string, radix) $export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt}); },{"32":32,"82":82}],199:[function(_dereq_,module,exports){ 'use strict'; var LIBRARY = _dereq_(58) , global = _dereq_(38) , ctx = _dereq_(25) , classof = _dereq_(17) , $export = _dereq_(32) , isObject = _dereq_(49) , anObject = _dereq_(7) , aFunction = _dereq_(3) , anInstance = _dereq_(6) , forOf = _dereq_(37) , setProto = _dereq_(90).set , speciesConstructor = _dereq_(95) , task = _dereq_(104).set , microtask = _dereq_(64)() , PROMISE = 'Promise' , TypeError = global.TypeError , process = global.process , $Promise = global[PROMISE] , process = global.process , isNode = classof(process) == 'process' , empty = function(){ /* empty */ } , Internal, GenericPromiseCapability, Wrapper; var USE_NATIVE = !!function(){ try { // correct subclassing with @@species support var promise = $Promise.resolve(1) , FakePromise = (promise.constructor = {})[_dereq_(117)('species')] = function(exec){ exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch(e){ /* empty */ } }(); // helpers var sameConstructor = function(a, b){ // with library wrapper special case return a === b || a === $Promise && b === Wrapper; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var newPromiseCapability = function(C){ return sameConstructor($Promise, C) ? new PromiseCapability(C) : new GenericPromiseCapability(C); }; var PromiseCapability = GenericPromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(promise, isReject){ if(promise._n)return; promise._n = true; var chain = promise._c; microtask(function(){ var value = promise._v , ok = promise._s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , domain = reaction.domain , result, then; try { if(handler){ if(!ok){ if(promise._h == 2)onHandleUnhandled(promise); promise._h = 1; } if(handler === true)result = value; else { if(domain)domain.enter(); result = handler(value); if(domain)domain.exit(); } if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if(isReject && !promise._h)onUnhandled(promise); }); }; var onUnhandled = function(promise){ task.call(global, function(){ var value = promise._v , abrupt, handler, console; if(isUnhandled(promise)){ abrupt = perform(function(){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if(abrupt)throw abrupt.error; }); }; var isUnhandled = function(promise){ if(promise._h == 1)return false; var chain = promise._a || promise._c , i = 0 , reaction; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var onHandleUnhandled = function(promise){ task.call(global, function(){ var handler; if(isNode){ process.emit('rejectionHandled', promise); } else if(handler = global.onrejectionhandled){ handler({promise: promise, reason: promise._v}); } }); }; var $reject = function(value){ var promise = this; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if(!promise._a)promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function(value){ var promise = this , then; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap try { if(promise === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ microtask(function(){ var wrapper = {_w: promise, _d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch(e){ $reject.call({_w: promise, _d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) $Promise = function Promise(executor){ anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch(err){ $reject.call(this, err); } }; Internal = function Promise(executor){ this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = _dereq_(86)($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if(this._a)this._a.push(reaction); if(this._s)notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); PromiseCapability = function(){ var promise = new Internal; this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); _dereq_(92)($Promise, PROMISE); _dereq_(91)(PROMISE); Wrapper = _dereq_(23)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = newPromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; var capability = newPromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && _dereq_(54)(function(iter){ $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = this , capability = newPromiseCapability(C) , resolve = capability.resolve , reject = capability.reject; var abrupt = perform(function(){ var values = [] , index = 0 , remaining = 1; forOf(iterable, false, function(promise){ var $index = index++ , alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = this , capability = newPromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } }); },{"104":104,"117":117,"17":17,"23":23,"25":25,"3":3,"32":32,"37":37,"38":38,"49":49,"54":54,"58":58,"6":6,"64":64,"7":7,"86":86,"90":90,"91":91,"92":92,"95":95}],200:[function(_dereq_,module,exports){ // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) var $export = _dereq_(32) , aFunction = _dereq_(3) , anObject = _dereq_(7) , _apply = Function.apply; $export($export.S, 'Reflect', { apply: function apply(target, thisArgument, argumentsList){ return _apply.call(aFunction(target), thisArgument, anObject(argumentsList)); } }); },{"3":3,"32":32,"7":7}],201:[function(_dereq_,module,exports){ // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) var $export = _dereq_(32) , create = _dereq_(66) , aFunction = _dereq_(3) , anObject = _dereq_(7) , isObject = _dereq_(49) , bind = _dereq_(16); // MS Edge supports only 2 arguments // FF Nightly sets third argument as `new.target`, but does not create `this` from it $export($export.S + $export.F * _dereq_(34)(function(){ function F(){} return !(Reflect.construct(function(){}, [], F) instanceof F); }), 'Reflect', { construct: function construct(Target, args /*, newTarget*/){ aFunction(Target); anObject(args); var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); if(Target == newTarget){ // w/o altered newTarget, optimization for 0-4 arguments switch(args.length){ case 0: return new Target; case 1: return new Target(args[0]); case 2: return new Target(args[0], args[1]); case 3: return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); } // w/o altered newTarget, lot of arguments case var $args = [null]; $args.push.apply($args, args); return new (bind.apply(Target, $args)); } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype , instance = create(isObject(proto) ? proto : Object.prototype) , result = Function.apply.call(Target, instance, args); return isObject(result) ? result : instance; } }); },{"16":16,"3":3,"32":32,"34":34,"49":49,"66":66,"7":7}],202:[function(_dereq_,module,exports){ // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) var dP = _dereq_(67) , $export = _dereq_(32) , anObject = _dereq_(7) , toPrimitive = _dereq_(110); // MS Edge has broken Reflect.defineProperty - throwing instead of returning false $export($export.S + $export.F * _dereq_(34)(function(){ Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2}); }), 'Reflect', { defineProperty: function defineProperty(target, propertyKey, attributes){ anObject(target); propertyKey = toPrimitive(propertyKey, true); anObject(attributes); try { dP.f(target, propertyKey, attributes); return true; } catch(e){ return false; } } }); },{"110":110,"32":32,"34":34,"67":67,"7":7}],203:[function(_dereq_,module,exports){ // 26.1.4 Reflect.deleteProperty(target, propertyKey) var $export = _dereq_(32) , gOPD = _dereq_(70).f , anObject = _dereq_(7); $export($export.S, 'Reflect', { deleteProperty: function deleteProperty(target, propertyKey){ var desc = gOPD(anObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; } }); },{"32":32,"7":7,"70":70}],204:[function(_dereq_,module,exports){ 'use strict'; // 26.1.5 Reflect.enumerate(target) var $export = _dereq_(32) , anObject = _dereq_(7); var Enumerate = function(iterated){ this._t = anObject(iterated); // target this._i = 0; // next index var keys = this._k = [] // keys , key; for(key in iterated)keys.push(key); }; _dereq_(52)(Enumerate, 'Object', function(){ var that = this , keys = that._k , key; do { if(that._i >= keys.length)return {value: undefined, done: true}; } while(!((key = keys[that._i++]) in that._t)); return {value: key, done: false}; }); $export($export.S, 'Reflect', { enumerate: function enumerate(target){ return new Enumerate(target); } }); },{"32":32,"52":52,"7":7}],205:[function(_dereq_,module,exports){ // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) var gOPD = _dereq_(70) , $export = _dereq_(32) , anObject = _dereq_(7); $export($export.S, 'Reflect', { getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return gOPD.f(anObject(target), propertyKey); } }); },{"32":32,"7":7,"70":70}],206:[function(_dereq_,module,exports){ // 26.1.8 Reflect.getPrototypeOf(target) var $export = _dereq_(32) , getProto = _dereq_(74) , anObject = _dereq_(7); $export($export.S, 'Reflect', { getPrototypeOf: function getPrototypeOf(target){ return getProto(anObject(target)); } }); },{"32":32,"7":7,"74":74}],207:[function(_dereq_,module,exports){ // 26.1.6 Reflect.get(target, propertyKey [, receiver]) var gOPD = _dereq_(70) , getPrototypeOf = _dereq_(74) , has = _dereq_(39) , $export = _dereq_(32) , isObject = _dereq_(49) , anObject = _dereq_(7); function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc, proto; if(anObject(target) === receiver)return target[propertyKey]; if(desc = gOPD.f(target, propertyKey))return has(desc, 'value') ? desc.value : desc.get !== undefined ? desc.get.call(receiver) : undefined; if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver); } $export($export.S, 'Reflect', {get: get}); },{"32":32,"39":39,"49":49,"7":7,"70":70,"74":74}],208:[function(_dereq_,module,exports){ // 26.1.9 Reflect.has(target, propertyKey) var $export = _dereq_(32); $export($export.S, 'Reflect', { has: function has(target, propertyKey){ return propertyKey in target; } }); },{"32":32}],209:[function(_dereq_,module,exports){ // 26.1.10 Reflect.isExtensible(target) var $export = _dereq_(32) , anObject = _dereq_(7) , $isExtensible = Object.isExtensible; $export($export.S, 'Reflect', { isExtensible: function isExtensible(target){ anObject(target); return $isExtensible ? $isExtensible(target) : true; } }); },{"32":32,"7":7}],210:[function(_dereq_,module,exports){ // 26.1.11 Reflect.ownKeys(target) var $export = _dereq_(32); $export($export.S, 'Reflect', {ownKeys: _dereq_(80)}); },{"32":32,"80":80}],211:[function(_dereq_,module,exports){ // 26.1.12 Reflect.preventExtensions(target) var $export = _dereq_(32) , anObject = _dereq_(7) , $preventExtensions = Object.preventExtensions; $export($export.S, 'Reflect', { preventExtensions: function preventExtensions(target){ anObject(target); try { if($preventExtensions)$preventExtensions(target); return true; } catch(e){ return false; } } }); },{"32":32,"7":7}],212:[function(_dereq_,module,exports){ // 26.1.14 Reflect.setPrototypeOf(target, proto) var $export = _dereq_(32) , setProto = _dereq_(90); if(setProto)$export($export.S, 'Reflect', { setPrototypeOf: function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } } }); },{"32":32,"90":90}],213:[function(_dereq_,module,exports){ // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) var dP = _dereq_(67) , gOPD = _dereq_(70) , getPrototypeOf = _dereq_(74) , has = _dereq_(39) , $export = _dereq_(32) , createDesc = _dereq_(85) , anObject = _dereq_(7) , isObject = _dereq_(49); function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = gOPD.f(anObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getPrototypeOf(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = createDesc(0); } if(has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0); existingDescriptor.value = V; dP.f(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } $export($export.S, 'Reflect', {set: set}); },{"32":32,"39":39,"49":49,"67":67,"7":7,"70":70,"74":74,"85":85}],214:[function(_dereq_,module,exports){ var global = _dereq_(38) , inheritIfRequired = _dereq_(43) , dP = _dereq_(67).f , gOPN = _dereq_(72).f , isRegExp = _dereq_(50) , $flags = _dereq_(36) , $RegExp = global.RegExp , Base = $RegExp , proto = $RegExp.prototype , re1 = /a/g , re2 = /a/g // "new" creates a new object, old webkit buggy here , CORRECT_NEW = new $RegExp(re1) !== re1; if(_dereq_(28) && (!CORRECT_NEW || _dereq_(34)(function(){ re2[_dereq_(117)('match')] = false; // RegExp constructor can alter flags and IsRegExp works correct with @@match return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; }))){ $RegExp = function RegExp(p, f){ var tiRE = this instanceof $RegExp , piRE = isRegExp(p) , fiU = f === undefined; return !tiRE && piRE && p.constructor === $RegExp && fiU ? p : inheritIfRequired(CORRECT_NEW ? new Base(piRE && !fiU ? p.source : p, f) : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) , tiRE ? this : proto, $RegExp); }; var proxy = function(key){ key in $RegExp || dP($RegExp, key, { configurable: true, get: function(){ return Base[key]; }, set: function(it){ Base[key] = it; } }); }; for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]); proto.constructor = $RegExp; $RegExp.prototype = proto; _dereq_(87)(global, 'RegExp', $RegExp); } _dereq_(91)('RegExp'); },{"117":117,"28":28,"34":34,"36":36,"38":38,"43":43,"50":50,"67":67,"72":72,"87":87,"91":91}],215:[function(_dereq_,module,exports){ // 21.2.5.3 get RegExp.prototype.flags() if(_dereq_(28) && /./g.flags != 'g')_dereq_(67).f(RegExp.prototype, 'flags', { configurable: true, get: _dereq_(36) }); },{"28":28,"36":36,"67":67}],216:[function(_dereq_,module,exports){ // @@match logic _dereq_(35)('match', 1, function(defined, MATCH, $match){ // 21.1.3.11 String.prototype.match(regexp) return [function match(regexp){ 'use strict'; var O = defined(this) , fn = regexp == undefined ? undefined : regexp[MATCH]; return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); }, $match]; }); },{"35":35}],217:[function(_dereq_,module,exports){ // @@replace logic _dereq_(35)('replace', 2, function(defined, REPLACE, $replace){ // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) return [function replace(searchValue, replaceValue){ 'use strict'; var O = defined(this) , fn = searchValue == undefined ? undefined : searchValue[REPLACE]; return fn !== undefined ? fn.call(searchValue, O, replaceValue) : $replace.call(String(O), searchValue, replaceValue); }, $replace]; }); },{"35":35}],218:[function(_dereq_,module,exports){ // @@search logic _dereq_(35)('search', 1, function(defined, SEARCH, $search){ // 21.1.3.15 String.prototype.search(regexp) return [function search(regexp){ 'use strict'; var O = defined(this) , fn = regexp == undefined ? undefined : regexp[SEARCH]; return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); }, $search]; }); },{"35":35}],219:[function(_dereq_,module,exports){ // @@split logic _dereq_(35)('split', 2, function(defined, SPLIT, $split){ 'use strict'; var isRegExp = _dereq_(50) , _split = $split , $push = [].push , $SPLIT = 'split' , LENGTH = 'length' , LAST_INDEX = 'lastIndex'; if( 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || '.'[$SPLIT](/()()/)[LENGTH] > 1 || ''[$SPLIT](/.?/)[LENGTH] ){ var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group // based on es5-shim implementation, need to rework it $split = function(separator, limit){ var string = String(this); if(separator === undefined && limit === 0)return []; // If `separator` is not a regex, use native split if(!isRegExp(separator))return _split.call(string, separator, limit); var output = []; var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); var lastLastIndex = 0; var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; // Make `global` and avoid `lastIndex` issues by working with a copy var separatorCopy = new RegExp(separator.source, flags + 'g'); var separator2, match, lastIndex, lastLength, i; // Doesn't need flags gy, but they don't hurt if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); while(match = separatorCopy.exec(string)){ // `separatorCopy.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0][LENGTH]; if(lastIndex > lastLastIndex){ output.push(string.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){ for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined; }); if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1)); lastLength = match[0][LENGTH]; lastLastIndex = lastIndex; if(output[LENGTH] >= splitLimit)break; } if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop } if(lastLastIndex === string[LENGTH]){ if(lastLength || !separatorCopy.test(''))output.push(''); } else output.push(string.slice(lastLastIndex)); return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; }; // Chakra, V8 } else if('0'[$SPLIT](undefined, 0)[LENGTH]){ $split = function(separator, limit){ return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); }; } // 21.1.3.17 String.prototype.split(separator, limit) return [function split(separator, limit){ var O = defined(this) , fn = separator == undefined ? undefined : separator[SPLIT]; return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); }, $split]; }); },{"35":35,"50":50}],220:[function(_dereq_,module,exports){ 'use strict'; _dereq_(215); var anObject = _dereq_(7) , $flags = _dereq_(36) , DESCRIPTORS = _dereq_(28) , TO_STRING = 'toString' , $toString = /./[TO_STRING]; var define = function(fn){ _dereq_(87)(RegExp.prototype, TO_STRING, fn, true); }; // 21.2.5.14 RegExp.prototype.toString() if(_dereq_(34)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){ define(function toString(){ var R = anObject(this); return '/'.concat(R.source, '/', 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); }); // FF44- RegExp#toString has a wrong name } else if($toString.name != TO_STRING){ define(function toString(){ return $toString.call(this); }); } },{"215":215,"28":28,"34":34,"36":36,"7":7,"87":87}],221:[function(_dereq_,module,exports){ 'use strict'; var strong = _dereq_(19); // 23.2 Set Objects module.exports = _dereq_(22)('Set', function(get){ return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); },{"19":19,"22":22}],222:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.2 String.prototype.anchor(name) _dereq_(99)('anchor', function(createHTML){ return function anchor(name){ return createHTML(this, 'a', 'name', name); } }); },{"99":99}],223:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.3 String.prototype.big() _dereq_(99)('big', function(createHTML){ return function big(){ return createHTML(this, 'big', '', ''); } }); },{"99":99}],224:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.4 String.prototype.blink() _dereq_(99)('blink', function(createHTML){ return function blink(){ return createHTML(this, 'blink', '', ''); } }); },{"99":99}],225:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.5 String.prototype.bold() _dereq_(99)('bold', function(createHTML){ return function bold(){ return createHTML(this, 'b', '', ''); } }); },{"99":99}],226:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $at = _dereq_(97)(false); $export($export.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: function codePointAt(pos){ return $at(this, pos); } }); },{"32":32,"97":97}],227:[function(_dereq_,module,exports){ // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) 'use strict'; var $export = _dereq_(32) , toLength = _dereq_(108) , context = _dereq_(98) , ENDS_WITH = 'endsWith' , $endsWith = ''[ENDS_WITH]; $export($export.P + $export.F * _dereq_(33)(ENDS_WITH), 'String', { endsWith: function endsWith(searchString /*, endPosition = @length */){ var that = context(this, searchString, ENDS_WITH) , endPosition = arguments.length > 1 ? arguments[1] : undefined , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len) , search = String(searchString); return $endsWith ? $endsWith.call(that, search, end) : that.slice(end - search.length, end) === search; } }); },{"108":108,"32":32,"33":33,"98":98}],228:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.6 String.prototype.fixed() _dereq_(99)('fixed', function(createHTML){ return function fixed(){ return createHTML(this, 'tt', '', ''); } }); },{"99":99}],229:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.7 String.prototype.fontcolor(color) _dereq_(99)('fontcolor', function(createHTML){ return function fontcolor(color){ return createHTML(this, 'font', 'color', color); } }); },{"99":99}],230:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.8 String.prototype.fontsize(size) _dereq_(99)('fontsize', function(createHTML){ return function fontsize(size){ return createHTML(this, 'font', 'size', size); } }); },{"99":99}],231:[function(_dereq_,module,exports){ var $export = _dereq_(32) , toIndex = _dereq_(105) , fromCharCode = String.fromCharCode , $fromCodePoint = String.fromCodePoint; // length should be 1, old FF problem $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , aLen = arguments.length , i = 0 , code; while(aLen > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); },{"105":105,"32":32}],232:[function(_dereq_,module,exports){ // 21.1.3.7 String.prototype.includes(searchString, position = 0) 'use strict'; var $export = _dereq_(32) , context = _dereq_(98) , INCLUDES = 'includes'; $export($export.P + $export.F * _dereq_(33)(INCLUDES), 'String', { includes: function includes(searchString /*, position = 0 */){ return !!~context(this, searchString, INCLUDES) .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); } }); },{"32":32,"33":33,"98":98}],233:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.9 String.prototype.italics() _dereq_(99)('italics', function(createHTML){ return function italics(){ return createHTML(this, 'i', '', ''); } }); },{"99":99}],234:[function(_dereq_,module,exports){ 'use strict'; var $at = _dereq_(97)(true); // 21.1.3.27 String.prototype[@@iterator]() _dereq_(53)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); },{"53":53,"97":97}],235:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.10 String.prototype.link(url) _dereq_(99)('link', function(createHTML){ return function link(url){ return createHTML(this, 'a', 'href', url); } }); },{"99":99}],236:[function(_dereq_,module,exports){ var $export = _dereq_(32) , toIObject = _dereq_(107) , toLength = _dereq_(108); $export($export.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = toIObject(callSite.raw) , len = toLength(tpl.length) , aLen = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < aLen)res.push(String(arguments[i])); } return res.join(''); } }); },{"107":107,"108":108,"32":32}],237:[function(_dereq_,module,exports){ var $export = _dereq_(32); $export($export.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: _dereq_(101) }); },{"101":101,"32":32}],238:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.11 String.prototype.small() _dereq_(99)('small', function(createHTML){ return function small(){ return createHTML(this, 'small', '', ''); } }); },{"99":99}],239:[function(_dereq_,module,exports){ // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) 'use strict'; var $export = _dereq_(32) , toLength = _dereq_(108) , context = _dereq_(98) , STARTS_WITH = 'startsWith' , $startsWith = ''[STARTS_WITH]; $export($export.P + $export.F * _dereq_(33)(STARTS_WITH), 'String', { startsWith: function startsWith(searchString /*, position = 0 */){ var that = context(this, searchString, STARTS_WITH) , index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)) , search = String(searchString); return $startsWith ? $startsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); },{"108":108,"32":32,"33":33,"98":98}],240:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.12 String.prototype.strike() _dereq_(99)('strike', function(createHTML){ return function strike(){ return createHTML(this, 'strike', '', ''); } }); },{"99":99}],241:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.13 String.prototype.sub() _dereq_(99)('sub', function(createHTML){ return function sub(){ return createHTML(this, 'sub', '', ''); } }); },{"99":99}],242:[function(_dereq_,module,exports){ 'use strict'; // B.2.3.14 String.prototype.sup() _dereq_(99)('sup', function(createHTML){ return function sup(){ return createHTML(this, 'sup', '', ''); } }); },{"99":99}],243:[function(_dereq_,module,exports){ 'use strict'; // 21.1.3.25 String.prototype.trim() _dereq_(102)('trim', function($trim){ return function trim(){ return $trim(this, 3); }; }); },{"102":102}],244:[function(_dereq_,module,exports){ 'use strict'; // ECMAScript 6 symbols shim var global = _dereq_(38) , has = _dereq_(39) , DESCRIPTORS = _dereq_(28) , $export = _dereq_(32) , redefine = _dereq_(87) , META = _dereq_(62).KEY , $fails = _dereq_(34) , shared = _dereq_(94) , setToStringTag = _dereq_(92) , uid = _dereq_(114) , wks = _dereq_(117) , wksExt = _dereq_(116) , wksDefine = _dereq_(115) , keyOf = _dereq_(57) , enumKeys = _dereq_(31) , isArray = _dereq_(47) , anObject = _dereq_(7) , toIObject = _dereq_(107) , toPrimitive = _dereq_(110) , createDesc = _dereq_(85) , _create = _dereq_(66) , gOPNExt = _dereq_(71) , $GOPD = _dereq_(70) , $DP = _dereq_(67) , $keys = _dereq_(76) , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; _dereq_(72).f = gOPNExt.f = $getOwnPropertyNames; _dereq_(77).f = $propertyIsEnumerable; _dereq_(73).f = $getOwnPropertySymbols; if(DESCRIPTORS && !_dereq_(58)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || _dereq_(40)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); },{"107":107,"110":110,"114":114,"115":115,"116":116,"117":117,"28":28,"31":31,"32":32,"34":34,"38":38,"39":39,"40":40,"47":47,"57":57,"58":58,"62":62,"66":66,"67":67,"7":7,"70":70,"71":71,"72":72,"73":73,"76":76,"77":77,"85":85,"87":87,"92":92,"94":94}],245:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , $typed = _dereq_(113) , buffer = _dereq_(112) , anObject = _dereq_(7) , toIndex = _dereq_(105) , toLength = _dereq_(108) , isObject = _dereq_(49) , TYPED_ARRAY = _dereq_(117)('typed_array') , ArrayBuffer = _dereq_(38).ArrayBuffer , speciesConstructor = _dereq_(95) , $ArrayBuffer = buffer.ArrayBuffer , $DataView = buffer.DataView , $isView = $typed.ABV && ArrayBuffer.isView , $slice = $ArrayBuffer.prototype.slice , VIEW = $typed.VIEW , ARRAY_BUFFER = 'ArrayBuffer'; $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer}); $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { // 24.1.3.1 ArrayBuffer.isView(arg) isView: function isView(it){ return $isView && $isView(it) || isObject(it) && VIEW in it; } }); $export($export.P + $export.U + $export.F * _dereq_(34)(function(){ return !new $ArrayBuffer(2).slice(1, undefined).byteLength; }), ARRAY_BUFFER, { // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) slice: function slice(start, end){ if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix var len = anObject(this).byteLength , first = toIndex(start, len) , final = toIndex(end === undefined ? len : end, len) , result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first)) , viewS = new $DataView(this) , viewT = new $DataView(result) , index = 0; while(first < final){ viewT.setUint8(index++, viewS.getUint8(first++)); } return result; } }); _dereq_(91)(ARRAY_BUFFER); },{"105":105,"108":108,"112":112,"113":113,"117":117,"32":32,"34":34,"38":38,"49":49,"7":7,"91":91,"95":95}],246:[function(_dereq_,module,exports){ var $export = _dereq_(32); $export($export.G + $export.W + $export.F * !_dereq_(113).ABV, { DataView: _dereq_(112).DataView }); },{"112":112,"113":113,"32":32}],247:[function(_dereq_,module,exports){ _dereq_(111)('Float32', 4, function(init){ return function Float32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"111":111}],248:[function(_dereq_,module,exports){ _dereq_(111)('Float64', 8, function(init){ return function Float64Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"111":111}],249:[function(_dereq_,module,exports){ _dereq_(111)('Int16', 2, function(init){ return function Int16Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"111":111}],250:[function(_dereq_,module,exports){ _dereq_(111)('Int32', 4, function(init){ return function Int32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"111":111}],251:[function(_dereq_,module,exports){ _dereq_(111)('Int8', 1, function(init){ return function Int8Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"111":111}],252:[function(_dereq_,module,exports){ _dereq_(111)('Uint16', 2, function(init){ return function Uint16Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"111":111}],253:[function(_dereq_,module,exports){ _dereq_(111)('Uint32', 4, function(init){ return function Uint32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"111":111}],254:[function(_dereq_,module,exports){ _dereq_(111)('Uint8', 1, function(init){ return function Uint8Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); },{"111":111}],255:[function(_dereq_,module,exports){ _dereq_(111)('Uint8', 1, function(init){ return function Uint8ClampedArray(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }, true); },{"111":111}],256:[function(_dereq_,module,exports){ 'use strict'; var each = _dereq_(12)(0) , redefine = _dereq_(87) , meta = _dereq_(62) , assign = _dereq_(65) , weak = _dereq_(21) , isObject = _dereq_(49) , has = _dereq_(39) , getWeak = meta.getWeak , isExtensible = Object.isExtensible , uncaughtFrozenStore = weak.ufstore , tmp = {} , InternalMap; var wrapper = function(get){ return function WeakMap(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }; var methods = { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).get(key); return data ? data[this._i] : undefined; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }; // 23.3 WeakMap Objects var $WeakMap = module.exports = _dereq_(22)('WeakMap', wrapper, methods, weak, true, true); // IE11 WeakMap frozen keys fix if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ InternalMap = weak.getConstructor(wrapper); assign(InternalMap.prototype, methods); meta.NEED = true; each(['delete', 'has', 'get', 'set'], function(key){ var proto = $WeakMap.prototype , method = proto[key]; redefine(proto, key, function(a, b){ // store frozen objects on internal weakmap shim if(isObject(a) && !isExtensible(a)){ if(!this._f)this._f = new InternalMap; var result = this._f[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }); }); } },{"12":12,"21":21,"22":22,"39":39,"49":49,"62":62,"65":65,"87":87}],257:[function(_dereq_,module,exports){ 'use strict'; var weak = _dereq_(21); // 23.4 WeakSet Objects _dereq_(22)('WeakSet', function(get){ return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); },{"21":21,"22":22}],258:[function(_dereq_,module,exports){ 'use strict'; // https://github.com/tc39/Array.prototype.includes var $export = _dereq_(32) , $includes = _dereq_(11)(true); $export($export.P, 'Array', { includes: function includes(el /*, fromIndex = 0 */){ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); _dereq_(5)('includes'); },{"11":11,"32":32,"5":5}],259:[function(_dereq_,module,exports){ // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask var $export = _dereq_(32) , microtask = _dereq_(64)() , process = _dereq_(38).process , isNode = _dereq_(18)(process) == 'process'; $export($export.G, { asap: function asap(fn){ var domain = isNode && process.domain; microtask(domain ? domain.bind(fn) : fn); } }); },{"18":18,"32":32,"38":38,"64":64}],260:[function(_dereq_,module,exports){ // https://github.com/ljharb/proposal-is-error var $export = _dereq_(32) , cof = _dereq_(18); $export($export.S, 'Error', { isError: function isError(it){ return cof(it) === 'Error'; } }); },{"18":18,"32":32}],261:[function(_dereq_,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = _dereq_(32); $export($export.P + $export.R, 'Map', {toJSON: _dereq_(20)('Map')}); },{"20":20,"32":32}],262:[function(_dereq_,module,exports){ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = _dereq_(32); $export($export.S, 'Math', { iaddh: function iaddh(x0, x1, y0, y1){ var $x0 = x0 >>> 0 , $x1 = x1 >>> 0 , $y0 = y0 >>> 0; return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; } }); },{"32":32}],263:[function(_dereq_,module,exports){ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = _dereq_(32); $export($export.S, 'Math', { imulh: function imulh(u, v){ var UINT16 = 0xffff , $u = +u , $v = +v , u0 = $u & UINT16 , v0 = $v & UINT16 , u1 = $u >> 16 , v1 = $v >> 16 , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); } }); },{"32":32}],264:[function(_dereq_,module,exports){ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = _dereq_(32); $export($export.S, 'Math', { isubh: function isubh(x0, x1, y0, y1){ var $x0 = x0 >>> 0 , $x1 = x1 >>> 0 , $y0 = y0 >>> 0; return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; } }); },{"32":32}],265:[function(_dereq_,module,exports){ // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = _dereq_(32); $export($export.S, 'Math', { umulh: function umulh(u, v){ var UINT16 = 0xffff , $u = +u , $v = +v , u0 = $u & UINT16 , v0 = $v & UINT16 , u1 = $u >>> 16 , v1 = $v >>> 16 , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); } }); },{"32":32}],266:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , toObject = _dereq_(109) , aFunction = _dereq_(3) , $defineProperty = _dereq_(67); // B.2.2.2 Object.prototype.__defineGetter__(P, getter) _dereq_(28) && $export($export.P + _dereq_(69), 'Object', { __defineGetter__: function __defineGetter__(P, getter){ $defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true}); } }); },{"109":109,"28":28,"3":3,"32":32,"67":67,"69":69}],267:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , toObject = _dereq_(109) , aFunction = _dereq_(3) , $defineProperty = _dereq_(67); // B.2.2.3 Object.prototype.__defineSetter__(P, setter) _dereq_(28) && $export($export.P + _dereq_(69), 'Object', { __defineSetter__: function __defineSetter__(P, setter){ $defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true}); } }); },{"109":109,"28":28,"3":3,"32":32,"67":67,"69":69}],268:[function(_dereq_,module,exports){ // https://github.com/tc39/proposal-object-values-entries var $export = _dereq_(32) , $entries = _dereq_(79)(true); $export($export.S, 'Object', { entries: function entries(it){ return $entries(it); } }); },{"32":32,"79":79}],269:[function(_dereq_,module,exports){ // https://github.com/tc39/proposal-object-getownpropertydescriptors var $export = _dereq_(32) , ownKeys = _dereq_(80) , toIObject = _dereq_(107) , gOPD = _dereq_(70) , createProperty = _dereq_(24); $export($export.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = toIObject(object) , getDesc = gOPD.f , keys = ownKeys(O) , result = {} , i = 0 , key, D; while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key)); return result; } }); },{"107":107,"24":24,"32":32,"70":70,"80":80}],270:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , toObject = _dereq_(109) , toPrimitive = _dereq_(110) , getPrototypeOf = _dereq_(74) , getOwnPropertyDescriptor = _dereq_(70).f; // B.2.2.4 Object.prototype.__lookupGetter__(P) _dereq_(28) && $export($export.P + _dereq_(69), 'Object', { __lookupGetter__: function __lookupGetter__(P){ var O = toObject(this) , K = toPrimitive(P, true) , D; do { if(D = getOwnPropertyDescriptor(O, K))return D.get; } while(O = getPrototypeOf(O)); } }); },{"109":109,"110":110,"28":28,"32":32,"69":69,"70":70,"74":74}],271:[function(_dereq_,module,exports){ 'use strict'; var $export = _dereq_(32) , toObject = _dereq_(109) , toPrimitive = _dereq_(110) , getPrototypeOf = _dereq_(74) , getOwnPropertyDescriptor = _dereq_(70).f; // B.2.2.5 Object.prototype.__lookupSetter__(P) _dereq_(28) && $export($export.P + _dereq_(69), 'Object', { __lookupSetter__: function __lookupSetter__(P){ var O = toObject(this) , K = toPrimitive(P, true) , D; do { if(D = getOwnPropertyDescriptor(O, K))return D.set; } while(O = getPrototypeOf(O)); } }); },{"109":109,"110":110,"28":28,"32":32,"69":69,"70":70,"74":74}],272:[function(_dereq_,module,exports){ // https://github.com/tc39/proposal-object-values-entries var $export = _dereq_(32) , $values = _dereq_(79)(false); $export($export.S, 'Object', { values: function values(it){ return $values(it); } }); },{"32":32,"79":79}],273:[function(_dereq_,module,exports){ 'use strict'; // https://github.com/zenparsing/es-observable var $export = _dereq_(32) , global = _dereq_(38) , core = _dereq_(23) , microtask = _dereq_(64)() , OBSERVABLE = _dereq_(117)('observable') , aFunction = _dereq_(3) , anObject = _dereq_(7) , anInstance = _dereq_(6) , redefineAll = _dereq_(86) , hide = _dereq_(40) , forOf = _dereq_(37) , RETURN = forOf.RETURN; var getMethod = function(fn){ return fn == null ? undefined : aFunction(fn); }; var cleanupSubscription = function(subscription){ var cleanup = subscription._c; if(cleanup){ subscription._c = undefined; cleanup(); } }; var subscriptionClosed = function(subscription){ return subscription._o === undefined; }; var closeSubscription = function(subscription){ if(!subscriptionClosed(subscription)){ subscription._o = undefined; cleanupSubscription(subscription); } }; var Subscription = function(observer, subscriber){ anObject(observer); this._c = undefined; this._o = observer; observer = new SubscriptionObserver(this); try { var cleanup = subscriber(observer) , subscription = cleanup; if(cleanup != null){ if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); }; else aFunction(cleanup); this._c = cleanup; } } catch(e){ observer.error(e); return; } if(subscriptionClosed(this))cleanupSubscription(this); }; Subscription.prototype = redefineAll({}, { unsubscribe: function unsubscribe(){ closeSubscription(this); } }); var SubscriptionObserver = function(subscription){ this._s = subscription; }; SubscriptionObserver.prototype = redefineAll({}, { next: function next(value){ var subscription = this._s; if(!subscriptionClosed(subscription)){ var observer = subscription._o; try { var m = getMethod(observer.next); if(m)return m.call(observer, value); } catch(e){ try { closeSubscription(subscription); } finally { throw e; } } } }, error: function error(value){ var subscription = this._s; if(subscriptionClosed(subscription))throw value; var observer = subscription._o; subscription._o = undefined; try { var m = getMethod(observer.error); if(!m)throw value; value = m.call(observer, value); } catch(e){ try { cleanupSubscription(subscription); } finally { throw e; } } cleanupSubscription(subscription); return value; }, complete: function complete(value){ var subscription = this._s; if(!subscriptionClosed(subscription)){ var observer = subscription._o; subscription._o = undefined; try { var m = getMethod(observer.complete); value = m ? m.call(observer, value) : undefined; } catch(e){ try { cleanupSubscription(subscription); } finally { throw e; } } cleanupSubscription(subscription); return value; } } }); var $Observable = function Observable(subscriber){ anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); }; redefineAll($Observable.prototype, { subscribe: function subscribe(observer){ return new Subscription(observer, this._f); }, forEach: function forEach(fn){ var that = this; return new (core.Promise || global.Promise)(function(resolve, reject){ aFunction(fn); var subscription = that.subscribe({ next : function(value){ try { return fn(value); } catch(e){ reject(e); subscription.unsubscribe(); } }, error: reject, complete: resolve }); }); } }); redefineAll($Observable, { from: function from(x){ var C = typeof this === 'function' ? this : $Observable; var method = getMethod(anObject(x)[OBSERVABLE]); if(method){ var observable = anObject(method.call(x)); return observable.constructor === C ? observable : new C(function(observer){ return observable.subscribe(observer); }); } return new C(function(observer){ var done = false; microtask(function(){ if(!done){ try { if(forOf(x, false, function(it){ observer.next(it); if(done)return RETURN; }) === RETURN)return; } catch(e){ if(done)throw e; observer.error(e); return; } observer.complete(); } }); return function(){ done = true; }; }); }, of: function of(){ for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++]; return new (typeof this === 'function' ? this : $Observable)(function(observer){ var done = false; microtask(function(){ if(!done){ for(var i = 0; i < items.length; ++i){ observer.next(items[i]); if(done)return; } observer.complete(); } }); return function(){ done = true; }; }); } }); hide($Observable.prototype, OBSERVABLE, function(){ return this; }); $export($export.G, {Observable: $Observable}); _dereq_(91)('Observable'); },{"117":117,"23":23,"3":3,"32":32,"37":37,"38":38,"40":40,"6":6,"64":64,"7":7,"86":86,"91":91}],274:[function(_dereq_,module,exports){ var metadata = _dereq_(63) , anObject = _dereq_(7) , toMetaKey = metadata.key , ordinaryDefineOwnMetadata = metadata.set; metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){ ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); }}); },{"63":63,"7":7}],275:[function(_dereq_,module,exports){ var metadata = _dereq_(63) , anObject = _dereq_(7) , toMetaKey = metadata.key , getOrCreateMetadataMap = metadata.map , store = metadata.store; metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){ var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]) , metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false; if(metadataMap.size)return true; var targetMetadata = store.get(target); targetMetadata['delete'](targetKey); return !!targetMetadata.size || store['delete'](target); }}); },{"63":63,"7":7}],276:[function(_dereq_,module,exports){ var Set = _dereq_(221) , from = _dereq_(10) , metadata = _dereq_(63) , anObject = _dereq_(7) , getPrototypeOf = _dereq_(74) , ordinaryOwnMetadataKeys = metadata.keys , toMetaKey = metadata.key; var ordinaryMetadataKeys = function(O, P){ var oKeys = ordinaryOwnMetadataKeys(O, P) , parent = getPrototypeOf(O); if(parent === null)return oKeys; var pKeys = ordinaryMetadataKeys(parent, P); return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; }; metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){ return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); }}); },{"10":10,"221":221,"63":63,"7":7,"74":74}],277:[function(_dereq_,module,exports){ var metadata = _dereq_(63) , anObject = _dereq_(7) , getPrototypeOf = _dereq_(74) , ordinaryHasOwnMetadata = metadata.has , ordinaryGetOwnMetadata = metadata.get , toMetaKey = metadata.key; var ordinaryGetMetadata = function(MetadataKey, O, P){ var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P); var parent = getPrototypeOf(O); return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; }; metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){ return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); },{"63":63,"7":7,"74":74}],278:[function(_dereq_,module,exports){ var metadata = _dereq_(63) , anObject = _dereq_(7) , ordinaryOwnMetadataKeys = metadata.keys , toMetaKey = metadata.key; metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){ return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); }}); },{"63":63,"7":7}],279:[function(_dereq_,module,exports){ var metadata = _dereq_(63) , anObject = _dereq_(7) , ordinaryGetOwnMetadata = metadata.get , toMetaKey = metadata.key; metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){ return ordinaryGetOwnMetadata(metadataKey, anObject(target) , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); },{"63":63,"7":7}],280:[function(_dereq_,module,exports){ var metadata = _dereq_(63) , anObject = _dereq_(7) , getPrototypeOf = _dereq_(74) , ordinaryHasOwnMetadata = metadata.has , toMetaKey = metadata.key; var ordinaryHasMetadata = function(MetadataKey, O, P){ var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); if(hasOwn)return true; var parent = getPrototypeOf(O); return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; }; metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){ return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); },{"63":63,"7":7,"74":74}],281:[function(_dereq_,module,exports){ var metadata = _dereq_(63) , anObject = _dereq_(7) , ordinaryHasOwnMetadata = metadata.has , toMetaKey = metadata.key; metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){ return ordinaryHasOwnMetadata(metadataKey, anObject(target) , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); },{"63":63,"7":7}],282:[function(_dereq_,module,exports){ var metadata = _dereq_(63) , anObject = _dereq_(7) , aFunction = _dereq_(3) , toMetaKey = metadata.key , ordinaryDefineOwnMetadata = metadata.set; metadata.exp({metadata: function metadata(metadataKey, metadataValue){ return function decorator(target, targetKey){ ordinaryDefineOwnMetadata( metadataKey, metadataValue, (targetKey !== undefined ? anObject : aFunction)(target), toMetaKey(targetKey) ); }; }}); },{"3":3,"63":63,"7":7}],283:[function(_dereq_,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = _dereq_(32); $export($export.P + $export.R, 'Set', {toJSON: _dereq_(20)('Set')}); },{"20":20,"32":32}],284:[function(_dereq_,module,exports){ 'use strict'; // https://github.com/mathiasbynens/String.prototype.at var $export = _dereq_(32) , $at = _dereq_(97)(true); $export($export.P, 'String', { at: function at(pos){ return $at(this, pos); } }); },{"32":32,"97":97}],285:[function(_dereq_,module,exports){ 'use strict'; // https://tc39.github.io/String.prototype.matchAll/ var $export = _dereq_(32) , defined = _dereq_(27) , toLength = _dereq_(108) , isRegExp = _dereq_(50) , getFlags = _dereq_(36) , RegExpProto = RegExp.prototype; var $RegExpStringIterator = function(regexp, string){ this._r = regexp; this._s = string; }; _dereq_(52)($RegExpStringIterator, 'RegExp String', function next(){ var match = this._r.exec(this._s); return {value: match, done: match === null}; }); $export($export.P, 'String', { matchAll: function matchAll(regexp){ defined(this); if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!'); var S = String(this) , flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp) , rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); rx.lastIndex = toLength(regexp.lastIndex); return new $RegExpStringIterator(rx, S); } }); },{"108":108,"27":27,"32":32,"36":36,"50":50,"52":52}],286:[function(_dereq_,module,exports){ 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = _dereq_(32) , $pad = _dereq_(100); $export($export.P, 'String', { padEnd: function padEnd(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); } }); },{"100":100,"32":32}],287:[function(_dereq_,module,exports){ 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = _dereq_(32) , $pad = _dereq_(100); $export($export.P, 'String', { padStart: function padStart(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); } }); },{"100":100,"32":32}],288:[function(_dereq_,module,exports){ 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim _dereq_(102)('trimLeft', function($trim){ return function trimLeft(){ return $trim(this, 1); }; }, 'trimStart'); },{"102":102}],289:[function(_dereq_,module,exports){ 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim _dereq_(102)('trimRight', function($trim){ return function trimRight(){ return $trim(this, 2); }; }, 'trimEnd'); },{"102":102}],290:[function(_dereq_,module,exports){ _dereq_(115)('asyncIterator'); },{"115":115}],291:[function(_dereq_,module,exports){ _dereq_(115)('observable'); },{"115":115}],292:[function(_dereq_,module,exports){ // https://github.com/ljharb/proposal-global var $export = _dereq_(32); $export($export.S, 'System', {global: _dereq_(38)}); },{"32":32,"38":38}],293:[function(_dereq_,module,exports){ var $iterators = _dereq_(131) , redefine = _dereq_(87) , global = _dereq_(38) , hide = _dereq_(40) , Iterators = _dereq_(56) , wks = _dereq_(117) , ITERATOR = wks('iterator') , TO_STRING_TAG = wks('toStringTag') , ArrayValues = Iterators.Array; for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype , key; if(proto){ if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues); if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true); } } },{"117":117,"131":131,"38":38,"40":40,"56":56,"87":87}],294:[function(_dereq_,module,exports){ var $export = _dereq_(32) , $task = _dereq_(104); $export($export.G + $export.B, { setImmediate: $task.set, clearImmediate: $task.clear }); },{"104":104,"32":32}],295:[function(_dereq_,module,exports){ // ie9- setTimeout & setInterval additional parameters fix var global = _dereq_(38) , $export = _dereq_(32) , invoke = _dereq_(44) , partial = _dereq_(83) , navigator = global.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check var wrap = function(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), typeof fn == 'function' ? fn : Function(fn) ), time); } : set; }; $export($export.G + $export.B + $export.F * MSIE, { setTimeout: wrap(global.setTimeout), setInterval: wrap(global.setInterval) }); },{"32":32,"38":38,"44":44,"83":83}],296:[function(_dereq_,module,exports){ _dereq_(244); _dereq_(181); _dereq_(183); _dereq_(182); _dereq_(185); _dereq_(187); _dereq_(192); _dereq_(186); _dereq_(184); _dereq_(194); _dereq_(193); _dereq_(189); _dereq_(190); _dereq_(188); _dereq_(180); _dereq_(191); _dereq_(195); _dereq_(196); _dereq_(147); _dereq_(149); _dereq_(148); _dereq_(198); _dereq_(197); _dereq_(168); _dereq_(178); _dereq_(179); _dereq_(169); _dereq_(170); _dereq_(171); _dereq_(172); _dereq_(173); _dereq_(174); _dereq_(175); _dereq_(176); _dereq_(177); _dereq_(151); _dereq_(152); _dereq_(153); _dereq_(154); _dereq_(155); _dereq_(156); _dereq_(157); _dereq_(158); _dereq_(159); _dereq_(160); _dereq_(161); _dereq_(162); _dereq_(163); _dereq_(164); _dereq_(165); _dereq_(166); _dereq_(167); _dereq_(231); _dereq_(236); _dereq_(243); _dereq_(234); _dereq_(226); _dereq_(227); _dereq_(232); _dereq_(237); _dereq_(239); _dereq_(222); _dereq_(223); _dereq_(224); _dereq_(225); _dereq_(228); _dereq_(229); _dereq_(230); _dereq_(233); _dereq_(235); _dereq_(238); _dereq_(240); _dereq_(241); _dereq_(242); _dereq_(142); _dereq_(144); _dereq_(143); _dereq_(146); _dereq_(145); _dereq_(130); _dereq_(128); _dereq_(135); _dereq_(132); _dereq_(138); _dereq_(140); _dereq_(127); _dereq_(134); _dereq_(124); _dereq_(139); _dereq_(122); _dereq_(137); _dereq_(136); _dereq_(129); _dereq_(133); _dereq_(121); _dereq_(123); _dereq_(126); _dereq_(125); _dereq_(141); _dereq_(131); _dereq_(214); _dereq_(220); _dereq_(215); _dereq_(216); _dereq_(217); _dereq_(218); _dereq_(219); _dereq_(199); _dereq_(150); _dereq_(221); _dereq_(256); _dereq_(257); _dereq_(245); _dereq_(246); _dereq_(251); _dereq_(254); _dereq_(255); _dereq_(249); _dereq_(252); _dereq_(250); _dereq_(253); _dereq_(247); _dereq_(248); _dereq_(200); _dereq_(201); _dereq_(202); _dereq_(203); _dereq_(204); _dereq_(207); _dereq_(205); _dereq_(206); _dereq_(208); _dereq_(209); _dereq_(210); _dereq_(211); _dereq_(213); _dereq_(212); _dereq_(258); _dereq_(284); _dereq_(287); _dereq_(286); _dereq_(288); _dereq_(289); _dereq_(285); _dereq_(290); _dereq_(291); _dereq_(269); _dereq_(272); _dereq_(268); _dereq_(266); _dereq_(267); _dereq_(270); _dereq_(271); _dereq_(261); _dereq_(283); _dereq_(292); _dereq_(260); _dereq_(262); _dereq_(264); _dereq_(263); _dereq_(265); _dereq_(274); _dereq_(275); _dereq_(277); _dereq_(276); _dereq_(279); _dereq_(278); _dereq_(280); _dereq_(281); _dereq_(282); _dereq_(259); _dereq_(273); _dereq_(295); _dereq_(294); _dereq_(293); module.exports = _dereq_(23); },{"121":121,"122":122,"123":123,"124":124,"125":125,"126":126,"127":127,"128":128,"129":129,"130":130,"131":131,"132":132,"133":133,"134":134,"135":135,"136":136,"137":137,"138":138,"139":139,"140":140,"141":141,"142":142,"143":143,"144":144,"145":145,"146":146,"147":147,"148":148,"149":149,"150":150,"151":151,"152":152,"153":153,"154":154,"155":155,"156":156,"157":157,"158":158,"159":159,"160":160,"161":161,"162":162,"163":163,"164":164,"165":165,"166":166,"167":167,"168":168,"169":169,"170":170,"171":171,"172":172,"173":173,"174":174,"175":175,"176":176,"177":177,"178":178,"179":179,"180":180,"181":181,"182":182,"183":183,"184":184,"185":185,"186":186,"187":187,"188":188,"189":189,"190":190,"191":191,"192":192,"193":193,"194":194,"195":195,"196":196,"197":197,"198":198,"199":199,"200":200,"201":201,"202":202,"203":203,"204":204,"205":205,"206":206,"207":207,"208":208,"209":209,"210":210,"211":211,"212":212,"213":213,"214":214,"215":215,"216":216,"217":217,"218":218,"219":219,"220":220,"221":221,"222":222,"223":223,"224":224,"225":225,"226":226,"227":227,"228":228,"229":229,"23":23,"230":230,"231":231,"232":232,"233":233,"234":234,"235":235,"236":236,"237":237,"238":238,"239":239,"240":240,"241":241,"242":242,"243":243,"244":244,"245":245,"246":246,"247":247,"248":248,"249":249,"250":250,"251":251,"252":252,"253":253,"254":254,"255":255,"256":256,"257":257,"258":258,"259":259,"260":260,"261":261,"262":262,"263":263,"264":264,"265":265,"266":266,"267":267,"268":268,"269":269,"270":270,"271":271,"272":272,"273":273,"274":274,"275":275,"276":276,"277":277,"278":278,"279":279,"280":280,"281":281,"282":282,"283":283,"284":284,"285":285,"286":286,"287":287,"288":288,"289":289,"290":290,"291":291,"292":292,"293":293,"294":294,"295":295}],297:[function(_dereq_,module,exports){ (function (global){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ !(function(global) { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided, then outerFn.prototype instanceof Generator. var generator = Object.create((outerFn || Generator).prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `value instanceof AwaitArgument` to determine if the yielded value is // meant to be awaited. Some may consider the name of this method too // cutesy, but they are curmudgeons. runtime.awrap = function(arg) { return new AwaitArgument(arg); }; function AwaitArgument(arg) { this.arg = arg; } function AsyncIterator(generator) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value instanceof AwaitArgument) { return Promise.resolve(value.arg).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return Promise.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; resolve(result); }, reject); } } if (typeof process === "object" && process.domain) { invoke = process.domain.bind(invoke); } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new Promise(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } while (true) { var delegate = context.delegate; if (delegate) { if (method === "return" || (method === "throw" && delegate.iterator[method] === undefined)) { // A return or throw (when the delegate iterator has no throw // method) always terminates the yield* loop. context.delegate = null; // If the delegate iterator has a return method, give it a // chance to clean up. var returnMethod = delegate.iterator["return"]; if (returnMethod) { var record = tryCatch(returnMethod, delegate.iterator, arg); if (record.type === "throw") { // If the return method threw an exception, let that // exception prevail over the original return or throw. method = "throw"; arg = record.arg; continue; } } if (method === "return") { // Continue with the outer return, now that the delegate // iterator has been terminated. continue; } } var record = tryCatch( delegate.iterator[method], delegate.iterator, arg ); if (record.type === "throw") { context.delegate = null; // Like returning generator.throw(uncaught), but without the // overhead of an extra function call. method = "throw"; arg = record.arg; continue; } // Delegate generator ran and handled its own exceptions so // regardless of what the method was, we continue as if it is // "next" with an undefined arg. method = "next"; arg = undefined; var info = record.arg; if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; } else { state = GenStateSuspendedYield; return info; } context.delegate = null; } if (method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = arg; } else if (method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw arg; } if (context.dispatchException(arg)) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. method = "next"; arg = undefined; } } else if (method === "return") { context.abrupt("return", arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; var info = { value: record.arg, done: context.done }; if (record.arg === ContinueSentinel) { if (context.delegate && method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. arg = undefined; } } else { return info; } } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(arg) call above. method = "throw"; arg = record.arg; } } }; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[iteratorSymbol] = function() { return this; }; Gp[toStringTagSymbol] = "Generator"; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, 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") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.next = finallyEntry.finallyLoc; } else { this.complete(record); } return ContinueSentinel; }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = record.arg; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; return ContinueSentinel; } }; })( // Among the various tricks for obtaining a reference to the global // object, this seems to be the most reliable technique that does not // use indirect eval (which violates Content Security Policy). typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : this ); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}]},{},[1]); (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('d3'), require('css-layout')) : typeof define === 'function' && define.amd ? define(['d3', 'css-layout'], factory) : (global.fc = factory(global.d3,global.computeLayout)); }(this, function (d3,computeLayout) { 'use strict'; d3 = 'default' in d3 ? d3['default'] : d3; computeLayout = 'default' in computeLayout ? computeLayout['default'] : computeLayout; var pi = Math.PI; var tau = 2 * pi; var epsilon = 1e-6; var tauEpsilon = tau - epsilon; function Path() { this._x0 = this._y0 = // start of current subpath this._x1 = this._y1 = null; // end of current subpath this._ = []; } function path() { return new Path(); } Path.prototype = path.prototype = { constructor: Path, moveTo: function moveTo(x, y) { this._.push("M", this._x0 = this._x1 = +x, ",", this._y0 = this._y1 = +y); }, closePath: function closePath() { if (this._x1 !== null) { this._x1 = this._x0, this._y1 = this._y0; this._.push("Z"); } }, lineTo: function lineTo(x, y) { this._.push("L", this._x1 = +x, ",", this._y1 = +y); }, quadraticCurveTo: function quadraticCurveTo(x1, y1, x, y) { this._.push("Q", +x1, ",", +y1, ",", this._x1 = +x, ",", this._y1 = +y); }, bezierCurveTo: function bezierCurveTo(x1, y1, x2, y2, x, y) { this._.push("C", +x1, ",", +y1, ",", +x2, ",", +y2, ",", this._x1 = +x, ",", this._y1 = +y); }, arcTo: function arcTo(x1, y1, x2, y2, r) { x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r; var x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01; // Is the radius negative? Error. if (r < 0) throw new Error("negative radius: " + r); // Is this path empty? Move to (x1,y1). if (this._x1 === null) { this._.push("M", this._x1 = x1, ",", this._y1 = y1); } // Or, is (x1,y1) coincident with (x0,y0)? Do nothing. else if (!(l01_2 > epsilon)) ; // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear? // Equivalently, is (x1,y1) coincident with (x2,y2)? // Or, is the radius zero? Line to (x1,y1). else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) { this._.push("L", this._x1 = x1, ",", this._y1 = y1); } // Otherwise, draw an arc! else { var x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21; // If the start tangent is not coincident with (x0,y0), line to. if (Math.abs(t01 - 1) > epsilon) { this._.push("L", x1 + t01 * x01, ",", y1 + t01 * y01); } this._.push("A", r, ",", r, ",0,0,", +(y01 * x20 > x01 * y20), ",", this._x1 = x1 + t21 * x21, ",", this._y1 = y1 + t21 * y21); } }, arc: function arc(x, y, r, a0, a1, ccw) { x = +x, y = +y, r = +r; var dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x + dx, y0 = y + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0; // Is the radius negative? Error. if (r < 0) throw new Error("negative radius: " + r); // Is this path empty? Move to (x0,y0). if (this._x1 === null) { this._.push("M", x0, ",", y0); } // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0). else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) { this._.push("L", x0, ",", y0); } // Is this arc empty? We’re done. if (!r) return; // Is this a complete circle? Draw two arcs to complete the circle. if (da > tauEpsilon) { this._.push("A", r, ",", r, ",0,1,", cw, ",", x - dx, ",", y - dy, "A", r, ",", r, ",0,1,", cw, ",", this._x1 = x0, ",", this._y1 = y0); } // Otherwise, draw an arc! else { if (da < 0) da = da % tau + tau; this._.push("A", r, ",", r, ",0,", +(da >= pi), ",", cw, ",", this._x1 = x + r * Math.cos(a1), ",", this._y1 = y + r * Math.sin(a1)); } }, rect: function rect(x, y, w, h) { this._.push("M", this._x0 = this._x1 = +x, ",", this._y0 = this._y1 = +y, "h", +w, "v", +h, "h", -w, "Z"); }, toString: function toString() { return this._.join(""); } }; var functor = (function (v) { return typeof v === 'function' ? v : function () { return v; }; }) // Renders an OHLC as an SVG path based on the given array of datapoints. Each // OHLC has a fixed width, whilst the x, open, high, low and close positions are // obtained from each point via the supplied accessor functions. var ohlc = (function () { var context = null; var x = function x(d) { return d.date; }; var open = function open(d) { return d.open; }; var high = function high(d) { return d.high; }; var low = function low(d) { return d.low; }; var close = function close(d) { return d.close; }; var orient = 'vertical'; var width = functor(3); var ohlc = function ohlc(data) { var buffer = context ? undefined : context = path(); data.forEach(function (d, i) { var xValue = x(d, i); var yOpen = open(d, i); var yHigh = high(d, i); var yLow = low(d, i); var yClose = close(d, i); var halfWidth = width(d, i) / 2; if (orient === 'vertical') { context.moveTo(xValue, yLow); context.lineTo(xValue, yHigh); context.moveTo(xValue, yOpen); context.lineTo(xValue - halfWidth, yOpen); context.moveTo(xValue, yClose); context.lineTo(xValue + halfWidth, yClose); } else { context.moveTo(yLow, xValue); context.lineTo(yHigh, xValue); context.moveTo(yOpen, xValue); context.lineTo(yOpen, xValue + halfWidth); context.moveTo(yClose, xValue); context.lineTo(yClose, xValue - halfWidth); } }); return buffer && (context = null, buffer.toString() || null); }; ohlc.context = function () { if (!arguments.length) { return context; } context = arguments.length <= 0 ? undefined : arguments[0]; return ohlc; }; ohlc.x = function () { if (!arguments.length) { return x; } x = functor(arguments.length <= 0 ? undefined : arguments[0]); return ohlc; }; ohlc.open = function () { if (!arguments.length) { return open; } open = functor(arguments.length <= 0 ? undefined : arguments[0]); return ohlc; }; ohlc.high = function () { if (!arguments.length) { return high; } high = functor(arguments.length <= 0 ? undefined : arguments[0]); return ohlc; }; ohlc.low = function () { if (!arguments.length) { return low; } low = functor(arguments.length <= 0 ? undefined : arguments[0]); return ohlc; }; ohlc.close = function () { if (!arguments.length) { return close; } close = functor(arguments.length <= 0 ? undefined : arguments[0]); return ohlc; }; ohlc.width = function () { if (!arguments.length) { return width; } width = functor(arguments.length <= 0 ? undefined : arguments[0]); return ohlc; }; ohlc.orient = function () { if (!arguments.length) { return orient; } orient = arguments.length <= 0 ? undefined : arguments[0]; return ohlc; }; return ohlc; }) // Renders a bar series as an SVG path based on the given array of datapoints. Each // bar has a fixed width, whilst the x, y and height are obtained from each data // point via the supplied accessor functions. var bar = (function () { var context = null; var x = function x(d) { return d.x; }; var y = function y(d) { return d.y; }; var horizontalAlign = 'center'; var verticalAlign = 'center'; var height = function height(d) { return d.height; }; var width = functor(3); var bar = function bar(data, index) { var buffer = context ? undefined : context = path(); data.forEach(function (d, i) { var xValue = x.call(this, d, index || i); var yValue = y.call(this, d, index || i); var barHeight = height.call(this, d, index || i); var barWidth = width.call(this, d, index || i); var horizontalOffset = void 0; switch (horizontalAlign) { case 'left': horizontalOffset = barWidth; break; case 'right': horizontalOffset = 0; break; case 'center': horizontalOffset = barWidth / 2; break; default: throw new Error('Invalid horizontal alignment ' + horizontalAlign); } var verticalOffset = void 0; switch (verticalAlign) { case 'bottom': verticalOffset = -barHeight; break; case 'top': verticalOffset = 0; break; case 'center': verticalOffset = barHeight / 2; break; default: throw new Error('Invalid vertical alignment ' + verticalAlign); } context.rect(xValue - horizontalOffset, yValue - verticalOffset, barWidth, barHeight); }, this); return buffer && (context = null, buffer.toString() || null); }; bar.context = function () { if (!arguments.length) { return context; } context = arguments.length <= 0 ? undefined : arguments[0]; return bar; }; bar.x = function () { if (!arguments.length) { return x; } x = functor(arguments.length <= 0 ? undefined : arguments[0]); return bar; }; bar.y = function () { if (!arguments.length) { return y; } y = functor(arguments.length <= 0 ? undefined : arguments[0]); return bar; }; bar.width = function () { if (!arguments.length) { return width; } width = functor(arguments.length <= 0 ? undefined : arguments[0]); return bar; }; bar.horizontalAlign = function () { if (!arguments.length) { return horizontalAlign; } horizontalAlign = arguments.length <= 0 ? undefined : arguments[0]; return bar; }; bar.height = function () { if (!arguments.length) { return height; } height = functor(arguments.length <= 0 ? undefined : arguments[0]); return bar; }; bar.verticalAlign = function () { if (!arguments.length) { return verticalAlign; } verticalAlign = arguments.length <= 0 ? undefined : arguments[0]; return bar; }; return bar; }) // Renders a candlestick as an SVG path based on the given array of datapoints. Each // candlestick has a fixed width, whilst the x, open, high, low and close positions are // obtained from each point via the supplied accessor functions. var candlestick = (function () { var context = null; var x = function x(d) { return d.date; }; var open = function open(d) { return d.open; }; var high = function high(d) { return d.high; }; var low = function low(d) { return d.low; }; var close = function close(d) { return d.close; }; var width = functor(3); var candlestick = function candlestick(data) { var buffer = context ? undefined : context = path(); data.forEach(function (d, i) { var xValue = x(d, i); var yOpen = open(d, i); var yHigh = high(d, i); var yLow = low(d, i); var yClose = close(d, i); var barWidth = width(d, i); var halfBarWidth = barWidth / 2; // Body context.rect(xValue - halfBarWidth, yOpen, barWidth, yClose - yOpen); // High wick // // Move to the max price of close or open; draw the high wick // N.B. Math.min() is used as we're dealing with pixel values, // the lower the pixel value, the higher the price! context.moveTo(xValue, Math.min(yClose, yOpen)); context.lineTo(xValue, yHigh); // Low wick // // Move to the min price of close or open; draw the low wick // N.B. Math.max() is used as we're dealing with pixel values, // the higher the pixel value, the lower the price! context.moveTo(xValue, Math.max(yClose, yOpen)); context.lineTo(xValue, yLow); }); return buffer && (context = null, buffer.toString() || null); }; candlestick.context = function () { if (!arguments.length) { return context; } context = arguments.length <= 0 ? undefined : arguments[0]; return candlestick; }; candlestick.x = function () { if (!arguments.length) { return x; } x = functor(arguments.length <= 0 ? undefined : arguments[0]); return candlestick; }; candlestick.open = function () { if (!arguments.length) { return open; } open = functor(arguments.length <= 0 ? undefined : arguments[0]); return candlestick; }; candlestick.high = function () { if (!arguments.length) { return high; } high = functor(arguments.length <= 0 ? undefined : arguments[0]); return candlestick; }; candlestick.low = function () { if (!arguments.length) { return low; } low = functor(arguments.length <= 0 ? undefined : arguments[0]); return candlestick; }; candlestick.close = function () { if (!arguments.length) { return close; } close = functor(arguments.length <= 0 ? undefined : arguments[0]); return candlestick; }; candlestick.width = function () { if (!arguments.length) { return width; } width = functor(arguments.length <= 0 ? undefined : arguments[0]); return candlestick; }; return candlestick; }) // Renders a box plot series as an SVG path based on the given array of datapoints. var boxPlot = (function () { var context = null; var value = function value(d) { return d.value; }; var median = function median(d) { return d.median; }; var upperQuartile = function upperQuartile(d) { return d.upperQuartile; }; var lowerQuartile = function lowerQuartile(d) { return d.lowerQuartile; }; var high = function high(d) { return d.high; }; var low = function low(d) { return d.low; }; var orient = 'vertical'; var width = functor(5); var cap = functor(0.5); var boxPlot = function boxPlot(data) { var buffer = context ? undefined : context = path(); data.forEach(function (d, i) { // naming convention is for vertical orientation var _value = value(d, i); var _width = width(d, i); var halfWidth = _width / 2; var capWidth = _width * cap(d, i); var halfCapWidth = capWidth / 2; var _high = high(d, i); var _upperQuartile = upperQuartile(d, i); var _median = median(d, i); var _lowerQuartile = lowerQuartile(d, i); var _low = low(d, i); var upperQuartileToLowerQuartile = _lowerQuartile - _upperQuartile; if (orient === 'vertical') { // Upper whisker context.moveTo(_value - halfCapWidth, _high); context.lineTo(_value + halfCapWidth, _high); context.moveTo(_value, _high); context.lineTo(_value, _upperQuartile); // Box context.rect(_value - halfWidth, _upperQuartile, _width, upperQuartileToLowerQuartile); context.moveTo(_value - halfWidth, _median); // Median line context.lineTo(_value + halfWidth, _median); // Lower whisker context.moveTo(_value, _lowerQuartile); context.lineTo(_value, _low); context.moveTo(_value - halfCapWidth, _low); context.lineTo(_value + halfCapWidth, _low); } else { // Lower whisker context.moveTo(_low, _value - halfCapWidth); context.lineTo(_low, _value + halfCapWidth); context.moveTo(_low, _value); context.lineTo(_lowerQuartile, _value); // Box context.rect(_lowerQuartile, _value - halfWidth, -upperQuartileToLowerQuartile, _width); context.moveTo(_median, _value - halfWidth); context.lineTo(_median, _value + halfWidth); // Upper whisker context.moveTo(_upperQuartile, _value); context.lineTo(_high, _value); context.moveTo(_high, _value - halfCapWidth); context.lineTo(_high, _value + halfCapWidth); } }); return buffer && (context = null, buffer.toString() || null); }; boxPlot.context = function () { if (!arguments.length) { return context; } context = arguments.length <= 0 ? undefined : arguments[0]; return boxPlot; }; boxPlot.value = function () { if (!arguments.length) { return value; } value = functor(arguments.length <= 0 ? undefined : arguments[0]); return boxPlot; }; boxPlot.median = function () { if (!arguments.length) { return median; } median = functor(arguments.length <= 0 ? undefined : arguments[0]); return boxPlot; }; boxPlot.upperQuartile = function () { if (!arguments.length) { return upperQuartile; } upperQuartile = functor(arguments.length <= 0 ? undefined : arguments[0]); return boxPlot; }; boxPlot.lowerQuartile = function () { if (!arguments.length) { return lowerQuartile; } lowerQuartile = functor(arguments.length <= 0 ? undefined : arguments[0]); return boxPlot; }; boxPlot.high = function () { if (!arguments.length) { return high; } high = functor(arguments.length <= 0 ? undefined : arguments[0]); return boxPlot; }; boxPlot.low = function () { if (!arguments.length) { return low; } low = functor(arguments.length <= 0 ? undefined : arguments[0]); return boxPlot; }; boxPlot.width = function () { if (!arguments.length) { return width; } width = functor(arguments.length <= 0 ? undefined : arguments[0]); return boxPlot; }; boxPlot.orient = function () { if (!arguments.length) { return orient; } orient = arguments.length <= 0 ? undefined : arguments[0]; return boxPlot; }; boxPlot.cap = function () { if (!arguments.length) { return cap; } cap = functor(arguments.length <= 0 ? undefined : arguments[0]); return boxPlot; }; return boxPlot; }) // Renders an error bar series as an SVG path based on the given array of datapoints. var errorBar = (function () { var context = null; var value = function value(d) { return d.x; }; var high = function high(d) { return d.high; }; var low = function low(d) { return d.low; }; var orient = 'vertical'; var width = functor(5); var errorBar = function errorBar(data) { var buffer = context ? undefined : context = path(); data.forEach(function (d, i) { // naming convention is for vertical orientation var _value = value(d, i); var _width = width(d, i); var halfWidth = _width / 2; var _high = high(d, i); var _low = low(d, i); if (orient === 'vertical') { context.moveTo(_value - halfWidth, _high); context.lineTo(_value + halfWidth, _high); context.moveTo(_value, _high); context.lineTo(_value, _low); context.moveTo(_value - halfWidth, _low); context.lineTo(_value + halfWidth, _low); } else { context.moveTo(_low, _value - halfWidth); context.lineTo(_low, _value + halfWidth); context.moveTo(_low, _value); context.lineTo(_high, _value); context.moveTo(_high, _value - halfWidth); context.lineTo(_high, _value + halfWidth); } }); return buffer && (context = null, buffer.toString() || null); }; errorBar.context = function () { if (!arguments.length) { return context; } context = arguments.length <= 0 ? undefined : arguments[0]; return errorBar; }; errorBar.value = function () { if (!arguments.length) { return value; } value = functor(arguments.length <= 0 ? undefined : arguments[0]); return errorBar; }; errorBar.high = function () { if (!arguments.length) { return high; } high = functor(arguments.length <= 0 ? undefined : arguments[0]); return errorBar; }; errorBar.low = function () { if (!arguments.length) { return low; } low = functor(arguments.length <= 0 ? undefined : arguments[0]); return errorBar; }; errorBar.width = function () { if (!arguments.length) { return width; } width = functor(arguments.length <= 0 ? undefined : arguments[0]); return errorBar; }; errorBar.orient = function () { if (!arguments.length) { return orient; } orient = arguments.length <= 0 ? undefined : arguments[0]; return errorBar; }; return errorBar; }) function context() { return this; } function identity(d) { return d; } function index(d, i) { return i; } function noop(d) {} // Checks that passes properties are 'defined', meaning that calling them with (d, i) returns non null values function defined() { var outerArguments = arguments; return function (d, i) { for (var c = 0, j = outerArguments.length; c < j; c++) { if (outerArguments[c](d, i) == null) { return false; } } return true; }; } var fn = Object.freeze({ context: context, identity: identity, index: index, noop: noop, defined: defined }); // "Caution: avoid interpolating to or from the number zero when the interpolator is used to generate // a string (such as with attr). // Very small values, when stringified, may be converted to scientific notation and // cause a temporarily invalid attribute or style property value. // For example, the number 0.0000001 is converted to the string "1e-7". // This is particularly noticeable when interpolating opacity values. // To avoid scientific notation, start or end the transition at 1e-6, // which is the smallest value that is not stringified in exponential notation." // - https://github.com/mbostock/d3/wiki/Transitions#d3_interpolateNumber var effectivelyZero = 1e-6; // Wrapper around d3's selectAll/data data-join, which allows decoration of the result. // This is achieved by appending the element to the enter selection before exposing it. // A default transition of fade in/out is also implicitly added but can be modified. function dataJoin () { var selector = 'g', children = false, element = 'g', attr = {}, key = index; var dataJoin = function dataJoin(container, data) { var joinedData = data || identity; // Can't use instanceof d3.selection (see #458) if (!(container.selectAll && container.node)) { container = d3.select(container); } // update var selection = container.selectAll(selector); if (children) { // in order to support nested selections, they can be filtered // to only return immediate children of the container selection = selection.filter(function () { return this.parentNode === container.node(); }); } var updateSelection = selection.data(joinedData, key); // enter // when container is a transition, entering elements fade in (from transparent to opaque) // N.B. insert() is used to create new elements, rather than append(). insert() behaves in a special manner // on enter selections - entering elements will be inserted immediately before the next following sibling // in the update selection, if any. // This helps order the elements in an order consistent with the data, but doesn't guarantee the ordering; // if the updating elements change order then selection.order() would be required to update the order. // (#528) var enterSelection = updateSelection.enter().insert(element) // <<<--- this is the secret sauce of this whole file .attr(attr).style('opacity', effectivelyZero); // exit // when container is a transition, exiting elements fade out (from opaque to transparent) var exitSelection = d3.transition(updateSelection.exit()).style('opacity', effectivelyZero).remove(); // when container is a transition, all properties of the transition (which can be interpolated) // will transition updateSelection = d3.transition(updateSelection).style('opacity', 1); updateSelection.enter = d3.functor(enterSelection); updateSelection.exit = d3.functor(exitSelection); return updateSelection; }; dataJoin.selector = function (x) { if (!arguments.length) { return selector; } selector = x; return dataJoin; }; dataJoin.children = function (x) { if (!arguments.length) { return children; } children = x; return dataJoin; }; dataJoin.element = function (x) { if (!arguments.length) { return element; } element = x; return dataJoin; }; dataJoin.attr = function (x) { if (!arguments.length) { return attr; } if (arguments.length === 1) { attr = arguments[0]; } else if (arguments.length === 2) { var dataKey = arguments[0]; var value = arguments[1]; attr[dataKey] = value; } return dataJoin; }; dataJoin.key = function (x) { if (!arguments.length) { return key; } key = x; return dataJoin; }; return dataJoin; } function isOrdinal(scale) { return scale.rangeExtent; } // ordinal axes have a rangeExtent function, this adds any padding that // was applied to the range. This functions returns the rangeExtent // if present, or range otherwise /// // NOTE: d3 uses very similar logic here: // https://github.com/mbostock/d3/blob/5b981a18db32938206b3579248c47205ecc94123/src/scale/scale.js#L8 function range(scale) { // for non ordinal, simply return the range if (!isOrdinal(scale)) { return scale.range(); } // For ordinal, use the rangeExtent. However, rangeExtent always provides // a non inverted range (i.e. extent[0] < extent[1]) regardless of the // range set on the scale. The logic below detects the inverted case. // // The d3 code that tackles the same issue doesn't have to deal with the inverted case. var scaleRange = scale.range(); var extent = scale.rangeExtent(); if (scaleRange.length <= 1) { // we cannot detect the inverted case if the range (and domain) has // a single item in it. return extent; } var inverted = scaleRange[0] > scaleRange[1]; return inverted ? [extent[1], extent[0]] : extent; } // Ordinal and quantitative scales have different methods for setting the range. This // function detects the scale type and sets the range accordingly. function setRange(scale, scaleRange) { if (isOrdinal(scale)) { scale.rangePoints(scaleRange, 1); } else { scale.range(scaleRange); } } var scale = Object.freeze({ isOrdinal: isOrdinal, range: range, setRange: setRange }); function band () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), x0, x1, y0, y1, x0Scaled = function x0Scaled() { return range(xScale)[0]; }, x1Scaled = function x1Scaled() { return range(xScale)[1]; }, y0Scaled = function y0Scaled() { return range(yScale)[0]; }, y1Scaled = function y1Scaled() { return range(yScale)[1]; }, decorate = noop; var dataJoin$$ = dataJoin().selector('g.annotation').element('g').attr('class', 'annotation'); var band = function band(selection) { selection.each(function (data, index) { var container = d3.select(this); var g = dataJoin$$(container, data); g.enter().append('path').classed('band', true); var pathGenerator = bar().horizontalAlign('right').verticalAlign('top').x(x0Scaled).y(y0Scaled).height(function () { return y1Scaled.apply(this, arguments) - y0Scaled.apply(this, arguments); }).width(function () { return x1Scaled.apply(this, arguments) - x0Scaled.apply(this, arguments); }); g.select('path').attr('d', function (d, i) { // the path generator is being used to render a single path, hence // an explicit index is provided return pathGenerator.call(this, [d], i); }); decorate(g, data, index); }); }; band.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return band; }; band.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return band; }; band.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return band; }; band.x0 = function (x) { if (!arguments.length) { return x0; } x0 = d3.functor(x); x0Scaled = function x0Scaled() { return xScale(x0.apply(this, arguments)); }; return band; }; band.x1 = function (x) { if (!arguments.length) { return x1; } x1 = d3.functor(x); x1Scaled = function x1Scaled() { return xScale(x1.apply(this, arguments)); }; return band; }; band.y0 = function (x) { if (!arguments.length) { return y0; } y0 = d3.functor(x); y0Scaled = function y0Scaled() { return yScale(y0.apply(this, arguments)); }; return band; }; band.y1 = function (x) { if (!arguments.length) { return y1; } y1 = d3.functor(x); y1Scaled = function y1Scaled() { return yScale(y1.apply(this, arguments)); }; return band; }; return band; } function _ticks () { var scale = d3.scale.identity(), tickArguments = [10], tickValues = null; function tryApply(fn, defaultVal) { return scale[fn] ? scale[fn].apply(scale, tickArguments) : defaultVal; } var ticks = function ticks() { return tickValues == null ? tryApply('ticks', scale.domain()) : tickValues; }; ticks.scale = function (x) { if (!arguments.length) { return scale; } scale = x; return ticks; }; ticks.ticks = function (x) { if (!arguments.length) { return tickArguments; } tickArguments = arguments; return ticks; }; ticks.tickValues = function (x) { if (!arguments.length) { return tickValues; } tickValues = x; return ticks; }; return ticks; } var regexify = (function (strsOrRegexes) { return strsOrRegexes.map(function (strOrRegex) { return typeof strOrRegex === 'string' ? new RegExp('^' + strOrRegex + '$') : strOrRegex; }); }) var include = (function () { for (var _len = arguments.length, inclusions = Array(_len), _key = 0; _key < _len; _key++) { inclusions[_key] = arguments[_key]; } inclusions = regexify(inclusions); return function (name) { return inclusions.some(function (inclusion) { return inclusion.test(name); }) && name; }; }) var createTransform = function createTransform(transforms) { return function (name) { return transforms.reduce(function (name, fn) { return name && fn(name); }, name); }; }; var createReboundMethod = function createReboundMethod(target, source, name) { var method = source[name]; if (typeof method !== 'function') { throw new Error('Attempt to rebind ' + name + ' which isn\'t a function on the source object'); } return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var value = method.apply(source, args); return value === source ? target : value; }; }; var rebindAll = (function (target, source) { for (var _len2 = arguments.length, transforms = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { transforms[_key2 - 2] = arguments[_key2]; } var transform = createTransform(transforms); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(source)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var name = _step.value; var result = transform(name); if (result) { target[result] = createReboundMethod(target, source, name); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return target; }) var rebind = (function (target, source) { for (var _len = arguments.length, names = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { names[_key - 2] = arguments[_key]; } return rebindAll(target, source, include.apply(undefined, names)); }) var exclude = (function () { for (var _len = arguments.length, exclusions = Array(_len), _key = 0; _key < _len; _key++) { exclusions[_key] = arguments[_key]; } exclusions = regexify(exclusions); return function (name) { return exclusions.every(function (exclusion) { return !exclusion.test(name); }) && name; }; }) var includeMap = (function (mappings) { return function (name) { return mappings[name]; }; }) var capitalizeFirstLetter = function capitalizeFirstLetter(str) { return str[0].toUpperCase() + str.slice(1); }; var prefix = (function (prefix) { return function (name) { return prefix + capitalizeFirstLetter(name); }; }) function gridline () { var xTicks = _ticks(), yTicks = _ticks(); var xDecorate = noop, yDecorate = noop; var xLineDataJoin = dataJoin().selector('line.x').element('line').attr('class', 'x gridline'); var yLineDataJoin = dataJoin().selector('line.y').element('line').attr('class', 'y gridline'); var gridlines = function gridlines(selection) { selection.each(function (data, index) { var xScale = xTicks.scale(), yScale = yTicks.scale(); var xData = xTicks(); var xLines = xLineDataJoin(this, xData); xLines.attr({ 'x1': xScale, 'x2': xScale, 'y1': range(yScale)[0], 'y2': range(yScale)[1] }); xDecorate(xLines, xData, index); var yData = yTicks(); var yLines = yLineDataJoin(this, yData); yLines.attr({ 'x1': range(xScale)[0], 'x2': range(xScale)[1], 'y1': yScale, 'y2': yScale }); yDecorate(yLines, yData, index); }); }; gridlines.yDecorate = function (x) { if (!arguments.length) { return yDecorate; } yDecorate = x; return gridlines; }; gridlines.xDecorate = function (x) { if (!arguments.length) { return xDecorate; } xDecorate = x; return gridlines; }; rebindAll(gridlines, xLineDataJoin, includeMap({ 'key': 'xKey' })); rebindAll(gridlines, yLineDataJoin, includeMap({ 'key': 'yKey' })); rebindAll(gridlines, xTicks, prefix('x')); rebindAll(gridlines, yTicks, prefix('y')); return gridlines; } function line () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), value = identity, keyValue = index, label = value, decorate = noop, orient = 'horizontal'; var dataJoin$$ = dataJoin().selector('g.annotation').element('g'); var line = function line(selection) { selection.each(function (data, selectionIndex) { // the value scale which the annotation 'value' relates to, the crossScale // is the other. Which is which depends on the orienation! var valueScale, crossScale, translation, lineProperty, handleOne, handleTwo, textAttributes = { x: -5, y: -5 }; switch (orient) { case 'horizontal': translation = function translation(a, b) { return 'translate(' + a + ', ' + b + ')'; }; lineProperty = 'x2'; crossScale = xScale; valueScale = yScale; handleOne = 'left-handle'; handleTwo = 'right-handle'; break; case 'vertical': translation = function translation(a, b) { return 'translate(' + b + ', ' + a + ')'; }; lineProperty = 'y2'; crossScale = yScale; valueScale = xScale; textAttributes.transform = 'rotate(-90)'; handleOne = 'bottom-handle'; handleTwo = 'top-handle'; break; default: throw new Error('Invalid orientation'); } var scaleRange = range(crossScale), // the transform that sets the 'origin' of the annotation containerTransform = function containerTransform(d) { var transform = valueScale(value(d)); return translation(scaleRange[0], transform); }, scaleWidth = scaleRange[1] - scaleRange[0]; var container = d3.select(this); // Create a group for each line dataJoin$$.attr('class', 'annotation ' + orient); var g = dataJoin$$(container, data); // create the outer container and line var enter = g.enter().attr('transform', containerTransform); enter.append('line').attr(lineProperty, scaleWidth); // create containers at each end of the annotation enter.append('g').classed(handleOne, true); enter.append('g').classed(handleTwo, true).attr('transform', translation(scaleWidth, 0)).append('text').attr(textAttributes); // Update // translate the parent container to the left hand edge of the annotation g.attr('transform', containerTransform); // update the elements that depend on scale width g.select('line').attr(lineProperty, scaleWidth); g.select('g.' + handleTwo).attr('transform', translation(scaleWidth, 0)); // Update the text label g.select('text').text(label); decorate(g, data, selectionIndex); }); }; line.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return line; }; line.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return line; }; line.value = function (x) { if (!arguments.length) { return value; } value = d3.functor(x); return line; }; line.keyValue = function (x) { if (!arguments.length) { return keyValue; } keyValue = d3.functor(x); return line; }; line.label = function (x) { if (!arguments.length) { return label; } label = d3.functor(x); return line; }; line.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return line; }; line.orient = function (x) { if (!arguments.length) { return orient; } orient = x; return line; }; return line; } var annotation = { band: band, gridline: gridline, line: line }; // A drop-in replacement for the D3 axis, supporting the decorate pattern. function axis$1 () { var decorate = noop, orient = 'bottom', tickFormat = null, outerTickSize = 6, innerTickSize = 6, tickPadding = 3, svgDomainLine = d3.svg.line(), ticks = _ticks(); var dataJoin$$ = dataJoin().selector('g.tick').element('g').key(identity).attr('class', 'tick'); var domainPathDataJoin = dataJoin().selector('path.domain').element('path').attr('class', 'domain'); // returns a function that creates a translation based on // the bound data function containerTranslate(s, trans) { return function (d) { return trans(s(d), 0); }; } function translate(x, y) { if (isVertical()) { return 'translate(' + y + ', ' + x + ')'; } else { return 'translate(' + x + ', ' + y + ')'; } } function pathTranspose(arr) { if (isVertical()) { return arr.map(function (d) { return [d[1], d[0]]; }); } else { return arr; } } function isVertical() { return orient === 'left' || orient === 'right'; } function tryApply(fn, defaultVal) { var scale = ticks.scale(); return scale[fn] ? scale[fn].apply(scale, ticks.ticks()) : defaultVal; } var axis = function axis(selection) { selection.each(function (data, index) { var scale = ticks.scale(); // Stash a snapshot of the new scale, and retrieve the old snapshot. var scaleOld = this.__chart__ || scale; this.__chart__ = scale.copy(); var ticksArray = ticks(); var tickFormatter = tickFormat == null ? tryApply('tickFormat', identity) : tickFormat; var sign = orient === 'bottom' || orient === 'right' ? 1 : -1; var container = d3.select(this); // add the domain line var range$$ = range(scale); var domainPathData = pathTranspose([[range$$[0], sign * outerTickSize], [range$$[0], 0], [range$$[1], 0], [range$$[1], sign * outerTickSize]]); var domainLine = domainPathDataJoin(container, [data]); domainLine.attr('d', svgDomainLine(domainPathData)); // datajoin and construct the ticks / label dataJoin$$.attr({ // set the initial tick position based on the previous scale // in order to get the correct enter transition - however, for ordinal // scales the tick will not exist on the old scale, so use the current position 'transform': containerTranslate(isOrdinal(scale) ? scale : scaleOld, translate) }); var g = dataJoin$$(container, ticksArray); // enter g.enter().append('path'); var labelOffset = sign * (innerTickSize + tickPadding); g.enter().append('text').attr('transform', translate(0, labelOffset)); // update g.attr('class', 'tick orient-' + orient); g.attr('transform', containerTranslate(scale, translate)); g.select('path').attr('d', function (d) { return svgDomainLine(pathTranspose([[0, 0], [0, sign * innerTickSize]])); }); g.select('text').attr('transform', translate(0, labelOffset)).attr('dy', function () { var offset = '0em'; if (isVertical()) { offset = '0.32em'; } else if (orient === 'bottom') { offset = '0.71em'; } return offset; }).text(tickFormatter); // exit - for non ordinal scales, exit by animating the tick to its new location if (!isOrdinal(scale)) { g.exit().attr('transform', containerTranslate(scale, translate)); } decorate(g, data, index); }); }; axis.tickFormat = function (x) { if (!arguments.length) { return tickFormat; } tickFormat = x; return axis; }; axis.tickSize = function (x) { var n = arguments.length; if (!n) { return innerTickSize; } innerTickSize = Number(x); outerTickSize = Number(arguments[n - 1]); return axis; }; axis.innerTickSize = function (x) { if (!arguments.length) { return innerTickSize; } innerTickSize = Number(x); return axis; }; axis.outerTickSize = function (x) { if (!arguments.length) { return outerTickSize; } outerTickSize = Number(x); return axis; }; axis.tickPadding = function (x) { if (!arguments.length) { return tickPadding; } tickPadding = x; return axis; }; axis.orient = function (x) { if (!arguments.length) { return orient; } orient = x; return axis; }; axis.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return axis; }; rebindAll(axis, ticks); return axis; } // Adapts a fc.svg.axis for use as a series (i.e. accepts xScale/yScale). Only required when // you want an axis to appear in the middle of a chart e.g. as part of a cycle plot. Otherwise // prefer using the fc.svg.axis directly. function axis () { var axis = axis$1(), baseline = d3.functor(0), decorate = noop, xScale = d3.time.scale(), yScale = d3.scale.linear(); var dataJoin$$ = dataJoin().selector('g.axis-adapter').element('g').attr({ 'class': 'axis axis-adapter' }); var axisAdapter = function axisAdapter(selection) { selection.each(function (data, index) { var g = dataJoin$$(this, [data]); var translation; switch (axisAdapter.orient()) { case 'top': case 'bottom': translation = 'translate(0,' + yScale(baseline(data)) + ')'; axis.scale(xScale); break; case 'left': case 'right': translation = 'translate(' + xScale(baseline(data)) + ',0)'; axis.scale(yScale); break; default: throw new Error('Invalid orientation'); } g.enter().attr('transform', translation); g.attr('transform', translation); g.call(axis); decorate(g, data, index); }); }; axisAdapter.baseline = function (x) { if (!arguments.length) { return baseline; } baseline = d3.functor(x); return axisAdapter; }; axisAdapter.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return axisAdapter; }; axisAdapter.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return axisAdapter; }; axisAdapter.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return axisAdapter; }; return d3.rebind(axisAdapter, axis, 'orient', 'ticks', 'tickValues', 'tickSize', 'innerTickSize', 'outerTickSize', 'tickPadding', 'tickFormat'); } // "Caution: avoid interpolating to or from the number zero when the interpolator is used to generate // a string (such as with attr). // Very small values, when stringified, may be converted to scientific notation and // cause a temporarily invalid attribute or style property value. // For example, the number 0.0000001 is converted to the string "1e-7". // This is particularly noticeable when interpolating opacity values. // To avoid scientific notation, start or end the transition at 1e-6, // which is the smallest value that is not stringified in exponential notation." // - https://github.com/mbostock/d3/wiki/Transitions#d3_interpolateNumber var effectivelyZero$1 = 1e-6; // Wrapper around d3's selectAll/data data-join, which allows decoration of the result. // This is achieved by appending the element to the enter selection before exposing it. // A default transition of fade in/out is also implicitly added but can be modified. var dataJoinUtil = (function () { var selector = 'g'; var children = false; var element = 'g'; var attr = {}; var key = function key(_, i) { return i; }; var dataJoin = function dataJoin(container, data) { var joinedData = data || function (x) { return x; }; // Can't use instanceof d3.selection (see #458) if (!(container.selectAll && container.node)) { container = d3.select(container); } // update var selection = container.selectAll(selector); if (children) { // in order to support nested selections, they can be filtered // to only return immediate children of the container selection = selection.filter(function () { return this.parentNode === container.node(); }); } var updateSelection = selection.data(joinedData, key); // enter // when container is a transition, entering elements fade in (from transparent to opaque) // N.B. insert() is used to create new elements, rather than append(). insert() behaves in a special manner // on enter selections - entering elements will be inserted immediately before the next following sibling // in the update selection, if any. // This helps order the elements in an order consistent with the data, but doesn't guarantee the ordering; // if the updating elements change order then selection.order() would be required to update the order. // (#528) var enterSelection = updateSelection.enter().insert(element) // <<<--- this is the secret sauce of this whole file .attr(attr).style('opacity', effectivelyZero$1); // exit // when container is a transition, exiting elements fade out (from opaque to transparent) var exitSelection = d3.transition(updateSelection.exit()).style('opacity', effectivelyZero$1).remove(); // when container is a transition, all properties of the transition (which can be interpolated) // will transition updateSelection = d3.transition(updateSelection).style('opacity', 1); updateSelection.enter = d3.functor(enterSelection); updateSelection.exit = d3.functor(exitSelection); return updateSelection; }; dataJoin.selector = function (x) { if (!arguments.length) { return selector; } selector = x; return dataJoin; }; dataJoin.children = function (x) { if (!arguments.length) { return children; } children = x; return dataJoin; }; dataJoin.element = function (x) { if (!arguments.length) { return element; } element = x; return dataJoin; }; dataJoin.attr = function (x) { if (!arguments.length) { return attr; } if (arguments.length === 1) { attr = arguments[0]; } else if (arguments.length === 2) { var dataKey = arguments[0]; var value = arguments[1]; attr[dataKey] = value; } return dataJoin; }; dataJoin.key = function (x) { if (!arguments.length) { return key; } key = x; return dataJoin; }; return dataJoin; }) var regexify$1 = (function (strsOrRegexes) { return strsOrRegexes.map(function (strOrRegex) { return typeof strOrRegex === 'string' ? new RegExp('^' + strOrRegex + '$') : strOrRegex; }); }) var include$1 = (function () { for (var _len = arguments.length, inclusions = Array(_len), _key = 0; _key < _len; _key++) { inclusions[_key] = arguments[_key]; } inclusions = regexify$1(inclusions); return function (name) { return inclusions.some(function (inclusion) { return inclusion.test(name); }) && name; }; }) var createTransform$1 = function createTransform(transforms) { return function (name) { return transforms.reduce(function (name, fn) { return name && fn(name); }, name); }; }; var createReboundMethod$1 = function createReboundMethod(target, source, name) { var method = source[name]; if (typeof method !== 'function') { throw new Error('Attempt to rebind ' + name + ' which isn\'t a function on the source object'); } return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var value = method.apply(source, args); return value === source ? target : value; }; }; var rebindAll$1 = (function (target, source) { for (var _len2 = arguments.length, transforms = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { transforms[_key2 - 2] = arguments[_key2]; } var transform = createTransform$1(transforms); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(source)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var name = _step.value; var result = transform(name); if (result) { target[result] = createReboundMethod$1(target, source, name); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } }) function labelLayout (layoutStrategy) { var size = d3.functor([0, 0]); var position = function position(d, i) { return [d.x, d.y]; }; var strategy = layoutStrategy || function (x) { return x; }; var component = function component() {}; var dataJoin = dataJoinUtil().selector('g.label').element('g').attr('class', 'label'); var label = function label(selection) { selection.each(function (data, index) { var _this = this; var g = dataJoin(this, data).call(component); // obtain the rectangular bounding boxes for each child var childRects = g[0].map(function (node, i) { var d = d3.select(node).datum(); var childPos = position.call(node, d, i); var childSize = size.call(node, d, i); return { hidden: false, x: childPos[0], y: childPos[1], width: childSize[0], height: childSize[1] }; }); // apply the strategy to derive the layout. The strategy does not change the order // or number of label. var layout = strategy(childRects); g.attr({ 'style': function style(_, i) { return 'display:' + (layout[i].hidden ? 'none' : 'inherit'); }, 'transform': function transform(_, i) { return 'translate(' + layout[i].x + ', ' + layout[i].y + ')'; }, // set the layout width / height so that children can use SVG layout if required 'layout-width': function layoutWidth(_, i) { return layout[i].width; }, 'layout-height': function layoutHeight(_, i) { return layout[i].height; }, 'anchor-x': function anchorX(d, i) { return position.call(_this, d, i)[0] - layout[i].x; }, 'anchor-y': function anchorY(d, i) { return position.call(_this, d, i)[1] - layout[i].y; } }); g.call(component); }); }; rebindAll$1(label, dataJoin, include$1('key')); rebindAll$1(label, strategy); label.size = function (x) { if (!arguments.length) { return size; } size = d3.functor(x); return label; }; label.position = function (x) { if (!arguments.length) { return position; } position = d3.functor(x); return label; }; label.component = function (value) { if (!arguments.length) { return component; } component = value; return label; }; return label; } var textLabel = (function (layoutStrategy) { var padding = 2; var value = function value(x) { return x; }; var textJoin = dataJoinUtil().selector('text').element('text'); var rectJoin = dataJoinUtil().selector('rect').element('rect'); var pointJoin = dataJoinUtil().selector('circle').element('circle'); var textLabel = function textLabel(selection) { selection.each(function (data, index) { var width = Number(this.getAttribute('layout-width')); var height = Number(this.getAttribute('layout-height')); var rect = rectJoin(this, [data]); rect.attr({ 'width': width, 'height': height }); var anchorX = Number(this.getAttribute('anchor-x')); var anchorY = Number(this.getAttribute('anchor-y')); var circle = pointJoin(this, [data]); circle.attr({ 'r': 2, 'cx': anchorX, 'cy': anchorY }); var text = textJoin(this, [data]); text.enter().attr({ 'dy': '0.9em', 'transform': 'translate(' + padding + ', ' + padding + ')' }); text.text(value); }); }; textLabel.padding = function (x) { if (!arguments.length) { return padding; } padding = x; return textLabel; }; textLabel.value = function (x) { if (!arguments.length) { return value; } value = d3.functor(x); return textLabel; }; return textLabel; }) var isIntersecting = function isIntersecting(a, b) { return !(a.x >= b.x + b.width || a.x + a.width <= b.x || a.y >= b.y + b.height || a.y + a.height <= b.y); }; var intersect = (function (a, b) { if (isIntersecting(a, b)) { var left = Math.max(a.x, b.x); var right = Math.min(a.x + a.width, b.x + b.width); var top = Math.max(a.y, b.y); var bottom = Math.min(a.y + a.height, b.y + b.height); return (right - left) * (bottom - top); } else { return 0; } }) // computes the area of overlap between the rectangle with the given index with the // rectangles in the array var collisionArea = function collisionArea(rectangles, index) { return d3.sum(rectangles.map(function (d, i) { return index === i ? 0 : intersect(rectangles[index], d); })); }; // computes the total overlapping area of all of the rectangles in the given array var totalCollisionArea = function totalCollisionArea(rectangles) { return d3.sum(rectangles.map(function (_, i) { return collisionArea(rectangles, i); })); }; // searches for a minimum when applying the given accessor to each item within the supplied array. // The returned array has the following form: // [minumum accessor value, datum, index] var minimum = (function (data, accessor) { return data.map(function (dataPoint, index) { return [accessor(dataPoint, index), dataPoint, index]; }).reduce(function (accumulator, dataPoint) { return accumulator[0] > dataPoint[0] ? dataPoint : accumulator; }, [Number.MAX_VALUE, null, -1]); }) function getPlacement(x, y, width, height, location) { return { x: x, y: y, width: width, height: height, location: location }; } // returns all the potential placements of the given label var placements = (function (label) { var x = label.x; var y = label.y; var width = label.width; var height = label.height; return [getPlacement(x, y, width, height, 'bottom-right'), getPlacement(x - width, y, width, height, 'bottom-left'), getPlacement(x - width, y - height, width, height, 'top-left'), getPlacement(x, y - height, width, height, 'top-right'), getPlacement(x, y - height / 2, width, height, 'middle-right'), getPlacement(x - width / 2, y, width, height, 'bottom-center'), getPlacement(x - width, y - height / 2, width, height, 'middle-left'), getPlacement(x - width / 2, y - height, width, height, 'top-center')]; }) function greedy () { var bounds = [0, 0]; var scorer = function scorer(layout) { var areaOfCollisions = totalCollisionArea(layout); var areaOutsideContainer = 0; if (bounds[0] !== 0 && bounds[1] !== 0) { var containerRect = { x: 0, y: 0, width: bounds[0], height: bounds[1] }; areaOutsideContainer = d3.sum(layout.map(function (d) { var areaOutside = d.width * d.height - intersect(d, containerRect); // this bias is twice as strong as the overlap penalty return areaOutside * 2; })); } return areaOfCollisions + areaOutsideContainer; }; var strategy = function strategy(data) { var rectangles = []; data.forEach(function (rectangle) { // add this rectangle - in all its possible placements var candidateConfigurations = placements(rectangle).map(function (placement) { var copy = rectangles.slice(); copy.push(placement); return copy; }); // keep the one the minimises the 'score' rectangles = minimum(candidateConfigurations, scorer)[1]; }); return rectangles; }; strategy.bounds = function (x) { if (!arguments.length) { return bounds; } bounds = x; return strategy; }; return strategy; } var randomItem = function randomItem(array) { return array[randomIndex(array)]; }; var randomIndex = function randomIndex(array) { return Math.floor(Math.random() * array.length); }; var cloneAndReplace = function cloneAndReplace(array, index, replacement) { var clone = array.slice(); clone[index] = replacement; return clone; }; var annealing = (function () { var temperature = 1000; var cooling = 1; var bounds = [0, 0]; function getPotentialState(originalData, iteratedData) { // For one point choose a random other placement. var victimLabelIndex = randomIndex(originalData); var label = originalData[victimLabelIndex]; var replacements = placements(label); var replacement = randomItem(replacements); return cloneAndReplace(iteratedData, victimLabelIndex, replacement); } function scorer(layout) { // penalise collisions var collisionArea = totalCollisionArea(layout); // penalise rectangles falling outside of the bounds var areaOutsideContainer = 0; if (bounds[0] !== 0 && bounds[1] !== 0) { var containerRect = { x: 0, y: 0, width: bounds[0], height: bounds[1] }; areaOutsideContainer = d3.sum(layout.map(function (d) { var areaOutside = d.width * d.height - intersect(d, containerRect); // this bias is twice as strong as the overlap penalty return areaOutside * 2; })); } // penalise certain orientations var orientationBias = d3.sum(layout.map(function (d) { // this bias is not as strong as overlap penalty var area = d.width * d.height / 4; if (d.location === 'bottom-right') { area = 0; } if (d.location === 'middle-right' || d.location === 'bottom-center') { area = area / 2; } return area; })); return collisionArea + areaOutsideContainer + orientationBias; } var strategy = function strategy(data) { var originalData = data; var iteratedData = data; var lastScore = Infinity; var currentTemperature = temperature; while (currentTemperature > 0) { var potentialReplacement = getPotentialState(originalData, iteratedData); var potentialScore = scorer(potentialReplacement); // Accept the state if it's a better state // or at random based off of the difference between scores. // This random % helps the algorithm break out of local minima var probablityOfChoosing = Math.exp((lastScore - potentialScore) / currentTemperature); if (potentialScore < lastScore || probablityOfChoosing > Math.random()) { iteratedData = potentialReplacement; lastScore = potentialScore; } currentTemperature -= cooling; } return iteratedData; }; strategy.temperature = function (x) { if (!arguments.length) { return temperature; } temperature = x; return strategy; }; strategy.cooling = function (x) { if (!arguments.length) { return cooling; } cooling = x; return strategy; }; strategy.bounds = function (x) { if (!arguments.length) { return bounds; } bounds = x; return strategy; }; return strategy; }) // iteratively remove the rectangle with the greatest area of collision var removeOverlaps = (function (adaptedStrategy) { adaptedStrategy = adaptedStrategy || function (x) { return x; }; var removeOverlaps = function removeOverlaps(layout) { layout = adaptedStrategy(layout); // returns a function that computes the area of overlap for rectangles // in the given layout array var scorerForLayout = function scorerForLayout(layout) { return function (_, i) { return -collisionArea(layout, i); }; }; var iterate = true; do { // apply the overlap calculation to visible rectangles var filteredLayout = layout.filter(function (d) { return !d.hidden; }); var min = minimum(filteredLayout, scorerForLayout(filteredLayout)); if (min[0] < 0) { // hide the rectangle with the greatest collision area min[1].hidden = true; } else { iterate = false; } } while (iterate); return layout; }; rebindAll$1(removeOverlaps, adaptedStrategy); return removeOverlaps; }) var boundingBox = (function () { var bounds = [0, 0]; var strategy = function strategy(data) { return data.map(function (d, i) { var tx = d.x; var ty = d.y; if (tx + d.width > bounds[0]) { tx -= d.width; } if (ty + d.height > bounds[1]) { ty -= d.height; } return { height: d.height, width: d.width, x: tx, y: ty }; }); }; strategy.bounds = function (value) { if (!arguments.length) { return bounds; } bounds = value; return strategy; }; return strategy; }) function label (strategy) { var adaptee = labelLayout(strategy); var xScale = d3.scale.identity(), yScale = d3.scale.identity(); var label = function label(selection) { // automatically set the bounds of the strategy based on the scale range if (strategy && strategy.bounds) { var xRange = range(xScale), yRange = range(yScale); strategy.bounds([Math.max(xRange[0], xRange[1]), Math.max(yRange[0], yRange[1])]); } selection.call(adaptee); }; rebindAll(label, adaptee); label.xScale = function (value) { if (!arguments.length) { return xScale; } xScale = value; return label; }; label.yScale = function (value) { if (!arguments.length) { return yScale; } yScale = value; return label; }; return label; } var layout = { label: label, textLabel: textLabel, strategy: { boundingBox: boundingBox, greedy: greedy, annealing: annealing, removeOverlaps: removeOverlaps } }; function xyBase () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), y0Value = d3.functor(0), x0Value = d3.functor(0), xValue = function xValue(d, i) { return d.x; }, yValue = function yValue(d, i) { return d.y; }; function base() {} base.x0 = function (d, i) { return xScale(x0Value(d, i)); }; base.y0 = function (d, i) { return yScale(y0Value(d, i)); }; base.x = base.x1 = function (d, i) { return xScale(xValue(d, i)); }; base.y = base.y1 = function (d, i) { return yScale(yValue(d, i)); }; base.defined = function (d, i) { return defined(x0Value, y0Value, xValue, yValue)(d, i); }; base.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return base; }; base.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return base; }; base.x0Value = function (x) { if (!arguments.length) { return x0Value; } x0Value = d3.functor(x); return base; }; base.y0Value = function (x) { if (!arguments.length) { return y0Value; } y0Value = d3.functor(x); return base; }; base.xValue = base.x1Value = function (x) { if (!arguments.length) { return xValue; } xValue = d3.functor(x); return base; }; base.yValue = base.y1Value = function (x) { if (!arguments.length) { return yValue; } yValue = d3.functor(x); return base; }; return base; } function _line () { var decorate = noop; var base = xyBase(); var lineData = d3.svg.line().defined(base.defined).x(base.x).y(base.y); var dataJoin$$ = dataJoin().selector('path.line').element('path').attr('class', 'line'); var line = function line(selection) { selection.each(function (data, index) { var path = dataJoin$$(this, [data]); path.attr('d', lineData); decorate(path, data, index); }); }; line.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return line; }; d3.rebind(line, base, 'xScale', 'xValue', 'yScale', 'yValue'); d3.rebind(line, dataJoin$$, 'key'); d3.rebind(line, lineData, 'interpolate', 'tension'); return line; } // A rectangle is an object with top, left, bottom and right properties. Component // margin or padding properties can accept an integer, which is converted to a rectangle where each // property equals the given value. Also, a margin / padding may have properties missing, in // which case they default to zero. // This function expand an integer to a rectangle and fills missing properties. function expandRect (margin) { var expandedRect = margin; if (typeof expandedRect === 'number') { expandedRect = { top: margin, bottom: margin, left: margin, right: margin }; } ['top', 'bottom', 'left', 'right'].forEach(function (direction) { if (!expandedRect[direction]) { expandedRect[direction] = 0; } }); return expandedRect; } function cartesian (xScale, yScale) { xScale = xScale || d3.scale.linear(); yScale = yScale || d3.scale.linear(); var margin = { bottom: 30, right: 30 }, yLabel = '', xLabel = '', xBaseline = null, yBaseline = null, chartLabel = '', plotArea = _line(), decorate = noop; // Each axis-series has a cross-scale which is defined as an identity // scale. If no baseline function is supplied, the axis is positioned // using the cross-scale range extents. If a baseline function is supplied // it is transformed via the respective scale. var xAxis = axis().orient('bottom').baseline(function () { if (xBaseline !== null) { return yScale(xBaseline.apply(this, arguments)); } else { var r = range(yScale); return xAxis.orient() === 'bottom' ? r[0] : r[1]; } }); var yAxis = axis().orient('right').baseline(function () { if (yBaseline !== null) { return xScale(yBaseline.apply(this, arguments)); } else { var r = range(xScale); return yAxis.orient() === 'left' ? r[0] : r[1]; } }); var containerDataJoin = dataJoin().selector('svg.cartesian-chart').element('svg').attr({ 'class': 'cartesian-chart', 'layout-style': 'flex: 1' }); var cartesian = function cartesian(selection) { selection.each(function (data, index) { var container = d3.select(this); var svg = containerDataJoin(container, [data]); svg.enter().call(function (s) { // container var plotContainer = s.append('g').classed('plot-area-container', true); plotContainer.append('rect').classed('background', true).layout({ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }); // axes var axesContainer = plotContainer.append('g').classed('axes-container', true); axesContainer.append('g').classed('x-axis', true).layout({ height: 0, width: 0 }); axesContainer.append('g').classed('y-axis', true).layout({ height: 0, width: 0 }); // plot area plotContainer.append('svg').classed('plot-area', true).layout({ position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }); // label containers plotContainer.append('g').classed('x-axis label-container', true).append('g').layout({ height: 0, width: 0 }).append('text').classed('label', true).attr('dy', '-0.5em'); plotContainer.append('g').classed('y-axis label-container', true).append('g').layout({ height: 0, width: 0 }).append('text').classed('label', true); plotContainer.append('g').classed('title label-container', true).append('g').layout({ height: 0, width: 0 }).append('text').classed('label', true); }); var expandedMargin = expandRect(margin); svg.select('.plot-area-container').layout({ position: 'absolute', top: expandedMargin.top, left: expandedMargin.left, bottom: expandedMargin.bottom, right: expandedMargin.right }); svg.select('.title').layout({ position: 'absolute', top: 0, alignItems: 'center', left: expandedMargin.left, right: expandedMargin.right }); var yAxisLayout = { position: 'absolute', top: expandedMargin.top, bottom: expandedMargin.bottom, alignItems: 'center', flexDirection: 'row' }; yAxisLayout[yAxis.orient()] = 0; svg.select('.y-axis.label-container').attr('class', 'y-axis label-container ' + yAxis.orient()).layout(yAxisLayout); var xAxisLayout = { position: 'absolute', left: expandedMargin.left, right: expandedMargin.right, alignItems: 'center' }; xAxisLayout[xAxis.orient()] = 0; svg.select('.x-axis.label-container').attr('class', 'x-axis label-container ' + xAxis.orient()).layout(xAxisLayout); // perform the flexbox / css layout container.layout(); // update the label text svg.select('.title .label').text(chartLabel); svg.select('.y-axis.label-container .label').text(yLabel).attr('transform', yAxis.orient() === 'right' ? 'rotate(90)' : 'rotate(-90)'); svg.select('.x-axis.label-container .label').text(xLabel); // set the axis ranges var plotAreaContainer = svg.select('.plot-area'); setRange(xScale, [0, plotAreaContainer.layout('width')]); setRange(yScale, [plotAreaContainer.layout('height'), 0]); // render the axes xAxis.xScale(xScale).yScale(d3.scale.identity()); yAxis.yScale(yScale).xScale(d3.scale.identity()); svg.select('.axes-container .x-axis').call(xAxis); svg.select('.axes-container .y-axis').call(yAxis); // render the plot area plotArea.xScale(xScale).yScale(yScale); plotAreaContainer.call(plotArea); decorate(svg, data, index); }); }; var scaleExclusions = exclude(/range\w*/, // the scale range is set via the component layout /tickFormat/ // use axis.tickFormat instead (only present on linear scales) ); rebindAll(cartesian, xScale, scaleExclusions, exclude('ticks'), prefix('x')); rebindAll(cartesian, yScale, scaleExclusions, exclude('ticks'), prefix('y')); // The scale ticks method is a stateless method that returns (roughly) the number of ticks // requested. This is subtley different from the axis ticks methods that simply stores the given arguments // for invocation of the scale method at some point in the future. // Here we expose the underling scale ticks method in case the user want to generate their own ticks. if (!isOrdinal(xScale)) { rebindAll(cartesian, xScale, includeMap({ 'ticks': 'xScaleTicks' })); } if (!isOrdinal(yScale)) { rebindAll(cartesian, yScale, includeMap({ 'ticks': 'yScaleTicks' })); } var axisExclusions = exclude('baseline', // the axis baseline is adapted so is not exposed directly 'xScale', 'yScale' // these are set by this components ); rebindAll(cartesian, xAxis, axisExclusions, prefix('x')); rebindAll(cartesian, yAxis, axisExclusions, prefix('y')); cartesian.xBaseline = function (x) { if (!arguments.length) { return xBaseline; } xBaseline = d3.functor(x); return cartesian; }; cartesian.yBaseline = function (x) { if (!arguments.length) { return yBaseline; } yBaseline = d3.functor(x); return cartesian; }; cartesian.chartLabel = function (x) { if (!arguments.length) { return chartLabel; } chartLabel = x; return cartesian; }; cartesian.plotArea = function (x) { if (!arguments.length) { return plotArea; } plotArea = x; return cartesian; }; cartesian.xLabel = function (x) { if (!arguments.length) { return xLabel; } xLabel = x; return cartesian; }; cartesian.margin = function (x) { if (!arguments.length) { return margin; } margin = x; return cartesian; }; cartesian.yLabel = function (x) { if (!arguments.length) { return yLabel; } yLabel = x; return cartesian; }; cartesian.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return cartesian; }; return cartesian; } function tooltip () { var split = 50, decorate = noop; var items = [['datum:', function (d) { return d.datum; }]]; var dataJoin$$ = dataJoin().selector('g.cell').element('g').attr('class', 'cell tooltip'); var tooltip = function tooltip(selection) { selection.each(function (data, index) { var container = d3.select(this); var legendData = items.map(function (item, i) { return { datum: data, label: d3.functor(item[0]), value: d3.functor(item[1]) }; }); var g = dataJoin$$(container, legendData); g.enter().layout({ 'flex': 1, 'flexDirection': 'row' }); g.enter().append('text').attr('class', 'label').attr('dy', '0.71em').layout('flex', split); g.enter().append('text').attr('class', 'value').attr('dy', '0.71em').layout('flex', 100 - split); g.select('.label').text(function (d, i) { return d.label.call(this, d.datum, i); }); g.select('.value').text(function (d, i) { return d.value.call(this, d.datum, i); }); decorate(g, data, index); container.layout(); }); }; tooltip.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return tooltip; }; tooltip.split = function (x) { if (!arguments.length) { return split; } split = x; return tooltip; }; tooltip.items = function (x) { if (!arguments.length) { return items; } items = x; return tooltip; }; return tooltip; } function identity$1 () { var identity$$ = {}; identity$$.distance = function (startDate, endDate) { return endDate.getTime() - startDate.getTime(); }; identity$$.offset = function (startDate, ms) { return new Date(startDate.getTime() + ms); }; identity$$.clampUp = identity; identity$$.clampDown = identity; identity$$.copy = function () { return identity$$; }; return identity$$; } // obtains the ticks from the given scale, transforming the result to ensure // it does not include any discontinuities function tickTransformer(ticks, discontinuityProvider, domain) { var clampedTicks = ticks.map(function (tick, index) { if (index < ticks.length - 1) { return discontinuityProvider.clampUp(tick); } else { var clampedTick = discontinuityProvider.clampUp(tick); return clampedTick < domain[1] ? clampedTick : discontinuityProvider.clampDown(tick); } }); var uniqueTicks = clampedTicks.reduce(function (arr, tick) { if (arr.filter(function (f) { return f.getTime() === tick.getTime(); }).length === 0) { arr.push(tick); } return arr; }, []); return uniqueTicks; } /** * The `fc.scale.dateTime` scale renders a discontinuous date time scale, i.e. a time scale that incorporates gaps. * As an example, you can use this scale to render a chart where the weekends are skipped. * * @type {object} * @memberof fc.scale * @class fc.scale.dateTime */ function dateTimeScale(adaptedScale, discontinuityProvider) { if (!arguments.length) { adaptedScale = d3.time.scale(); discontinuityProvider = identity$1(); } function scale(date) { var domain = adaptedScale.domain(); var range = adaptedScale.range(); // The discontinuityProvider is responsible for determine the distance between two points // along a scale that has discontinuities (i.e. sections that have been removed). // the scale for the given point 'x' is calculated as the ratio of the discontinuous distance // over the domain of this axis, versus the discontinuous distance to 'x' var totalDomainDistance = discontinuityProvider.distance(domain[0], domain[1]); var distanceToX = discontinuityProvider.distance(domain[0], date); var ratioToX = distanceToX / totalDomainDistance; var scaledByRange = ratioToX * (range[1] - range[0]) + range[0]; return scaledByRange; } scale.invert = function (x) { var domain = adaptedScale.domain(); var range = adaptedScale.range(); var ratioToX = (x - range[0]) / (range[1] - range[0]); var totalDomainDistance = discontinuityProvider.distance(domain[0], domain[1]); var distanceToX = ratioToX * totalDomainDistance; return discontinuityProvider.offset(domain[0], distanceToX); }; scale.domain = function (x) { if (!arguments.length) { return adaptedScale.domain(); } // clamp the upper and lower domain values to ensure they // do not fall within a discontinuity var domainLower = discontinuityProvider.clampUp(x[0]); var domainUpper = discontinuityProvider.clampDown(x[1]); adaptedScale.domain([domainLower, domainUpper]); return scale; }; scale.nice = function () { adaptedScale.nice(); var domain = adaptedScale.domain(); var domainLower = discontinuityProvider.clampUp(domain[0]); var domainUpper = discontinuityProvider.clampDown(domain[1]); adaptedScale.domain([domainLower, domainUpper]); return scale; }; scale.ticks = function () { var ticks = adaptedScale.ticks.apply(this, arguments); return tickTransformer(ticks, discontinuityProvider, scale.domain()); }; scale.copy = function () { return dateTimeScale(adaptedScale.copy(), discontinuityProvider.copy()); }; scale.discontinuityProvider = function (x) { if (!arguments.length) { return discontinuityProvider; } discontinuityProvider = x; return scale; }; return d3.rebind(scale, adaptedScale, 'range', 'rangeRound', 'interpolate', 'clamp', 'tickFormat'); } function exportedScale() { return dateTimeScale(); } exportedScale.tickTransformer = tickTransformer; // returns the width and height of the given element minus the padding. function innerDimensions (element) { var style = element.ownerDocument.defaultView.getComputedStyle(element); return { width: parseFloat(style.width) - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight), height: parseFloat(style.height) - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom) }; } // The multi series does some data-join gymnastics to ensure we don't - // * Create unnecessary intermediate DOM nodes // * Manipulate the data specified by the user // This is achieved by data joining the series array to the container but // overriding where the series value is stored on the node (__series__) and // forcing the node datum (__data__) to be the user supplied data (via mapping). function _multi () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), series = [], mapping = context, key = index, decorate = noop; var dataJoin$$ = dataJoin().selector('g.multi').children(true).attr('class', 'multi').element('g').key(function (d, i) { // This function is invoked twice, the first pass is to pull the key // value from the DOM nodes and the second pass is to pull the key // value from the data values. // As we store the series as an additional property on the node, we // look for that first and if we find it assume we're being called // during the first pass. Otherwise we assume it's the second pass // and pull the series from the data value. var dataSeries = this.__series__ || d; return key.call(this, dataSeries, i); }); var multi = function multi(selection) { selection.each(function (data, i) { var g = dataJoin$$(this, series); g.each(function (dataSeries, seriesIndex) { // We must always assign the series to the node, as the order // may have changed. N.B. in such a case the output is most // likely garbage (containers should not be re-used) but by // doing this we at least make it debuggable garbage :) this.__series__ = dataSeries; (dataSeries.xScale || dataSeries.x).call(dataSeries, xScale); (dataSeries.yScale || dataSeries.y).call(dataSeries, yScale); d3.select(this).datum(mapping.call(data, dataSeries, seriesIndex)).call(dataSeries); }); // order is not available on a transition selection d3.selection.prototype.order.call(g); decorate(g, data, i); }); }; multi.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return multi; }; multi.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return multi; }; multi.series = function (x) { if (!arguments.length) { return series; } series = x; return multi; }; multi.mapping = function (x) { if (!arguments.length) { return mapping; } mapping = x; return multi; }; multi.key = function (x) { if (!arguments.length) { return key; } key = x; return multi; }; multi.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return multi; }; return multi; } function point () { var decorate = noop, symbol = d3.svg.symbol(); var base = xyBase(); var dataJoin$$ = dataJoin().selector('g.point').element('g').attr('class', 'point'); var containerTransform = function containerTransform(d, i) { return 'translate(' + base.x(d, i) + ', ' + base.y(d, i) + ')'; }; var point = function point(selection) { selection.each(function (data, index) { var filteredData = data.filter(base.defined); var g = dataJoin$$(this, filteredData); g.enter().attr('transform', containerTransform).append('path'); g.attr('transform', containerTransform).select('path').attr('d', symbol); decorate(g, data, index); }); }; point.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return point; }; d3.rebind(point, base, 'xScale', 'xValue', 'yScale', 'yValue'); d3.rebind(point, dataJoin$$, 'key'); d3.rebind(point, symbol, 'size', 'type'); return point; } function sparkline () { // creates an array with four elements, representing the high, low, open and close // values of the given array function highLowOpenClose(data) { var xValueAccessor = sparkline.xValue(), yValueAccessor = sparkline.yValue(); var high = d3.max(data, yValueAccessor); var low = d3.min(data, yValueAccessor); function elementWithYValue(value) { return data.filter(function (d) { return yValueAccessor(d) === value; })[0]; } return [{ x: xValueAccessor(data[0]), y: yValueAccessor(data[0]) }, { x: xValueAccessor(elementWithYValue(high)), y: high }, { x: xValueAccessor(elementWithYValue(low)), y: low }, { x: xValueAccessor(data[data.length - 1]), y: yValueAccessor(data[data.length - 1]) }]; } var xScale = exportedScale(); var yScale = d3.scale.linear(); var radius = 2; var line = _line(); // configure the point series to render the data from the // highLowOpenClose function var point$$ = point().xValue(function (d) { return d.x; }).yValue(function (d) { return d.y; }).decorate(function (sel) { sel.attr('class', function (d, i) { switch (i) { case 0: return 'open'; case 1: return 'high'; case 2: return 'low'; case 3: return 'close'; } }); }); var multi = _multi().series([line, point$$]).mapping(function (series) { switch (series) { case point$$: return highLowOpenClose(this); default: return this; } }); var sparkline = function sparkline(selection) { point$$.size(radius * radius * Math.PI); selection.each(function (data) { var container = d3.select(this); var dimensions = innerDimensions(this); var margin = radius; xScale.range([margin, dimensions.width - margin]); yScale.range([dimensions.height - margin, margin]); multi.xScale(xScale).yScale(yScale); container.call(multi); }); }; rebindAll(sparkline, xScale, include('discontinuityProvider', 'domain'), prefix('x')); rebindAll(sparkline, yScale, include('domain'), prefix('y')); rebindAll(sparkline, line, include('xValue', 'yValue')); sparkline.xScale = function () { return xScale; }; sparkline.yScale = function () { return yScale; }; sparkline.radius = function (x) { if (!arguments.length) { return radius; } radius = x; return sparkline; }; return sparkline; } function smallMultiples (xScale, yScale) { xScale = xScale || d3.scale.linear(); yScale = yScale || d3.scale.linear(); var padding = 10, columns = 9, decorate = noop, plotArea = _line(), margin = { bottom: 30, right: 30 }, values = function values(d) { return d.values; }, key = function key(d) { return d.key; }, xDomain, yDomain; var xAxis = axis$1().ticks(2); var yAxis = axis$1().orient('right').ticks(3); function classedDataJoin(clazz) { return dataJoin().selector('g.' + clazz).element('g').attr('class', clazz); } var dataJoin$$ = classedDataJoin('multiple'), xAxisDataJoin = classedDataJoin('x-axis'), yAxisDataJoin = classedDataJoin('y-axis'); function cellForIndex(index) { return [index % columns, Math.floor(index / columns)]; } function cellsAreEqual(a, b) { return a[0] === b[0] && a[1] === b[1]; } function domainsForCell(cell, data) { var dataForCell = data.filter(function (datum, index) { return cellsAreEqual(cellForIndex(index), cell); }); return [xDomain(dataForCell), yDomain(dataForCell)]; } var multiples = function multiples(selection) { selection.each(function (data, index) { var container = d3.select(this); var expandedMargin = expandRect(margin); expandedMargin.position = 'absolute'; var svg = container.selectAll('svg').data([data]); svg.enter().append('svg').layout('flex', 1).append('g').attr('class', 'multiples-chart'); var plotAreaContainer = svg.select('g').layout(expandedMargin); container.layout(); var rows = Math.ceil(data.length / columns); var multipleWidth = plotAreaContainer.layout('width') / columns - padding; var multipleHeight = plotAreaContainer.layout('height') / rows - padding; function translationForMultiple(row, column) { return { xOffset: (multipleWidth + padding) * row, yOffset: (multipleHeight + padding) * column }; } setRange(xScale, [0, multipleWidth]); setRange(yScale, [multipleHeight, 0]); // create a container for each multiple chart var multipleContainer = dataJoin$$(plotAreaContainer, data); multipleContainer.attr('transform', function (d, i) { var translation = translationForMultiple(i % columns, Math.floor(i / columns)); return 'translate(' + translation.xOffset + ',' + translation.yOffset + ')'; }); // within each, add an inner 'g' and background rect var inner = multipleContainer.enter().append('g'); inner.append('rect').attr('class', 'background'); inner.append('g').attr('transform', 'translate(' + multipleWidth / 2 + ', 0)').append('text').attr('class', 'label').text(key); multipleContainer.select('g').each(function (d, i) { var cell = cellForIndex(i); var domains = domainsForCell(cell, data); xScale.domain(domains[0]); yScale.domain(domains[1]); plotArea.xScale(xScale).yScale(yScale); d3.select(this).datum(values).call(plotArea); }); multipleContainer.select('rect').attr({ width: multipleWidth, height: multipleHeight }); decorate(multipleContainer, data, index); var xAxisContainer = xAxisDataJoin(plotAreaContainer, d3.range(columns)); xAxisContainer.attr('transform', function (d, i) { var row = xAxis.orient() === 'bottom' ? rows : 0; var offset = xAxis.orient() === 'bottom' ? 0 : -padding; var translation = translationForMultiple(i, row); return 'translate(' + translation.xOffset + ',' + (translation.yOffset + offset) + ')'; }).each(function (d, i) { var domains = domainsForCell(cellForIndex(i), data); xScale.domain(domains[0]); xAxis.scale(xScale); d3.select(this).call(xAxis); }); var yAxisContainer = yAxisDataJoin(plotAreaContainer, d3.range(rows)); yAxisContainer.attr('transform', function (d, i) { var column = yAxis.orient() === 'left' ? 0 : columns; var offset = yAxis.orient() === 'left' ? -padding : 0; var translation = translationForMultiple(column, i); return 'translate(' + (translation.xOffset + offset) + ',' + translation.yOffset + ')'; }).each(function (d, i) { var domains = domainsForCell(cellForIndex(i), data); yScale.domain(domains[1]); yAxis.scale(yScale); d3.select(this).call(yAxis); }); }); }; var scaleExclusions = exclude(/range\w*/, // the scale range is set via the component layout /tickFormat/, // use axis.tickFormat instead (only present on linear scales) /domain/ // the domain has been adapted to allow it to be expressed as a function ); rebindAll(multiples, xScale, scaleExclusions, prefix('x')); rebindAll(multiples, yScale, scaleExclusions, prefix('y')); rebindAll(multiples, xAxis, prefix('x')); rebindAll(multiples, yAxis, prefix('y')); multiples.columns = function (x) { if (!arguments.length) { return columns; } columns = x; return multiples; }; multiples.margin = function (x) { if (!arguments.length) { return margin; } margin = x; return multiples; }; multiples.padding = function (x) { if (!arguments.length) { return padding; } padding = x; return multiples; }; multiples.plotArea = function (x) { if (!arguments.length) { return plotArea; } plotArea = x; return multiples; }; multiples.values = function (x) { if (!arguments.length) { return values; } values = x; return multiples; }; multiples.key = function (x) { if (!arguments.length) { return key; } key = x; return multiples; }; multiples.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return multiples; }; multiples.xDomain = function (x) { if (!arguments.length) { return xDomain; } xDomain = d3.functor(x); return multiples; }; multiples.yDomain = function (x) { if (!arguments.length) { return yDomain; } yDomain = d3.functor(x); return multiples; }; return multiples; } var chart = { cartesian: cartesian, sparkline: sparkline, tooltip: tooltip, smallMultiples: smallMultiples }; var prefix$2 = "$"; function Map() {} Map.prototype = map$1.prototype = { constructor: Map, has: function has(key) { return prefix$2 + key in this; }, get: function get(key) { return this[prefix$2 + key]; }, set: function set(key, value) { this[prefix$2 + key] = value; return this; }, remove: function remove(key) { var property = prefix$2 + key; return property in this && delete this[property]; }, clear: function clear() { for (var property in this) { if (property[0] === prefix$2) delete this[property]; } }, keys: function keys() { var keys = []; for (var property in this) { if (property[0] === prefix$2) keys.push(property.slice(1)); }return keys; }, values: function values() { var values = []; for (var property in this) { if (property[0] === prefix$2) values.push(this[property]); }return values; }, entries: function entries() { var entries = []; for (var property in this) { if (property[0] === prefix$2) entries.push({ key: property.slice(1), value: this[property] }); }return entries; }, size: function size() { var size = 0; for (var property in this) { if (property[0] === prefix$2) ++size; }return size; }, empty: function empty() { for (var property in this) { if (property[0] === prefix$2) return false; }return true; }, each: function each(f) { for (var property in this) { if (property[0] === prefix$2) f(this[property], property.slice(1), this); } } }; function map$1(object, f) { var map = new Map(); // Copy constructor. if (object instanceof Map) object.each(function (value, key) { map.set(key, value); }); // Index array by numeric index or specified key function. else if (Array.isArray(object)) { var i = -1, n = object.length, o; if (f == null) while (++i < n) { map.set(i, object[i]); } else while (++i < n) { map.set(f(o = object[i], i, object), o); } } // Convert object to map. else if (object) for (var key in object) { map.set(key, object[key]); }return map; } var proto = map$1.prototype; var noop$1 = { value: function value() {} }; function dispatch() { for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) { if (!(t = arguments[i] + "") || t in _) throw new Error("illegal type: " + t); _[t] = []; } return new Dispatch(_); } function Dispatch(_) { this._ = _; } function parseTypenames(typenames, types) { return typenames.trim().split(/^|\s+/).map(function (t) { var name = "", i = t.indexOf("."); if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i); if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t); return { type: t, name: name }; }); } Dispatch.prototype = dispatch.prototype = { constructor: Dispatch, on: function on(typename, callback) { var _ = this._, T = parseTypenames(typename + "", _), t, i = -1, n = T.length; // If no callback was specified, return the callback of the given type and name. if (arguments.length < 2) { while (++i < n) { if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t; }return; } // If a type was specified, set the callback for the given type and name. // Otherwise, if a null callback was specified, remove callbacks of the given name. if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback); while (++i < n) { if (t = (typename = T[i]).type) _[t] = set$1(_[t], typename.name, callback);else if (callback == null) for (t in _) { _[t] = set$1(_[t], typename.name, null); } } return this; }, copy: function copy() { var copy = {}, _ = this._; for (var t in _) { copy[t] = _[t].slice(); }return new Dispatch(copy); }, call: function call(type, that) { if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) { args[i] = arguments[i + 2]; }if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type); for (t = this._[type], i = 0, n = t.length; i < n; ++i) { t[i].value.apply(that, args); } }, apply: function apply(type, that, args) { if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type); for (var t = this._[type], i = 0, n = t.length; i < n; ++i) { t[i].value.apply(that, args); } } }; function get(type, name) { for (var i = 0, n = type.length, c; i < n; ++i) { if ((c = type[i]).name === name) { return c.value; } } } function set$1(type, name, callback) { for (var i = 0, n = type.length; i < n; ++i) { if (type[i].name === name) { type[i] = noop$1, type = type.slice(0, i).concat(type.slice(i + 1)); break; } } if (callback != null) type.push({ name: name, value: callback }); return type; } function request (url, callback) { var request, event = dispatch("beforesend", "progress", "load", "error"), _mimeType, headers = map$1(), xhr = new XMLHttpRequest(), _user = null, _password = null, _response, _responseType, _timeout = 0; // If IE does not support CORS, use XDomainRequest. if (typeof XDomainRequest !== "undefined" && !("withCredentials" in xhr) && /^(http(s)?:)?\/\//.test(url)) xhr = new XDomainRequest(); "onload" in xhr ? xhr.onload = xhr.onerror = xhr.ontimeout = respond : xhr.onreadystatechange = function (o) { xhr.readyState > 3 && respond(o); }; function respond(o) { var status = xhr.status, result; if (!status && hasResponse(xhr) || status >= 200 && status < 300 || status === 304) { if (_response) { try { result = _response.call(request, xhr); } catch (e) { event.call("error", request, e); return; } } else { result = xhr; } event.call("load", request, result); } else { event.call("error", request, o); } } xhr.onprogress = function (e) { event.call("progress", request, e); }; request = { header: function header(name, value) { name = (name + "").toLowerCase(); if (arguments.length < 2) return headers.get(name); if (value == null) headers.remove(name);else headers.set(name, value + ""); return request; }, // If mimeType is non-null and no Accept header is set, a default is used. mimeType: function mimeType(value) { if (!arguments.length) return _mimeType; _mimeType = value == null ? null : value + ""; return request; }, // Specifies what type the response value should take; // for instance, arraybuffer, blob, document, or text. responseType: function responseType(value) { if (!arguments.length) return _responseType; _responseType = value; return request; }, timeout: function timeout(value) { if (!arguments.length) return _timeout; _timeout = +value; return request; }, user: function user(value) { return arguments.length < 1 ? _user : (_user = value == null ? null : value + "", request); }, password: function password(value) { return arguments.length < 1 ? _password : (_password = value == null ? null : value + "", request); }, // Specify how to convert the response content to a specific type; // changes the callback value on "load" events. response: function response(value) { _response = value; return request; }, // Alias for send("GET", …). get: function get(data, callback) { return request.send("GET", data, callback); }, // Alias for send("POST", …). post: function post(data, callback) { return request.send("POST", data, callback); }, // If callback is non-null, it will be used for error and load events. send: function send(method, data, callback) { if (!callback && typeof data === "function") callback = data, data = null; if (callback && callback.length === 1) callback = fixCallback(callback); xhr.open(method, url, true, _user, _password); if (_mimeType != null && !headers.has("accept")) headers.set("accept", _mimeType + ",*/*"); if (xhr.setRequestHeader) headers.each(function (value, name) { xhr.setRequestHeader(name, value); }); if (_mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(_mimeType); if (_responseType != null) xhr.responseType = _responseType; if (_timeout > 0) xhr.timeout = _timeout; if (callback) request.on("error", callback).on("load", function (xhr) { callback(null, xhr); }); event.call("beforesend", request, xhr); xhr.send(data == null ? null : data); return request; }, abort: function abort() { xhr.abort(); return request; }, on: function on() { var value = event.on.apply(event, arguments); return value === event ? request : value; } }; return callback ? request.get(callback) : request; } function fixCallback(callback) { return function (error, xhr) { callback(error == null ? xhr : null); }; } function hasResponse(xhr) { var type = xhr.responseType; return type && type !== "text" ? xhr.response // null on error : xhr.responseText; // "" on error } function type (defaultMimeType, response) { return function (url, callback) { var r = request(url).mimeType(defaultMimeType).response(response); return callback ? r.get(callback) : r; }; } var json = type("application/json", function (xhr) { return JSON.parse(xhr.responseText); }); function objectConverter(columns) { return new Function("d", "return {" + columns.map(function (name, i) { return JSON.stringify(name) + ": d[" + i + "]"; }).join(",") + "}"); } function customConverter(columns, f) { var object = objectConverter(columns); return function (row, i) { return f(object(row), i, columns); }; } // Compute unique columns in order of discovery. function inferColumns(rows) { var columnSet = Object.create(null), columns = []; rows.forEach(function (row) { for (var column in row) { if (!(column in columnSet)) { columns.push(columnSet[column] = column); } } }); return columns; } function dsv (delimiter) { var reFormat = new RegExp("[\"" + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); function parse(text, f) { var convert, columns, rows = parseRows(text, function (row, i) { if (convert) return convert(row, i - 1); columns = row, convert = f ? customConverter(row, f) : objectConverter(row); }); rows.columns = columns; return rows; } function parseRows(text, f) { var EOL = {}, // sentinel value for end-of-line EOF = {}, // sentinel value for end-of-file rows = [], // output rows N = text.length, I = 0, // current character index n = 0, // the current line number t, // the current token eol; // is the current token followed by EOL? function token() { if (I >= N) return EOF; // special case: end of file if (eol) return eol = false, EOL; // special case: end of line // special case: quotes var j = I, c; if (text.charCodeAt(j) === 34) { var i = j; while (i++ < N) { if (text.charCodeAt(i) === 34) { if (text.charCodeAt(i + 1) !== 34) break; ++i; } } I = i + 2; c = text.charCodeAt(i + 1); if (c === 13) { eol = true; if (text.charCodeAt(i + 2) === 10) ++I; } else if (c === 10) { eol = true; } return text.slice(j + 1, i).replace(/""/g, "\""); } // common case: find next delimiter or newline while (I < N) { var k = 1; c = text.charCodeAt(I++); if (c === 10) eol = true; // \n else if (c === 13) { eol = true;if (text.charCodeAt(I) === 10) ++I, ++k; } // \r|\r\n else if (c !== delimiterCode) continue; return text.slice(j, I - k); } // special case: last token before EOF return text.slice(j); } while ((t = token()) !== EOF) { var a = []; while (t !== EOL && t !== EOF) { a.push(t); t = token(); } if (f && (a = f(a, n++)) == null) continue; rows.push(a); } return rows; } function format(rows, columns) { if (columns == null) columns = inferColumns(rows); return [columns.map(formatValue).join(delimiter)].concat(rows.map(function (row) { return columns.map(function (column) { return formatValue(row[column]); }).join(delimiter); })).join("\n"); } function formatRows(rows) { return rows.map(formatRow).join("\n"); } function formatRow(row) { return row.map(formatValue).join(delimiter); } function formatValue(text) { return text == null ? "" : reFormat.test(text += "") ? "\"" + text.replace(/\"/g, "\"\"") + "\"" : text; } return { parse: parse, parseRows: parseRows, format: format, formatRows: formatRows }; } var csv$1 = dsv(","); var tsv = dsv("\t"); // https://docs.exchange.coinbase.com/#market-data function coinbase () { var product = 'BTC-USD'; var start = null; var end = null; var granularity = null; var coinbase = function coinbase(cb) { var params = []; if (start != null) { params.push('start=' + start.toISOString()); } if (end != null) { params.push('end=' + end.toISOString()); } if (granularity != null) { params.push('granularity=' + granularity); } var url = 'https://api.exchange.coinbase.com/products/' + product + '/candles?' + params.join('&'); json(url, function (error, data) { if (error) { cb(error); return; } data = data.map(function (d) { return { date: new Date(d[0] * 1000), open: d[3], high: d[2], low: d[1], close: d[4], volume: d[5] }; }); cb(error, data); }); }; coinbase.product = function (x) { if (!arguments.length) { return product; } product = x; return coinbase; }; coinbase.start = function (x) { if (!arguments.length) { return start; } start = x; return coinbase; }; coinbase.end = function (x) { if (!arguments.length) { return end; } end = x; return coinbase; }; coinbase.granularity = function (x) { if (!arguments.length) { return granularity; } granularity = x; return coinbase; }; return coinbase; } // https://www.quandl.com/docs/api#datasets function quandl () { function defaultColumnNameMap(colName) { return colName[0].toLowerCase() + colName.substr(1); } var database = 'YAHOO'; var dataset = 'GOOG'; var apiKey = null; var start = null; var end = null; var rows = null; var descending = false; var collapse = null; var columnNameMap = defaultColumnNameMap; var quandl = function quandl(cb) { var params = []; if (apiKey != null) { params.push('api_key=' + apiKey); } if (start != null) { params.push('start_date=' + start.toISOString().substring(0, 10)); } if (end != null) { params.push('end_date=' + end.toISOString().substring(0, 10)); } if (rows != null) { params.push('rows=' + rows); } if (!descending) { params.push('order=asc'); } if (collapse != null) { params.push('collapse=' + collapse); } var url = 'https://www.quandl.com/api/v3/datasets/' + database + '/' + dataset + '/data.json?' + params.join('&'); json(url, function (error, data) { if (error) { cb(error); return; } var datasetData = data.dataset_data; var nameMapping = columnNameMap || function (n) { return n; }; var colNames = datasetData.column_names.map(function (n, i) { return [i, nameMapping(n)]; }).filter(function (v) { return v[1]; }); var mappedData = datasetData.data.map(function (d) { var output = {}; colNames.forEach(function (v) { output[v[1]] = v[0] === 0 ? new Date(d[v[0]]) : d[v[0]]; }); return output; }); cb(error, mappedData); }); }; // Unique Database Code (e.g. WIKI) quandl.database = function (x) { if (!arguments.length) { return database; } database = x; return quandl; }; // Unique Dataset Code (e.g. AAPL) quandl.dataset = function (x) { if (!arguments.length) { return dataset; } dataset = x; return quandl; }; // Set To Use API Key In Request (needed for premium set or high frequency requests) quandl.apiKey = function (x) { if (!arguments.length) { return apiKey; } apiKey = x; return quandl; }; // Start Date of Data Series quandl.start = function (x) { if (!arguments.length) { return start; } start = x; return quandl; }; // End Date of Data Series quandl.end = function (x) { if (!arguments.length) { return end; } end = x; return quandl; }; // Limit Number of Rows quandl.rows = function (x) { if (!arguments.length) { return rows; } rows = x; return quandl; }; // Return Results In Descending Order (true) or Ascending (false) quandl.descending = function (x) { if (!arguments.length) { return descending; } descending = x; return quandl; }; // Periodicity of Data (daily | weekly | monthly | quarterly | annual) quandl.collapse = function (x) { if (!arguments.length) { return collapse; } collapse = x; return quandl; }; // Function Used to Normalise the Quandl Column Name To Field Name, Return Null To Skip Field quandl.columnNameMap = function (x) { if (!arguments.length) { return columnNameMap; } columnNameMap = x; return quandl; }; // Expose default column name map quandl.defaultColumnNameMap = defaultColumnNameMap; return quandl; } var feed = Object.freeze({ coinbase: coinbase, quandl: quandl }); function _walk () { var period = 1, steps = 20, mu = 0.1, sigma = 0.1; var walk = function walk(value) { var randomNormal = d3.random.normal(), timeStep = period / steps, walkData = []; for (var i = 0; i < steps + 1; i++) { walkData.push(value); var increment = randomNormal() * Math.sqrt(timeStep) * sigma + (mu - sigma * sigma / 2) * timeStep; value = value * Math.exp(increment); } return walkData; }; walk.period = function (x) { if (!arguments.length) { return period; } period = x; return walk; }; walk.steps = function (x) { if (!arguments.length) { return steps; } steps = x; return walk; }; walk.mu = function (x) { if (!arguments.length) { return mu; } mu = x; return walk; }; walk.sigma = function (x) { if (!arguments.length) { return sigma; } sigma = x; return walk; }; return walk; } function financial () { var startDate = new Date(); var startPrice = 100; var interval = d3.time.day; var intervalStep = 1; var unitInterval = d3.time.year; var unitIntervalStep = 1; var filter = null; var volume = function volume() { var randomNormal = d3.random.normal(1, 0.1); return Math.ceil(randomNormal() * 1000); }; var walk = _walk(); function getOffsetPeriod(date) { var unitMilliseconds = unitInterval.offset(date, unitIntervalStep) - date; return (interval.offset(date, intervalStep) - date) / unitMilliseconds; } function calculateOHLC(start, price) { var period = getOffsetPeriod(start); var prices = walk.period(period)(price); var ohlc = { date: start, open: prices[0], high: Math.max.apply(Math, prices), low: Math.min.apply(Math, prices), close: prices[walk.steps()] }; ohlc.volume = volume(ohlc); return ohlc; } function getNextDatum(ohlc) { var date, price; do { date = ohlc ? interval.offset(ohlc.date, intervalStep) : new Date(startDate.getTime()); price = ohlc ? ohlc.close : startPrice; ohlc = calculateOHLC(date, price); } while (filter && !filter(ohlc)); return ohlc; } var financial = function financial(numPoints) { var stream = makeStream(); return stream.take(numPoints); }; financial.stream = makeStream; function makeStream() { var latest; var stream = {}; stream.next = function () { var ohlc = getNextDatum(latest); latest = ohlc; return ohlc; }; stream.take = function (numPoints) { return this.until(function (d, i) { return !numPoints || numPoints < 0 || i === numPoints; }); }; stream.until = function (comparison) { var data = []; var index = 0; var ohlc = getNextDatum(latest); while (comparison && !comparison(ohlc, index)) { data.push(ohlc); latest = ohlc; ohlc = getNextDatum(latest); index += 1; } return data; }; return stream; } financial.startDate = function (x) { if (!arguments.length) { return startDate; } startDate = x; return financial; }; financial.startPrice = function (x) { if (!arguments.length) { return startPrice; } startPrice = x; return financial; }; financial.interval = function (x) { if (!arguments.length) { return interval; } interval = x; return financial; }; financial.intervalStep = function (x) { if (!arguments.length) { return intervalStep; } intervalStep = x; return financial; }; financial.unitInterval = function (x) { if (!arguments.length) { return unitInterval; } unitInterval = x; return financial; }; financial.unitIntervalStep = function (x) { if (!arguments.length) { return unitIntervalStep; } unitIntervalStep = x; return financial; }; financial.filter = function (x) { if (!arguments.length) { return filter; } filter = x; return financial; }; financial.volume = function (x) { if (!arguments.length) { return volume; } volume = d3.functor(x); return financial; }; d3.rebind(financial, walk, 'steps', 'mu', 'sigma'); return financial; } function skipWeekends() { return function (datum) { var day = datum.date.getDay(); return !(day === 0 || day === 6); }; } var random = { filter: { skipWeekends: skipWeekends }, financial: financial, walk: _walk }; function ascending (a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; } function bisector (compare) { if (compare.length === 1) compare = ascendingComparator(compare); return { left: function left(a, x, lo, hi) { if (lo == null) lo = 0; if (hi == null) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) < 0) lo = mid + 1;else hi = mid; } return lo; }, right: function right(a, x, lo, hi) { if (lo == null) lo = 0; if (hi == null) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) > 0) hi = mid;else lo = mid + 1; } return lo; } }; } function ascendingComparator(f) { return function (d, x) { return ascending(f(d), x); }; } var ascendingBisect = bisector(ascending); function number (x) { return x === null ? NaN : +x; } function extent (array, f) { var i = -1, n = array.length, a, b, c; if (f == null) { while (++i < n) { if ((b = array[i]) != null && b >= b) { a = c = b;break; } }while (++i < n) { if ((b = array[i]) != null) { if (a > b) a = b; if (c < b) c = b; } } } else { while (++i < n) { if ((b = f(array[i], i, array)) != null && b >= b) { a = c = b;break; } }while (++i < n) { if ((b = f(array[i], i, array)) != null) { if (a > b) a = b; if (c < b) c = b; } } } return [a, c]; } function range$1 (start, stop, step) { start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step; var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0, range = new Array(n); while (++i < n) { range[i] = start + i * step; } return range; } function max (array, f) { var i = -1, n = array.length, a, b; if (f == null) { while (++i < n) { if ((b = array[i]) != null && b >= b) { a = b;break; } }while (++i < n) { if ((b = array[i]) != null && b > a) a = b; } } else { while (++i < n) { if ((b = f(array[i], i, array)) != null && b >= b) { a = b;break; } }while (++i < n) { if ((b = f(array[i], i, array)) != null && b > a) a = b; } } return a; } function mean (array, f) { var s = 0, n = array.length, a, i = -1, j = n; if (f == null) { while (++i < n) { if (!isNaN(a = number(array[i]))) s += a;else --j; } } else { while (++i < n) { if (!isNaN(a = number(f(array[i], i, array)))) s += a;else --j; } } if (j) return s / j; } function bucket () { var bucketSize = 10; var bucket = function bucket(data) { return range$1(0, Math.ceil(data.length / bucketSize)).map(function (i) { return data.slice(i * bucketSize, (i + 1) * bucketSize); }); }; bucket.bucketSize = function (x) { if (!arguments.length) { return bucketSize; } bucketSize = x; return bucket; }; return bucket; } function largestTriangleOneBucket () { var dataBucketer = bucket(); var x = function x(d) { return d; }; var y = function y(d) { return d; }; var largestTriangleOneBucket = function largestTriangleOneBucket(data) { if (dataBucketer.bucketSize() >= data.length) { return data; } var pointAreas = calculateAreaOfPoints(data); var pointAreaBuckets = dataBucketer(pointAreas); var buckets = dataBucketer(data.slice(1, data.length - 1)); var subsampledData = buckets.map(function (thisBucket, i) { var pointAreaBucket = pointAreaBuckets[i]; var maxArea = max(pointAreaBucket); var currentMaxIndex = pointAreaBucket.indexOf(maxArea); return thisBucket[currentMaxIndex]; }); // First and last data points are their own buckets. return [].concat(data[0], subsampledData, data[data.length - 1]); }; function calculateAreaOfPoints(data) { var xyData = data.map(function (point) { return [x(point), y(point)]; }); var pointAreas = range$1(1, xyData.length - 1).map(function (i) { var lastPoint = xyData[i - 1]; var thisPoint = xyData[i]; var nextPoint = xyData[i + 1]; var base = (lastPoint[0] - nextPoint[0]) * (thisPoint[1] - lastPoint[1]); var height = (lastPoint[0] - thisPoint[0]) * (nextPoint[1] - lastPoint[1]); return Math.abs(0.5 * base * height); }); return pointAreas; } rebind(largestTriangleOneBucket, dataBucketer, 'bucketSize'); largestTriangleOneBucket.x = function (d) { if (!arguments.length) { return x; } x = d; return largestTriangleOneBucket; }; largestTriangleOneBucket.y = function (d) { if (!arguments.length) { return y; } y = d; return largestTriangleOneBucket; }; return largestTriangleOneBucket; } function largestTriangleThreeBucket () { var x = function x(d) { return d; }; var y = function y(d) { return d; }; var dataBucketer = bucket(); var largestTriangleThreeBucket = function largestTriangleThreeBucket(data) { if (dataBucketer.bucketSize() >= data.length) { return data; } var buckets = dataBucketer(data.slice(1, data.length - 1)); var firstBucket = data[0]; var lastBucket = data[data.length - 1]; // Keep track of the last selected bucket info and all buckets // (for the next bucket average) var allBuckets = [].concat(firstBucket, buckets, lastBucket); var lastSelectedX = x(firstBucket); var lastSelectedY = y(firstBucket); var subsampledData = buckets.map(function (thisBucket, i) { var nextAvgX = mean(allBuckets[i + 1], x); var nextAvgY = mean(allBuckets[i + 1], y); var xyData = thisBucket.map(function (item) { return [x(item), y(item)]; }); var areas = xyData.map(function (item) { var base = (lastSelectedX - nextAvgX) * (item[1] - lastSelectedY); var height = (lastSelectedX - item[0]) * (nextAvgY - lastSelectedY); return Math.abs(0.5 * base * height); }); var highestIndex = areas.indexOf(max(areas)); var highestXY = xyData[highestIndex]; lastSelectedX = highestXY[0]; lastSelectedY = highestXY[1]; return thisBucket[highestIndex]; }); // First and last data points are their own buckets. return [].concat(data[0], subsampledData, data[data.length - 1]); }; rebind(largestTriangleThreeBucket, dataBucketer, 'bucketSize'); largestTriangleThreeBucket.x = function (d) { if (!arguments.length) { return x; } x = d; return largestTriangleThreeBucket; }; largestTriangleThreeBucket.y = function (d) { if (!arguments.length) { return y; } y = d; return largestTriangleThreeBucket; }; return largestTriangleThreeBucket; } function modeMedian () { var dataBucketer = bucket(); var value = function value(d) { return d; }; var modeMedian = function modeMedian(data) { if (dataBucketer.bucketSize() > data.length) { return data; } var minMax = extent(data, value); var buckets = dataBucketer(data.slice(1, data.length - 1)); var subsampledData = buckets.map(function (thisBucket, i) { var frequencies = {}; var mostFrequent; var mostFrequentIndex; var singleMostFrequent = true; var values = thisBucket.map(value); var globalMinMax = values.filter(function (value) { return value === minMax[0] || value === minMax[1]; }).map(function (value) { return values.indexOf(value); })[0]; if (globalMinMax !== undefined) { return thisBucket[globalMinMax]; } values.forEach(function (item, i) { if (frequencies[item] === undefined) { frequencies[item] = 0; } frequencies[item]++; if (frequencies[item] > frequencies[mostFrequent] || mostFrequent === undefined) { mostFrequent = item; mostFrequentIndex = i; singleMostFrequent = true; } else if (frequencies[item] === frequencies[mostFrequent]) { singleMostFrequent = false; } }); if (singleMostFrequent) { return thisBucket[mostFrequentIndex]; } else { return thisBucket[Math.floor(thisBucket.length / 2)]; } }); // First and last data points are their own buckets. return [].concat(data[0], subsampledData, data[data.length - 1]); }; rebind(modeMedian, dataBucketer, 'bucketSize'); modeMedian.value = function (x) { if (!arguments.length) { return value; } value = x; return modeMedian; }; return modeMedian; } var sampler = Object.freeze({ bucket: bucket, largestTriangleOneBucket: largestTriangleOneBucket, largestTriangleThreeBucket: largestTriangleThreeBucket, modeMedian: modeMedian }); // the D3 CSV loader / parser converts each row into an object with property names // derived from the headings in the CSV. The spread component converts this into an // array of series; one per column (vertical spread), or one per row (horizontal spread). function spread () { var xValueKey = '', orient = 'vertical', yValue = function yValue(row, key) { // D3 CSV returns all values as strings, this converts them to numbers // by default. return Number(row[key]); }; function verticalSpread(data) { var series = Object.keys(data[0]).filter(function (key) { return key !== xValueKey; }).map(function (key) { var values = data.filter(function (row) { return row[key]; }).map(function (row) { return { x: row[xValueKey], y: yValue(row, key) }; }); return { key: key, values: values }; }); return series; } function horizontalSpread(data) { var series = data.map(function (row) { var keys = Object.keys(row).filter(function (d) { return d !== xValueKey; }); return { key: row[xValueKey], values: keys.map(function (key) { return { x: key, y: yValue(row, key) }; }) }; }); return series; } var spread = function spread(data) { return orient === 'vertical' ? verticalSpread(data) : horizontalSpread(data); }; spread.xValueKey = function (x) { if (!arguments.length) { return xValueKey; } xValueKey = x; return spread; }; spread.yValue = function (x) { if (!arguments.length) { return yValue; } yValue = x; return spread; }; spread.orient = function (x) { if (!arguments.length) { return orient; } orient = x; return spread; }; return spread; } var data = { feed: feed, random: random, spread: spread, sampler: sampler }; function ascending$1 (a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; } function bisector$1 (compare) { if (compare.length === 1) compare = ascendingComparator$1(compare); return { left: function left(a, x, lo, hi) { if (lo == null) lo = 0; if (hi == null) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) < 0) lo = mid + 1;else hi = mid; } return lo; }, right: function right(a, x, lo, hi) { if (lo == null) lo = 0; if (hi == null) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) > 0) hi = mid;else lo = mid + 1; } return lo; } }; } function ascendingComparator$1(f) { return function (d, x) { return ascending$1(f(d), x); }; } var ascendingBisect$1 = bisector$1(ascending$1); function number$2 (x) { return x === null ? NaN : +x; } function variance$1 (array, f) { var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; if (f == null) { while (++i < n) { if (!isNaN(a = number$2(array[i]))) { d = a - m; m += d / ++j; s += d * (a - m); } } } else { while (++i < n) { if (!isNaN(a = number$2(f(array[i], i, array)))) { d = a - m; m += d / ++j; s += d * (a - m); } } } if (j > 1) return s / (j - 1); } function deviation$1 (array, f) { var v = variance$1(array, f); return v ? Math.sqrt(v) : v; } function max$1 (array, f) { var i = -1, n = array.length, a, b; if (f == null) { while (++i < n) { if ((b = array[i]) != null && b >= b) { a = b;break; } }while (++i < n) { if ((b = array[i]) != null && b > a) a = b; } } else { while (++i < n) { if ((b = f(array[i], i, array)) != null && b >= b) { a = b;break; } }while (++i < n) { if ((b = f(array[i], i, array)) != null && b > a) a = b; } } return a; } function mean$1 (array, f) { var s = 0, n = array.length, a, i = -1, j = n; if (f == null) { while (++i < n) { if (!isNaN(a = number$2(array[i]))) s += a;else --j; } } else { while (++i < n) { if (!isNaN(a = number$2(f(array[i], i, array)))) s += a;else --j; } } if (j) return s / j; } function min$1 (array, f) { var i = -1, n = array.length, a, b; if (f == null) { while (++i < n) { if ((b = array[i]) != null && b >= b) { a = b;break; } }while (++i < n) { if ((b = array[i]) != null && a > b) a = b; } } else { while (++i < n) { if ((b = f(array[i], i, array)) != null && b >= b) { a = b;break; } }while (++i < n) { if ((b = f(array[i], i, array)) != null && a > b) a = b; } } return a; } function transpose$1 (matrix) { if (!(n = matrix.length)) return []; for (var i = -1, m = min$1(matrix, length$1), transpose = new Array(m); ++i < m;) { for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) { row[j] = matrix[j][i]; } } return transpose; } function length$1(d) { return d.length; } function zip$1 () { return transpose$1(arguments); } function identity$4(d) { return d; } function noop$2(d) {} function functor$1(v) { return typeof v === 'function' ? v : function () { return v; }; } function convertNaN(value) { return typeof value === 'number' && isNaN(value) ? undefined : value; } function _slidingWindow () { var period = function period() { return 10; }; var accumulator = noop$2; var value = identity$4; var defined = function defined(d) { return d != null; }; var slidingWindow = function slidingWindow(data) { var size = period.apply(this, arguments); var windowData = data.slice(0, size).map(value); return data.map(function (d, i) { if (i >= size) { // Treat windowData as FIFO rolling buffer windowData.shift(); windowData.push(value(d, i)); } if (i < size - 1 || windowData.some(function (d) { return !defined(d); })) { return accumulator(undefined, i); } return accumulator(windowData, i); }); }; slidingWindow.period = function () { if (!arguments.length) { return period; } period = functor$1(arguments.length <= 0 ? undefined : arguments[0]); return slidingWindow; }; slidingWindow.accumulator = function () { if (!arguments.length) { return accumulator; } accumulator = arguments.length <= 0 ? undefined : arguments[0]; return slidingWindow; }; slidingWindow.defined = function () { if (!arguments.length) { return defined; } defined = arguments.length <= 0 ? undefined : arguments[0]; return slidingWindow; }; slidingWindow.value = function () { if (!arguments.length) { return value; } value = arguments.length <= 0 ? undefined : arguments[0]; return slidingWindow; }; return slidingWindow; } function calculator () { var multiplier = 2; var slidingWindow = _slidingWindow().accumulator(function (values) { var stdDev = values && deviation$1(values); var average = values && mean$1(values); return { average: average, upper: convertNaN(average + multiplier * stdDev), lower: convertNaN(average - multiplier * stdDev) }; }); var bollingerBands = function bollingerBands(data) { return slidingWindow(data); }; bollingerBands.multiplier = function () { if (!arguments.length) { return multiplier; } multiplier = arguments.length <= 0 ? undefined : arguments[0]; return bollingerBands; }; rebind(bollingerBands, slidingWindow, 'period', 'value'); return bollingerBands; } function calculator$1 () { var value = identity$4; var period = function period() { return 9; }; var initialMovingAverageAccumulator = function initialMovingAverageAccumulator(period) { var values = []; return function (value) { var movingAverage = void 0; if (values.length < period) { if (value != null) { values.push(value); } else { values = []; } } if (values.length >= period) { movingAverage = mean$1(values); } return movingAverage; }; }; var exponentialMovingAverage = function exponentialMovingAverage(data) { var size = period.apply(this, arguments); var alpha = 2 / (size + 1); var initialAccumulator = initialMovingAverageAccumulator(size); var ema = void 0; return data.map(function (d, i) { var v = value(d, i); if (ema === undefined) { ema = initialAccumulator(v); } else { ema = v * alpha + (1 - alpha) * ema; } return convertNaN(ema); }); }; exponentialMovingAverage.period = function () { if (!arguments.length) { return period; } period = functor$1(arguments.length <= 0 ? undefined : arguments[0]); return exponentialMovingAverage; }; exponentialMovingAverage.value = function () { if (!arguments.length) { return value; } value = arguments.length <= 0 ? undefined : arguments[0]; return exponentialMovingAverage; }; return exponentialMovingAverage; } function calculator$2 () { var value = identity$4; var fastEMA = calculator$1().period(12); var slowEMA = calculator$1().period(26); var signalEMA = calculator$1().period(9); var macd = function macd(data) { fastEMA.value(value); slowEMA.value(value); var diff = zip$1(fastEMA(data), slowEMA(data)).map(function (d) { return d[0] !== undefined && d[1] !== undefined ? d[0] - d[1] : undefined; }); var averageDiff = signalEMA(diff); return zip$1(diff, averageDiff).map(function (d) { return { macd: d[0], signal: d[1], divergence: d[0] !== undefined && d[1] !== undefined ? d[0] - d[1] : undefined }; }); }; macd.value = function () { if (!arguments.length) { return value; } value = arguments.length <= 0 ? undefined : arguments[0]; return macd; }; rebindAll(macd, fastEMA, includeMap({ 'period': 'fastPeriod' })); rebindAll(macd, slowEMA, includeMap({ 'period': 'slowPeriod' })); rebindAll(macd, signalEMA, includeMap({ 'period': 'signalPeriod' })); return macd; } function calculator$3 () { var slidingWindow = _slidingWindow().period(14); var wildersSmoothing = function wildersSmoothing(values, prevAvg) { return prevAvg + (values[values.length - 1] - prevAvg) / values.length; }; var sum = function sum(a, b) { return a + b; }; var makeAccumulator = function makeAccumulator(prevClose, prevDownChangesAvg, prevUpChangesAvg) { return function (closes) { if (!closes) { if (prevClose !== undefined) { prevClose = NaN; } return undefined; } if (prevClose === undefined) { prevClose = closes[0]; return undefined; } var downChanges = []; var upChanges = []; closes.forEach(function (close) { var downChange = prevClose < close ? 0 : prevClose - close; var upChange = prevClose > close ? 0 : close - prevClose; downChanges.push(downChange); upChanges.push(upChange); prevClose = isNaN(prevClose) ? NaN : close; }); var downChangesAvg = prevDownChangesAvg ? wildersSmoothing(downChanges, prevDownChangesAvg) : downChanges.reduce(sum) / closes.length; var upChangesAvg = prevUpChangesAvg ? wildersSmoothing(upChanges, prevUpChangesAvg) : upChanges.reduce(sum) / closes.length; prevDownChangesAvg = downChangesAvg; prevUpChangesAvg = upChangesAvg; var rs = upChangesAvg / downChangesAvg; return convertNaN(100 - 100 / (1 + rs)); }; }; var rsi = function rsi(data) { var rsiAccumulator = makeAccumulator(); slidingWindow.accumulator(rsiAccumulator); return slidingWindow(data); }; rebind(rsi, slidingWindow, 'period', 'value'); return rsi; } function calculator$5 () { var slidingWindow = _slidingWindow().accumulator(function (values) { return values && mean$1(values); }); var movingAverage = function movingAverage(data) { return slidingWindow(data); }; rebind(movingAverage, slidingWindow, 'period', 'value'); return movingAverage; } function calculator$4 () { var closeValue = function closeValue(d, i) { return d.close; }; var highValue = function highValue(d, i) { return d.high; }; var lowValue = function lowValue(d, i) { return d.low; }; var kWindow = _slidingWindow().period(5).defined(function (d) { return closeValue(d) != null && highValue(d) != null && lowValue(d) != null; }).accumulator(function (values) { var maxHigh = values && max$1(values, highValue); var minLow = values && min$1(values, lowValue); var kValue = values && 100 * (closeValue(values[values.length - 1]) - minLow) / (maxHigh - minLow); return convertNaN(kValue); }); var dWindow = calculator$5().period(3); var stochastic = function stochastic(data) { var kValues = kWindow(data); var dValues = dWindow(kValues); return kValues.map(function (k, i) { return { k: k, d: dValues[i] }; }); }; stochastic.closeValue = function () { if (!arguments.length) { return closeValue; } closeValue = arguments.length <= 0 ? undefined : arguments[0]; return stochastic; }; stochastic.highValue = function () { if (!arguments.length) { return highValue; } highValue = arguments.length <= 0 ? undefined : arguments[0]; return stochastic; }; stochastic.lowValue = function () { if (!arguments.length) { return lowValue; } lowValue = arguments.length <= 0 ? undefined : arguments[0]; return stochastic; }; rebindAll(stochastic, kWindow, includeMap({ 'period': 'kPeriod' })); rebindAll(stochastic, dWindow, includeMap({ 'period': 'dPeriod' })); return stochastic; } function calculator$6 () { var volumeValue = function volumeValue(d, i) { return d.volume; }; var closeValue = function closeValue(d, i) { return d.close; }; var emaComputer = calculator$1().period(13); var slidingWindow = _slidingWindow().period(2).defined(function (d) { return closeValue(d) != null && volumeValue(d) != null; }).accumulator(function (values) { return values && convertNaN((closeValue(values[1]) - closeValue(values[0])) * volumeValue(values[1])); }); var force = function force(data) { var forceIndex = slidingWindow(data); return emaComputer(forceIndex); }; force.volumeValue = function () { if (!arguments.length) { return volumeValue; } volumeValue = arguments.length <= 0 ? undefined : arguments[0]; return force; }; force.closeValue = function () { if (!arguments.length) { return closeValue; } closeValue = arguments.length <= 0 ? undefined : arguments[0]; return force; }; rebind(force, emaComputer, 'period'); return force; } function calculator$7 () { var factor = 0.1; var value = identity$4; var envelope = function envelope(data) { return data.map(function (d) { var lower = convertNaN(value(d) * (1.0 - factor)); var upper = convertNaN(value(d) * (1.0 + factor)); return { lower: lower, upper: upper }; }); }; envelope.factor = function () { if (!arguments.length) { return factor; } factor = arguments.length <= 0 ? undefined : arguments[0]; return envelope; }; envelope.value = function () { if (!arguments.length) { return value; } value = arguments.length <= 0 ? undefined : arguments[0]; return envelope; }; return envelope; } function calculator$8 () { var closeValue = function closeValue(d, i) { return d.close; }; var highValue = function highValue(d, i) { return d.high; }; var lowValue = function lowValue(d, i) { return d.low; }; var emaComputer = calculator$1().period(13); var elderRay = function elderRay(data) { emaComputer.value(closeValue); return zip$1(data, emaComputer(data)).map(function (d) { var bullPower = convertNaN(highValue(d[0]) - d[1]); var bearPower = convertNaN(lowValue(d[0]) - d[1]); return { bullPower: bullPower, bearPower: bearPower }; }); }; elderRay.closeValue = function () { if (!arguments.length) { return closeValue; } closeValue = arguments.length <= 0 ? undefined : arguments[0]; return elderRay; }; elderRay.highValue = function () { if (!arguments.length) { return highValue; } highValue = arguments.length <= 0 ? undefined : arguments[0]; return elderRay; }; elderRay.lowValue = function () { if (!arguments.length) { return lowValue; } lowValue = arguments.length <= 0 ? undefined : arguments[0]; return elderRay; }; rebind(elderRay, emaComputer, 'period'); return elderRay; } // applies an algorithm to an array and merges the result using the given merge function. function merge$2 () { var merge = noop, algorithm = identity; var mergeCompute = function mergeCompute(data) { return d3.zip(data, algorithm(data)).map(function (tuple) { return merge(tuple[0], tuple[1]); }); }; mergeCompute.algorithm = function (x) { if (!arguments.length) { return algorithm; } algorithm = x; return mergeCompute; }; mergeCompute.merge = function (x) { if (!arguments.length) { return merge; } merge = x; return mergeCompute; }; return mergeCompute; } function bollingerBands () { var bollingerAlgorithm = calculator().value(function (d) { return d.close; }); var mergedAlgorithm = merge$2().algorithm(bollingerAlgorithm).merge(function (datum, indicator) { datum.bollingerBands = indicator; return datum; }); var bollingerBands = function bollingerBands(data) { return mergedAlgorithm(data); }; bollingerBands.root = function (d) { return d.bollingerBands; }; rebind(bollingerBands, mergedAlgorithm, 'merge'); rebind(bollingerBands, bollingerAlgorithm, 'period', 'value', 'multiplier'); return bollingerBands; } function exponentialMovingAverage () { var ema = calculator$1().value(function (d) { return d.close; }); var mergedAlgorithm = merge$2().algorithm(ema).merge(function (datum, indicator) { datum.exponentialMovingAverage = indicator; return datum; }); var exponentialMovingAverage = function exponentialMovingAverage(data) { return mergedAlgorithm(data); }; rebind(exponentialMovingAverage, mergedAlgorithm, 'merge'); rebind(exponentialMovingAverage, ema, 'period', 'value'); return exponentialMovingAverage; } function macd () { var macdAlgorithm = calculator$2().value(function (d) { return d.close; }); var mergedAlgorithm = merge$2().algorithm(macdAlgorithm).merge(function (datum, indicator) { datum.macd = indicator; return datum; }); var macd = function macd(data) { return mergedAlgorithm(data); }; rebind(macd, mergedAlgorithm, 'merge'); rebind(macd, macdAlgorithm, 'fastPeriod', 'slowPeriod', 'signalPeriod', 'value'); return macd; } function movingAverage () { var ma = calculator$5().value(function (d) { return d.close; }); var mergedAlgorithm = merge$2().algorithm(ma).merge(function (datum, indicator) { datum.movingAverage = indicator; return datum; }); var movingAverage = function movingAverage(data) { return mergedAlgorithm(data); }; rebind(movingAverage, mergedAlgorithm, 'merge'); rebind(movingAverage, ma, 'period', 'value'); return movingAverage; } function relativeStrengthIndex () { var rsi = calculator$3(); var mergedAlgorithm = merge$2().algorithm(rsi).merge(function (datum, indicator) { datum.rsi = indicator; return datum; }); var relativeStrengthIndex = function relativeStrengthIndex(data) { return mergedAlgorithm(data); }; rebind(relativeStrengthIndex, mergedAlgorithm, 'merge'); rebind(relativeStrengthIndex, rsi, 'period', 'value'); return relativeStrengthIndex; } function stochasticOscillator () { var stoc = calculator$4(); var mergedAlgorithm = merge$2().algorithm(stoc).merge(function (datum, indicator) { datum.stochastic = indicator; return datum; }); var stochasticOscillator = function stochasticOscillator(data) { return mergedAlgorithm(data); }; rebind(stochasticOscillator, mergedAlgorithm, 'merge'); rebind(stochasticOscillator, stoc, 'kPeriod', 'dPeriod', 'lowValue', 'closeValue', 'highValue'); return stochasticOscillator; } function forceIndex () { var force = calculator$6(); var mergedAlgorithm = merge$2().algorithm(force).merge(function (datum, indicator) { datum.force = indicator; return datum; }); var forceIndex = function forceIndex(data) { return mergedAlgorithm(data); }; rebind(forceIndex, mergedAlgorithm, 'merge'); rebind(forceIndex, force, 'period', 'volumeValue', 'closeValue'); return forceIndex; } function envelope () { var envelopeAlgorithm = calculator$7(); var mergedAlgorithm = merge$2().algorithm(envelopeAlgorithm).merge(function (datum, env) { datum.envelope = env; return datum; }); var envelope = function envelope(data) { return mergedAlgorithm(data); }; envelope.root = function (d) { return d.envelope; }; rebind(envelope, mergedAlgorithm, 'merge'); rebind(envelope, envelopeAlgorithm, 'value', 'factor'); return envelope; } function elderRay () { var elderRayAlgorithm = calculator$8().closeValue(function (d) { return d.close; }); var mergedAlgorithm = merge$2().algorithm(elderRayAlgorithm).merge(function (datum, indicator) { datum.elderRay = indicator; return datum; }); var elderRay = function elderRay(data) { return mergedAlgorithm(data); }; rebind(elderRay, mergedAlgorithm, 'merge'); rebind(elderRay, elderRayAlgorithm, 'highValue', 'lowValue', 'period', 'value'); return elderRay; } var algorithm = { bollingerBands: bollingerBands, exponentialMovingAverage: exponentialMovingAverage, macd: macd, merge: merge$2, movingAverage: movingAverage, relativeStrengthIndex: relativeStrengthIndex, stochasticOscillator: stochasticOscillator, forceIndex: forceIndex, envelope: envelope, elderRay: elderRay }; function _area () { var decorate = noop; var base = xyBase(); var areaData = d3.svg.area().defined(base.defined).x(base.x).y0(base.y0).y1(base.y1); var dataJoin$$ = dataJoin().selector('path.area').element('path').attr('class', 'area'); var area = function area(selection) { selection.each(function (data, index) { var path = dataJoin$$(this, [data]); path.attr('d', areaData); decorate(path, data, index); }); }; area.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return area; }; d3.rebind(area, base, 'xScale', 'xValue', 'yScale', 'yValue', 'y1Value', 'y0Value'); d3.rebind(area, dataJoin$$, 'key'); d3.rebind(area, areaData, 'interpolate', 'tension'); return area; } function bollingerBands$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), yValue = function yValue(d, i) { return d.close; }, xValue = function xValue(d, i) { return d.date; }, root = function root(d) { return d.bollingerBands; }, decorate = noop; var area = _area().y0Value(function (d, i) { return root(d).upper; }).y1Value(function (d, i) { return root(d).lower; }); var upperLine = _line().yValue(function (d, i) { return root(d).upper; }); var averageLine = _line().yValue(function (d, i) { return root(d).average; }); var lowerLine = _line().yValue(function (d, i) { return root(d).lower; }); var bollingerBands = function bollingerBands(selection) { var multi = _multi().xScale(xScale).yScale(yScale).series([area, upperLine, lowerLine, averageLine]).decorate(function (g, data, index) { g.enter().attr('class', function (d, i) { return 'multi bollinger ' + ['area', 'upper', 'lower', 'average'][i]; }); decorate(g, data, index); }); area.xValue(xValue); upperLine.xValue(xValue); averageLine.xValue(xValue); lowerLine.xValue(xValue); selection.call(multi); }; bollingerBands.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return bollingerBands; }; bollingerBands.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return bollingerBands; }; bollingerBands.xValue = function (x) { if (!arguments.length) { return xValue; } xValue = x; return bollingerBands; }; bollingerBands.yValue = function (x) { if (!arguments.length) { return yValue; } yValue = x; return bollingerBands; }; bollingerBands.root = function (x) { if (!arguments.length) { return root; } root = x; return bollingerBands; }; bollingerBands.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return bollingerBands; }; return bollingerBands; } // the barWidth property of the various series takes a function which, when given an // array of x values, returns a suitable width. This function creates a width which is // equal to the smallest distance between neighbouring datapoints multiplied // by the given factor function fractionalBarWidth (fraction) { return function (pixelValues) { // return some default value if there are not enough datapoints to compute the width if (pixelValues.length <= 1) { return 10; } pixelValues.sort(); // compute the distance between neighbouring items var neighbourDistances = d3.pairs(pixelValues).map(function (tuple) { return Math.abs(tuple[0] - tuple[1]); }); var minDistance = d3.min(neighbourDistances); return fraction * minDistance; }; } // The bar series renders a vertical (column) or horizontal (bar) series. In order // to provide a common implementation there are a number of functions that specialise // the rendering logic based on the 'orient' property. function barUtil () { var decorate = noop, barWidth = fractionalBarWidth(0.75), orient = 'vertical', pathGenerator = bar(); var base = xyBase().xValue(function (d, i) { return orient === 'vertical' ? d.x : d.y; }).yValue(function (d, i) { return orient === 'vertical' ? d.y : d.x; }); var dataJoin$$ = dataJoin().selector('g.bar').element('g'); function containerTranslation(d, i) { if (orient === 'vertical') { return 'translate(' + base.x1(d, i) + ', ' + base.y0(d, i) + ')'; } else { return 'translate(' + base.x0(d, i) + ', ' + base.y1(d, i) + ')'; } } function barHeight(d, i) { if (orient === 'vertical') { return base.y1(d, i) - base.y0(d, i); } else { return base.x1(d, i) - base.x0(d, i); } } function valueAxisDimension(generator) { if (orient === 'vertical') { return generator.height; } else { return generator.width; } } function crossAxisDimension(generator) { if (orient === 'vertical') { return generator.width; } else { return generator.height; } } function crossAxisValueFunction() { return orient === 'vertical' ? base.x : base.y; } var bar$$ = function bar$$(selection) { selection.each(function (data, index) { if (orient !== 'vertical' && orient !== 'horizontal') { throw new Error('The bar series does not support an orientation of ' + orient); } dataJoin$$.attr('class', 'bar ' + orient); var filteredData = data.filter(base.defined); pathGenerator.x(0).y(0).width(0).height(0); if (orient === 'vertical') { pathGenerator.verticalAlign('top'); } else { pathGenerator.horizontalAlign('right'); } // set the width of the bars var width = barWidth(filteredData.map(crossAxisValueFunction())); crossAxisDimension(pathGenerator)(width); var g = dataJoin$$(this, filteredData); // within the enter selection the pathGenerator creates a zero // height bar. As a result, when used with a transition the bar grows // from y0 to y1 (y) g.enter().attr('transform', containerTranslation).append('path').attr('d', function (d) { return pathGenerator([d]); }); // set the bar to its correct height valueAxisDimension(pathGenerator)(barHeight); g.attr('transform', containerTranslation).select('path').attr('d', function (d) { return pathGenerator([d]); }); decorate(g, filteredData, index); }); }; bar$$.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return bar$$; }; bar$$.barWidth = function (x) { if (!arguments.length) { return barWidth; } barWidth = d3.functor(x); return bar$$; }; bar$$.orient = function (x) { if (!arguments.length) { return orient; } orient = x; return bar$$; }; d3.rebind(bar$$, base, 'xScale', 'xValue', 'x1Value', 'x0Value', 'yScale', 'yValue', 'y1Value', 'y0Value'); d3.rebind(bar$$, dataJoin$$, 'key'); return bar$$; } function macd$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), xValue = function xValue(d) { return d.date; }, root = function root(d) { return d.macd; }, macdLine = _line(), signalLine = _line(), divergenceBar = barUtil(), multiSeries = _multi(), decorate = noop; var macd = function macd(selection) { macdLine.xValue(xValue).yValue(function (d, i) { return root(d).macd; }); signalLine.xValue(xValue).yValue(function (d, i) { return root(d).signal; }); divergenceBar.xValue(xValue).yValue(function (d, i) { return root(d).divergence; }); multiSeries.xScale(xScale).yScale(yScale).series([divergenceBar, macdLine, signalLine]).decorate(function (g, data, index) { g.enter().attr('class', function (d, i) { return 'multi ' + ['macd-divergence', 'macd', 'macd-signal'][i]; }); decorate(g, data, index); }); selection.call(multiSeries); }; macd.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return macd; }; macd.xValue = function (x) { if (!arguments.length) { return xValue; } xValue = x; return macd; }; macd.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return macd; }; macd.root = function (x) { if (!arguments.length) { return root; } root = x; return macd; }; macd.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return macd; }; d3.rebind(macd, divergenceBar, 'barWidth'); return macd; } function relativeStrengthIndex$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), upperValue = 70, lowerValue = 30, multiSeries = _multi(), decorate = noop; var annotations = line(); var rsiLine = _line().xValue(function (d, i) { return d.date; }).yValue(function (d, i) { return d.rsi; }); var rsi = function rsi(selection) { multiSeries.xScale(xScale).yScale(yScale).series([annotations, rsiLine]).mapping(function (series) { if (series === annotations) { return [upperValue, 50, lowerValue]; } return this; }).decorate(function (g, data, index) { g.enter().attr('class', function (d, i) { return 'multi rsi ' + ['annotations', 'indicator'][i]; }); decorate(g, data, index); }); selection.call(multiSeries); }; rsi.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return rsi; }; rsi.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return rsi; }; rsi.upperValue = function (x) { if (!arguments.length) { return upperValue; } upperValue = x; return rsi; }; rsi.lowerValue = function (x) { if (!arguments.length) { return lowerValue; } lowerValue = x; return rsi; }; rsi.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return rsi; }; d3.rebind(rsi, rsiLine, 'yValue', 'xValue'); return rsi; } function stochasticOscillator$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), upperValue = 80, lowerValue = 20, multi = _multi(), decorate = noop; var annotations = line(); var dLine = _line().xValue(function (d, i) { return d.date; }).yValue(function (d, i) { return d.stochastic.d; }); var kLine = _line().yValue(function (d, i) { return d.stochastic.k; }); var stochastic = function stochastic(selection) { multi.xScale(xScale).yScale(yScale).series([annotations, dLine, kLine]).mapping(function (series) { if (series === annotations) { return [upperValue, lowerValue]; } return this; }).decorate(function (g, data, index) { g.enter().attr('class', function (d, i) { return 'multi stochastic ' + ['annotations', 'stochastic-d', 'stochastic-k'][i]; }); decorate(g, data, index); }); selection.call(multi); }; stochastic.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return stochastic; }; stochastic.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return stochastic; }; stochastic.upperValue = function (x) { if (!arguments.length) { return upperValue; } upperValue = x; return stochastic; }; stochastic.lowerValue = function (x) { if (!arguments.length) { return lowerValue; } lowerValue = x; return stochastic; }; stochastic.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return stochastic; }; d3.rebind(stochastic, dLine, 'yDValue', 'xDValue'); d3.rebind(stochastic, kLine, 'yKValue', 'xKValue'); return stochastic; } function forceIndex$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), multiSeries = _multi(), decorate = noop; var annotations = line(); var forceLine = _line().xValue(function (d, i) { return d.date; }).yValue(function (d, i) { return d.force; }); var force = function force(selection) { multiSeries.xScale(xScale).yScale(yScale).series([annotations, forceLine]).mapping(function (series) { if (series === annotations) { return [0]; } return this; }).decorate(function (g, data, index) { g.enter().attr('class', function (d, i) { return 'multi ' + ['annotations', 'indicator'][i]; }); decorate(g, data, index); }); selection.call(multiSeries); }; force.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; annotations.xScale(x); return force; }; force.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; annotations.yScale(x); return force; }; force.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return force; }; d3.rebind(force, forceLine, 'yValue', 'xValue'); return force; } function envelope$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), yValue = function yValue(d, i) { return d.close; }, xValue = function xValue(d, i) { return d.date; }, root = function root(d) { return d.envelope; }, decorate = noop; var area = _area().y0Value(function (d, i) { return root(d).upper; }).y1Value(function (d, i) { return root(d).lower; }); var upperLine = _line().yValue(function (d, i) { return root(d).upper; }); var lowerLine = _line().yValue(function (d, i) { return root(d).lower; }); var envelope = function envelope(selection) { var multi = _multi().xScale(xScale).yScale(yScale).series([area, upperLine, lowerLine]).decorate(function (g, data, index) { g.enter().attr('class', function (d, i) { return 'multi envelope ' + ['area', 'upper', 'lower'][i]; }); decorate(g, data, index); }); area.xValue(xValue); upperLine.xValue(xValue); lowerLine.xValue(xValue); selection.call(multi); }; envelope.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return envelope; }; envelope.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return envelope; }; envelope.xValue = function (x) { if (!arguments.length) { return xValue; } xValue = x; return envelope; }; envelope.yValue = function (x) { if (!arguments.length) { return yValue; } yValue = x; return envelope; }; envelope.root = function (x) { if (!arguments.length) { return root; } root = x; return envelope; }; envelope.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return envelope; }; return envelope; } function elderRay$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), xValue = function xValue(d) { return d.date; }, root = function root(d) { return d.elderRay; }, barWidth = fractionalBarWidth(0.75), bullBar = barUtil(), bearBar = barUtil(), bullBarTop = barUtil(), bearBarTop = barUtil(), multi = _multi(), decorate = noop; var elderRay = function elderRay(selection) { function isTop(input, comparison) { // The values share parity and the input is smaller than the comparison return input * comparison > 0 && Math.abs(input) < Math.abs(comparison); } bullBar.xValue(xValue).yValue(function (d, i) { return isTop(root(d).bullPower, root(d).bearPower) ? undefined : root(d).bullPower; }).barWidth(barWidth); bearBar.xValue(xValue).yValue(function (d, i) { return isTop(root(d).bearPower, root(d).bullPower) ? undefined : root(d).bearPower; }).barWidth(barWidth); bullBarTop.xValue(xValue).yValue(function (d, i) { return isTop(root(d).bullPower, root(d).bearPower) ? root(d).bullPower : undefined; }).barWidth(barWidth); bearBarTop.xValue(xValue).yValue(function (d, i) { return isTop(root(d).bearPower, root(d).bullPower) ? root(d).bearPower : undefined; }).barWidth(barWidth); multi.xScale(xScale).yScale(yScale).series([bullBar, bearBar, bullBarTop, bearBarTop]).decorate(function (g, data, index) { g.enter().attr('class', function (d, i) { return 'multi ' + ['bull', 'bear', 'bull top', 'bear top'][i]; }); decorate(g, data, index); }); selection.call(multi); }; elderRay.barWidth = function (x) { if (!arguments.length) { return barWidth; } barWidth = d3.functor(x); return elderRay; }; elderRay.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return elderRay; }; elderRay.xValue = function (x) { if (!arguments.length) { return xValue; } xValue = x; return elderRay; }; elderRay.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return elderRay; }; elderRay.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return elderRay; }; return elderRay; } var renderer = { bollingerBands: bollingerBands$1, macd: macd$1, relativeStrengthIndex: relativeStrengthIndex$1, stochasticOscillator: stochasticOscillator$1, forceIndex: forceIndex$1, envelope: envelope$1, elderRay: elderRay$1 }; var indicator = { algorithm: algorithm, renderer: renderer }; function ownerSVGElement(node) { while (node.ownerSVGElement) { node = node.ownerSVGElement; } return node; } // parses the style attribute, converting it into a JavaScript object function parseStyle(style) { if (!style) { return {}; } var properties = style.split(';'); var json = {}; properties.forEach(function (property) { var components = property.split(':'); if (components.length === 2) { var name = components[0].trim(); var value = components[1].trim(); json[name] = isNaN(value) ? value : Number(value); } }); return json; } // creates the structure required by the layout engine function createNodes(el) { function getChildNodes() { var children = []; for (var i = 0; i < el.childNodes.length; i++) { var child = el.childNodes[i]; if (child.nodeType === 1) { if (child.getAttribute('layout-style')) { children.push(createNodes(child)); } } } return children; } return { style: parseStyle(el.getAttribute('layout-style')), children: getChildNodes(el), element: el }; } // takes the result of layout and applied it to the SVG elements function applyLayout(node, subtree) { // don't set layout-width/height on layout root node if (subtree) { node.element.setAttribute('layout-width', node.layout.width); node.element.setAttribute('layout-height', node.layout.height); } node.element.setAttribute('layout-x', node.layout.left); node.element.setAttribute('layout-y', node.layout.top); var rectOrSvg = node.element.nodeName.match(/(?:svg|rect)/i); //for svg / rect set the dimensions via width/height properties if (rectOrSvg) { node.element.setAttribute('width', node.layout.width); node.element.setAttribute('height', node.layout.height); } //for non-root svg / rect set the offset via x/y properties if (rectOrSvg && subtree) { node.element.setAttribute('x', node.layout.left); node.element.setAttribute('y', node.layout.top); } // for all other non-root elements apply a transform if (!rectOrSvg && subtree) { node.element.setAttribute('transform', 'translate(' + node.layout.left + ', ' + node.layout.top + ')'); } node.children.forEach(function (childNode) { applyLayout(childNode, true); }); } function computeDimensions(node) { if (node.hasAttribute('layout-width') && node.hasAttribute('layout-height')) { return { width: Number(node.getAttribute('layout-width')), height: Number(node.getAttribute('layout-height')) }; } else { return innerDimensions(node); } } function computePosition(node) { if (node.hasAttribute('layout-x') && node.hasAttribute('layout-y')) { return { x: Number(node.getAttribute('layout-x')), y: Number(node.getAttribute('layout-y')) }; } else { return { x: 0, y: 0 }; } } function layout$1(node) { if (ownerSVGElement(node).__layout__ === 'suspended') { return; } var dimensions = computeDimensions(node); var position = computePosition(node); // create the layout nodes var layoutNodes = createNodes(node); // set the dimensions / position of the root layoutNodes.style.width = dimensions.width; layoutNodes.style.height = dimensions.height; layoutNodes.style.left = position.x; layoutNodes.style.top = position.y; // use the Facebook CSS goodness computeLayout(layoutNodes); // apply the resultant layout applyLayout(layoutNodes); } function layoutSuspended(x) { if (!arguments.length) { return Boolean(ownerSVGElement(this.node()).__layout__); } return this.each(function () { ownerSVGElement(this).__layout__ = x ? 'suspended' : ''; }); } d3.selection.prototype.layoutSuspended = layoutSuspended; d3.transition.prototype.layoutSuspended = layoutSuspended; function layoutSelection(name, value) { var argsLength = arguments.length; // For layout(string), return the lyout value for the first node if (argsLength === 1 && typeof name === 'string') { var node = this.node(); return Number(node.getAttribute('layout-' + name)); } // for all other invocations, iterate over each item in the selection return this.each(function () { if (argsLength === 2) { if (typeof name !== 'string') { // layout(number, number) - sets the width and height and performs layout this.setAttribute('layout-width', name); this.setAttribute('layout-height', value); layout$1(this); } else { // layout(name, value) - sets a layout- attribute this.setAttribute('layout-style', name + ':' + value); } } else if (argsLength === 1) { if (typeof name !== 'string') { // layout(object) - sets the layout-style property to the given object var currentStyle = parseStyle(this.getAttribute('layout-style')); var styleDiff = name; Object.keys(styleDiff).forEach(function (property) { currentStyle[property] = styleDiff[property]; }); var layoutCss = Object.keys(currentStyle).map(function (property) { return property + ':' + currentStyle[property]; }).join(';'); this.setAttribute('layout-style', layoutCss); } } else if (argsLength === 0) { // layout() - executes layout layout$1(this); } }); } d3.selection.prototype.layout = layoutSelection; d3.transition.prototype.layout = layoutSelection; function skipWeekends$1 () { var millisPerDay = 24 * 3600 * 1000; var millisPerWorkWeek = millisPerDay * 5; var millisPerWeek = millisPerDay * 7; var skipWeekends = {}; function isWeekend(date) { return date.getDay() === 0 || date.getDay() === 6; } skipWeekends.clampDown = function (date) { if (date && isWeekend(date)) { var daysToSubtract = date.getDay() === 0 ? 2 : 1; // round the date up to midnight var newDate = d3.time.day.ceil(date); // then subtract the required number of days return d3.time.day.offset(newDate, -daysToSubtract); } else { return date; } }; skipWeekends.clampUp = function (date) { if (date && isWeekend(date)) { var daysToAdd = date.getDay() === 0 ? 1 : 2; // round the date down to midnight var newDate = d3.time.day.floor(date); // then add the required number of days return d3.time.day.offset(newDate, daysToAdd); } else { return date; } }; // returns the number of included milliseconds (i.e. those which do not fall) // within discontinuities, along this scale skipWeekends.distance = function (startDate, endDate) { startDate = skipWeekends.clampUp(startDate); endDate = skipWeekends.clampDown(endDate); // move the start date to the end of week boundary var offsetStart = d3.time.saturday.ceil(startDate); if (endDate < offsetStart) { return endDate.getTime() - startDate.getTime(); } var msAdded = offsetStart.getTime() - startDate.getTime(); // move the end date to the end of week boundary var offsetEnd = d3.time.saturday.ceil(endDate); var msRemoved = offsetEnd.getTime() - endDate.getTime(); // determine how many weeks there are between these two dates // round to account for DST transitions var weeks = Math.round((offsetEnd.getTime() - offsetStart.getTime()) / millisPerWeek); return weeks * millisPerWorkWeek + msAdded - msRemoved; }; skipWeekends.offset = function (startDate, ms) { var date = isWeekend(startDate) ? skipWeekends.clampUp(startDate) : startDate; if (ms === 0) { return date; } var isNegativeOffset = ms < 0; var isPositiveOffset = ms > 0; var remainingms = ms; // move to the end of week boundary for a postive offset or to the start of a week for a negative offset var weekBoundary = isNegativeOffset ? d3.time.monday.floor(date) : d3.time.saturday.ceil(date); remainingms -= weekBoundary.getTime() - date.getTime(); // if the distance to the boundary is greater than the number of ms // simply add the ms to the current date if (isNegativeOffset && remainingms > 0 || isPositiveOffset && remainingms < 0) { return new Date(date.getTime() + ms); } // skip the weekend for a positive offset date = isNegativeOffset ? weekBoundary : d3.time.day.offset(weekBoundary, 2); // add all of the complete weeks to the date var completeWeeks = Math.floor(remainingms / millisPerWorkWeek); date = d3.time.day.offset(date, completeWeeks * 7); remainingms -= completeWeeks * millisPerWorkWeek; // add the remaining time date = new Date(date.getTime() + remainingms); return date; }; skipWeekends.copy = function () { return skipWeekends; }; return skipWeekends; } var scale$1 = { discontinuity: { identity: identity$1, skipWeekends: skipWeekends$1 }, dateTime: exportedScale }; function ohlcBase () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), xValue = function xValue(d, i) { return d.date; }, yOpenValue = function yOpenValue(d, i) { return d.open; }, yHighValue = function yHighValue(d, i) { return d.high; }, yLowValue = function yLowValue(d, i) { return d.low; }, yCloseValue = function yCloseValue(d, i) { return d.close; }, barWidth = fractionalBarWidth(0.75), xValueScaled = function xValueScaled(d, i) { return xScale(xValue(d, i)); }; function base() {} base.width = function (data) { return barWidth(data.map(xValueScaled)); }; base.defined = function (d, i) { return defined(xValue, yOpenValue, yLowValue, yHighValue, yCloseValue)(d, i); }; base.values = function (d, i) { var yCloseRaw = yCloseValue(d, i), yOpenRaw = yOpenValue(d, i); var direction = ''; if (yCloseRaw > yOpenRaw) { direction = 'up'; } else if (yCloseRaw < yOpenRaw) { direction = 'down'; } return { x: xValueScaled(d, i), yOpen: yScale(yOpenRaw), yHigh: yScale(yHighValue(d, i)), yLow: yScale(yLowValue(d, i)), yClose: yScale(yCloseRaw), direction: direction }; }; base.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return base; }; base.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return base; }; base.xValue = function (x) { if (!arguments.length) { return xValue; } xValue = x; return base; }; base.yOpenValue = function (x) { if (!arguments.length) { return yOpenValue; } yOpenValue = x; return base; }; base.yHighValue = function (x) { if (!arguments.length) { return yHighValue; } yHighValue = x; return base; }; base.yLowValue = function (x) { if (!arguments.length) { return yLowValue; } yLowValue = x; return base; }; base.yValue = base.yCloseValue = function (x) { if (!arguments.length) { return yCloseValue; } yCloseValue = x; return base; }; base.barWidth = function (x) { if (!arguments.length) { return barWidth; } barWidth = d3.functor(x); return base; }; return base; } function candlestick$1 () { var decorate = noop, base = ohlcBase(); var dataJoin$$ = dataJoin().selector('g.candlestick').element('g').attr('class', 'candlestick'); function containerTranslation(values) { return 'translate(' + values.x + ', ' + values.yHigh + ')'; } var candlestick$$ = function candlestick$$(selection) { selection.each(function (data, index) { var filteredData = data.filter(base.defined); var g = dataJoin$$(this, filteredData); g.enter().attr('transform', function (d, i) { return containerTranslation(base.values(d, i)) + ' scale(1e-6, 1)'; }).append('path'); var pathGenerator = candlestick().width(base.width(filteredData)); g.each(function (d, i) { var values = base.values(d, i); var graph = d3.transition(d3.select(this)).attr({ 'class': 'candlestick ' + values.direction, 'transform': function transform() { return containerTranslation(values) + ' scale(1)'; } }); pathGenerator.x(d3.functor(0)).open(function () { return values.yOpen - values.yHigh; }).high(function () { return values.yHigh - values.yHigh; }).low(function () { return values.yLow - values.yHigh; }).close(function () { return values.yClose - values.yHigh; }); graph.select('path').attr('d', pathGenerator([d])); }); decorate(g, data, index); }); }; candlestick$$.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return candlestick$$; }; d3.rebind(candlestick$$, dataJoin$$, 'key'); rebindAll(candlestick$$, base); return candlestick$$; } function cycle () { var decorate = noop, xScale = d3.scale.linear(), yScale = d3.scale.linear(), xValue = function xValue(d, i) { return d.date.getDay(); }, subScale = d3.scale.linear(), subSeries = _line(), barWidth = fractionalBarWidth(0.75); var dataJoin$$ = dataJoin().selector('g.cycle').element('g').attr('class', 'cycle'); var cycle = function cycle(selection) { selection.each(function (data, index) { var dataByX = d3.nest().key(xValue).map(data); var xValues = Object.keys(dataByX); var width = barWidth(xValues.map(xScale)), halfWidth = width / 2; var g = dataJoin$$(this, xValues); g.each(function (d, i) { var graph = d3.select(this); graph.attr('transform', 'translate(' + xScale(d) + ', 0)'); (subScale.rangeBands || subScale.range)([-halfWidth, halfWidth]); subSeries.xScale(subScale).yScale(yScale); d3.select(this).datum(dataByX[d]).call(subSeries); }); decorate(g, xValues, index); }); }; cycle.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return cycle; }; cycle.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return cycle; }; cycle.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return cycle; }; cycle.xValue = function (x) { if (!arguments.length) { return xValue; } xValue = x; return cycle; }; cycle.subScale = function (x) { if (!arguments.length) { return subScale; } subScale = x; return cycle; }; cycle.subSeries = function (x) { if (!arguments.length) { return subSeries; } subSeries = x; return cycle; }; cycle.barWidth = function (x) { if (!arguments.length) { return barWidth; } barWidth = d3.functor(x); return cycle; }; d3.rebind(cycle, dataJoin$$, 'key'); return cycle; } function ohlc$1 (drawMethod) { var decorate = noop, base = ohlcBase(); var dataJoin$$ = dataJoin().selector('g.ohlc').element('g').attr('class', 'ohlc'); function containerTranslation(values) { return 'translate(' + values.x + ', ' + values.yHigh + ')'; } var ohlc$$ = function ohlc$$(selection) { selection.each(function (data, index) { var filteredData = data.filter(base.defined); var g = dataJoin$$(this, filteredData); g.enter().attr('transform', function (d, i) { return containerTranslation(base.values(d, i)) + ' scale(1e-6, 1)'; }).append('path'); var pathGenerator = ohlc().width(base.width(filteredData)); g.each(function (d, i) { var values = base.values(d, i); var graph = d3.transition(d3.select(this)).attr({ 'class': 'ohlc ' + values.direction, 'transform': function transform() { return containerTranslation(values) + ' scale(1)'; } }); pathGenerator.x(d3.functor(0)).open(function () { return values.yOpen - values.yHigh; }).high(function () { return values.yHigh - values.yHigh; }).low(function () { return values.yLow - values.yHigh; }).close(function () { return values.yClose - values.yHigh; }); graph.select('path').attr('d', pathGenerator([d])); }); decorate(g, data, index); }); }; ohlc$$.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return ohlc$$; }; d3.rebind(ohlc$$, dataJoin$$, 'key'); rebindAll(ohlc$$, base); return ohlc$$; } function _stack () { var series = noop, values = function values(d) { return d.values; }; var stack = function stack(selection) { selection.each(function (data) { var container = d3.select(this); var dataJoin$$ = dataJoin().selector('g.stacked').element('g').attr('class', 'stacked'); var g = dataJoin$$(container, data); g.enter().append('g'); g.select('g').datum(values).call(series); }); }; stack.series = function (x) { if (!arguments.length) { return series; } series = x; return stack; }; stack.values = function (x) { if (!arguments.length) { return values; } values = x; return stack; }; return stack; } function area () { var area = _area().yValue(function (d) { return d.y0 + d.y; }).y0Value(function (d) { return d.y0; }); var stack = _stack().series(area); var stackedArea = function stackedArea(selection) { selection.call(stack); }; rebindAll(stackedArea, area); return stackedArea; } function bar$1 () { var bar = barUtil().yValue(function (d) { return d.y0 + d.y; }).y0Value(function (d) { return d.y0; }); var stack = _stack().series(bar); var stackedBar = function stackedBar(selection) { selection.call(stack); }; rebindAll(stackedBar, bar); return stackedBar; } function line$1 () { var line = _line().yValue(function (d) { return d.y0 + d.y; }); var stack = _stack().series(line); var stackedLine = function stackedLine(selection) { selection.call(stack); }; rebindAll(stackedLine, line); return stackedLine; } var stacked = { area: area, bar: bar$1, stack: _stack, line: line$1 }; function grouped (series) { var barWidth = fractionalBarWidth(0.75), decorate = noop, xScale = d3.scale.linear(), values = function values(d) { return d.values; }; var dataJoin$$ = dataJoin().selector('g.stacked').element('g').attr('class', 'stacked'); var grouped = function grouped(selection) { selection.each(function (data) { var value = series.xValue(), x = function x(d, i) { return xScale(value(d, i)); }, width = barWidth(data[0].values.map(x)), offsetScale = d3.scale.linear(); if (series.barWidth) { var subBarWidth = width / (data.length - 1); series.barWidth(subBarWidth); } var halfWidth = width / 2; offsetScale.domain([0, data.length - 1]).range([-halfWidth, halfWidth]); var g = dataJoin$$(this, data); g.enter().append('g'); g.select('g').datum(values).each(function (_, index) { var container = d3.select(this); // create a composite scale that applies the required offset var compositeScale = function compositeScale(_x) { return xScale(_x) + offsetScale(index); }; series.xScale(compositeScale); // adapt the decorate function to give each series the correct index series.decorate(function (s, d) { decorate(s, d, index); }); container.call(series); }); }); }; grouped.groupWidth = function (_x) { if (!arguments.length) { return barWidth; } barWidth = d3.functor(_x); return grouped; }; grouped.decorate = function (_x) { if (!arguments.length) { return decorate; } decorate = _x; return grouped; }; grouped.xScale = function (_x) { if (!arguments.length) { return xScale; } xScale = _x; return grouped; }; grouped.values = function (_x) { if (!arguments.length) { return values; } values = _x; return grouped; }; rebindAll(grouped, series, exclude('decorate', 'xScale')); return grouped; } function errorBar$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), high = function high(d, i) { return d.high; }, low = function low(d, i) { return d.low; }, value = function value(d, i) { return d.value; }, orient = 'vertical', barWidth = fractionalBarWidth(0.5), decorate = noop; var dataJoin$$ = dataJoin().selector('g.errorBar').element('g').attr('class', 'errorBar'); var pathGenerator = errorBar().value(0); var errorBar$$ = function errorBar$$(selection) { selection.each(function (data, index) { var filteredData = data.filter(defined(low, high, value, value)); var g = dataJoin$$(this, filteredData); g.enter().append('path'); var scale = orient === 'vertical' ? xScale : yScale; var width = barWidth(filteredData.map(function (d, i) { return scale(value(d, i)); })); pathGenerator.orient(orient).width(width); g.each(function (d, i) { var origin, _high, _low; if (orient === 'vertical') { var y = yScale(high(d, i)); origin = xScale(value(d, i)) + ',' + y; _high = 0; _low = yScale(low(d, i)) - y; } else { var x = xScale(low(d, i)); origin = x + ',' + yScale(value(d, i)); _high = xScale(high(d, i)) - x; _low = 0; } pathGenerator.high(_high).low(_low); d3.select(this).attr('transform', 'translate(' + origin + ')').select('path').attr('d', pathGenerator([d])); }); decorate(g, data, index); }); }; errorBar$$.orient = function (x) { if (!arguments.length) { return orient; } orient = x; return errorBar$$; }; errorBar$$.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return errorBar$$; }; errorBar$$.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return errorBar$$; }; errorBar$$.low = function (x) { if (!arguments.length) { return low; } low = d3.functor(x); return errorBar$$; }; errorBar$$.high = function (x) { if (!arguments.length) { return high; } high = d3.functor(x); return errorBar$$; }; errorBar$$.value = function (x) { if (!arguments.length) { return value; } value = d3.functor(x); return errorBar$$; }; errorBar$$.barWidth = function (x) { if (!arguments.length) { return barWidth; } barWidth = d3.functor(x); return errorBar$$; }; errorBar$$.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return errorBar$$; }; d3.rebind(errorBar$$, dataJoin$$, 'key'); return errorBar$$; } function waterfall () { function isVertical() { return bar.orient() === 'vertical'; } var bar = barUtil(); var waterfall = function waterfall(selection) { bar.xValue(function (d, i) { return isVertical() ? d.x : d.y1; }).yValue(function (d, i) { return isVertical() ? d.y1 : d.x; }).x0Value(function (d, i) { return isVertical() ? 0 : d.y0; }).y0Value(function (d, i) { return isVertical() ? d.y0 : 0; }).decorate(function (g, d1, i) { g.enter().attr('class', 'waterfall ' + bar.orient()).classed('up', function (d) { return d.direction === 'up'; }).classed('down', function (d) { return d.direction === 'down'; }); }); bar(selection); }; rebindAll(waterfall, bar); return waterfall; } function waterfall$1 () { var xValueKey = '', yValue = function yValue(d) { return d.y; }, startsWithTotal = false, totals = function totals(d, i, data) { if (i === data.length - 1) { return 'Final'; } }, directions = { up: 'up', down: 'down', unchanged: 'unchanged' }; var waterfall = function waterfall(data) { var length = data.length, i = 0, previousEnd = 0, start, end, total, result = []; if (startsWithTotal) { // First value is a total previousEnd = yValue(data[0]); result.push({ x: data[0][xValueKey], y0: 0, y1: previousEnd, direction: directions.unchanged }); i = 1; } for (i; i < length; i += 1) { start = previousEnd; end = yValue(data[i]) + previousEnd; result.push({ x: data[i][xValueKey], y0: start, y1: end, direction: end - start > 0 ? directions.up : directions.down }); total = totals(data[i], i, data); if (total) { // Insert a total value here result.push({ x: total, y0: 0, y1: end, direction: directions.unchanged }); } previousEnd = end; } return result; }; waterfall.xValueKey = function (x) { if (!arguments.length) { return xValueKey; } xValueKey = x; return waterfall; }; waterfall.yValue = function (x) { if (!arguments.length) { return yValue; } yValue = x; return waterfall; }; waterfall.total = function (x) { if (!arguments.length) { return totals; } totals = x; return waterfall; }; waterfall.startsWithTotal = function (x) { if (!arguments.length) { return startsWithTotal; } startsWithTotal = x; return waterfall; }; return waterfall; } var algorithm$1 = { waterfall: waterfall$1 }; function boxPlot$1 () { var xScale = d3.time.scale(), yScale = d3.scale.linear(), upperQuartile = function upperQuartile(d, i) { return d.upperQuartile; }, lowerQuartile = function lowerQuartile(d, i) { return d.lowerQuartile; }, high = function high(d, i) { return d.high; }, low = function low(d, i) { return d.low; }, value = function value(d, i) { return d.value; }, median = function median(d, i) { return d.median; }, orient = 'vertical', barWidth = fractionalBarWidth(0.5), decorate = noop; var dataJoin$$ = dataJoin().selector('g.box-plot').element('g').attr('class', 'box-plot'); var pathGenerator = boxPlot().value(0); var boxPlot$$ = function boxPlot$$(selection) { selection.each(function (data, index) { var filteredData = data.filter(defined(low, high, lowerQuartile, upperQuartile, value, median)); var g = dataJoin$$(this, filteredData); g.enter().append('path'); var scale = orient === 'vertical' ? xScale : yScale; var width = barWidth(filteredData.map(function (d, i) { return scale(value(d, i)); })); pathGenerator.orient(orient).width(width); g.each(function (d, i) { var origin, _median, _upperQuartile, _lowerQuartile, _high, _low; if (orient === 'vertical') { var y = yScale(high(d, i)); origin = xScale(value(d, i)) + ',' + y; _high = 0; _upperQuartile = yScale(upperQuartile(d, i)) - y; _median = yScale(median(d, i)) - y; _lowerQuartile = yScale(lowerQuartile(d, i)) - y; _low = yScale(low(d, i)) - y; } else { var x = xScale(low(d, i)); origin = x + ',' + yScale(value(d, i)); _high = xScale(high(d, i)) - x; _upperQuartile = xScale(upperQuartile(d, i)) - x; _median = xScale(median(d, i)) - x; _lowerQuartile = xScale(lowerQuartile(d, i)) - x; _low = 0; } pathGenerator.median(_median).upperQuartile(_upperQuartile).lowerQuartile(_lowerQuartile).high(_high).low(_low); d3.select(this).attr('transform', 'translate(' + origin + ')').select('path').attr('d', pathGenerator([d])); }); decorate(g, data, index); }); }; boxPlot$$.orient = function (x) { if (!arguments.length) { return orient; } orient = x; return boxPlot$$; }; boxPlot$$.xScale = function (x) { if (!arguments.length) { return xScale; } xScale = x; return boxPlot$$; }; boxPlot$$.yScale = function (x) { if (!arguments.length) { return yScale; } yScale = x; return boxPlot$$; }; boxPlot$$.lowerQuartile = function (x) { if (!arguments.length) { return lowerQuartile; } lowerQuartile = d3.functor(x); return boxPlot$$; }; boxPlot$$.upperQuartile = function (x) { if (!arguments.length) { return upperQuartile; } upperQuartile = d3.functor(x); return boxPlot$$; }; boxPlot$$.low = function (x) { if (!arguments.length) { return low; } low = d3.functor(x); return boxPlot$$; }; boxPlot$$.high = function (x) { if (!arguments.length) { return high; } high = d3.functor(x); return boxPlot$$; }; boxPlot$$.value = function (x) { if (!arguments.length) { return value; } value = d3.functor(x); return boxPlot$$; }; boxPlot$$.median = function (x) { if (!arguments.length) { return median; } median = d3.functor(x); return boxPlot$$; }; boxPlot$$.barWidth = function (x) { if (!arguments.length) { return barWidth; } barWidth = d3.functor(x); return boxPlot$$; }; boxPlot$$.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return boxPlot$$; }; d3.rebind(boxPlot$$, dataJoin$$, 'key'); d3.rebind(boxPlot$$, pathGenerator, 'cap'); return boxPlot$$; } var series = { area: _area, axis: axis, bar: barUtil, candlestick: candlestick$1, cycle: cycle, line: _line, multi: _multi, ohlc: ohlc$1, point: point, stacked: stacked, grouped: grouped, xyBase: xyBase, ohlcBase: ohlcBase, errorBar: errorBar$1, boxPlot: boxPlot$1, waterfall: waterfall, algorithm: algorithm$1 }; var svg = { axis: axis$1, bar: bar, boxPlot: boxPlot, candlestick: candlestick, errorBar: errorBar, ohlc: ohlc }; // searches for a minimum when applying the given accessor to each item within the supplied array. // The returned array has the following form: // [minumum accessor value, datum, index] function minimum$1(data, accessor) { return data.map(function (dataPoint, index) { return [accessor(dataPoint, index), dataPoint, index]; }).reduce(function (accumulator, dataPoint) { return accumulator[0] > dataPoint[0] ? dataPoint : accumulator; }, [Number.MAX_VALUE, null, -1]); } function noSnap(xScale, yScale) { return function (xPixel, yPixel) { return { x: xPixel, y: yPixel }; }; } function pointSnap(xScale, yScale, xValue, yValue, data, objectiveFunction) { // a default function that computes the distance between two points objectiveFunction = objectiveFunction || function (x, y, cx, cy) { var dx = x - cx, dy = y - cy; return dx * dx + dy * dy; }; return function (xPixel, yPixel) { var filtered = data.filter(function (d, i) { return defined(xValue, yValue)(d, i); }); var nearest = minimum$1(filtered, function (d) { return objectiveFunction(xPixel, yPixel, xScale(xValue(d)), yScale(yValue(d))); })[1]; return { datum: nearest, x: nearest ? xScale(xValue(nearest)) : xPixel, y: nearest ? yScale(yValue(nearest)) : yPixel }; }; } function seriesPointSnap(series, data, objectiveFunction) { return function (xPixel, yPixel) { var xScale = series.xScale(), yScale = series.yScale(), xValue = series.xValue(), yValue = (series.yValue || series.yCloseValue).call(series); return pointSnap(xScale, yScale, xValue, yValue, data, objectiveFunction)(xPixel, yPixel); }; } function seriesPointSnapXOnly(series, data) { function objectiveFunction(x, y, cx, cy) { var dx = x - cx; return Math.abs(dx); } return seriesPointSnap(series, data, objectiveFunction); } function seriesPointSnapYOnly(series, data) { function objectiveFunction(x, y, cx, cy) { var dy = y - cy; return Math.abs(dy); } return seriesPointSnap(series, data, objectiveFunction); } function crosshair () { var event = d3.dispatch('trackingstart', 'trackingmove', 'trackingend'), xScale = d3.time.scale(), yScale = d3.scale.linear(), snap = function snap(_x, _y) { return noSnap(xScale, yScale)(_x, _y); }, decorate = noop; var x = function x(d) { return d.x; }, y = function y(d) { return d.y; }; var dataJoin$$ = dataJoin().children(true).selector('g.crosshair').element('g').attr('class', 'crosshair'); var pointSeries = point().xValue(x).yValue(y); var horizontalLine = line().value(y).label(function (d) { return d.y; }); var verticalLine = line().orient('vertical').value(x).label(function (d) { return d.x; }); // the line annotations used to render the crosshair are positioned using // screen coordinates. This function constructs a suitable scale for rendering // these annotations. function identityScale(scale) { return d3.scale.identity().range(range(scale)); } var crosshair = function crosshair(selection) { selection.each(function (data, index) { var container = d3.select(this).style('pointer-events', 'all').on('mouseenter.crosshair', mouseenter).on('mousemove.crosshair', mousemove).on('wheel.crosshair', mousemove).on('mouseleave.crosshair', mouseleave); var overlay = container.selectAll('rect').data([data]); overlay.enter().append('rect').style('visibility', 'hidden'); container.select('rect').attr('x', range(xScale)[0]).attr('y', range(yScale)[1]).attr('width', range(xScale)[1]).attr('height', range(yScale)[0]); var crosshairElement = dataJoin$$(container, data); crosshairElement.enter().style('pointer-events', 'none'); var multi = _multi().series([horizontalLine, verticalLine, pointSeries]).xScale(identityScale(xScale)).yScale(identityScale(yScale)).mapping(function () { return [this]; }); crosshairElement.call(multi); decorate(crosshairElement, data, index); }); }; function mouseenter() { var mouse = d3.mouse(this); var container = d3.select(this); var snapped = snap.apply(this, mouse); var data = container.datum(); data.push(snapped); container.call(crosshair); event.trackingstart.apply(this, arguments); } function mousemove() { var mouse = d3.mouse(this); var container = d3.select(this); var snapped = snap.apply(this, mouse); var data = container.datum(); data[data.length - 1] = snapped; container.call(crosshair); event.trackingmove.apply(this, arguments); } function mouseleave() { var container = d3.select(this); var data = container.datum(); data.pop(); container.call(crosshair); event.trackingend.apply(this, arguments); } crosshair.xScale = function (_x) { if (!arguments.length) { return xScale; } xScale = _x; return crosshair; }; crosshair.yScale = function (_x) { if (!arguments.length) { return yScale; } yScale = _x; return crosshair; }; crosshair.snap = function (_x) { if (!arguments.length) { return snap; } snap = _x; return crosshair; }; crosshair.decorate = function (_x) { if (!arguments.length) { return decorate; } decorate = _x; return crosshair; }; d3.rebind(crosshair, event, 'on'); var lineIncludes = include('label'); rebindAll(crosshair, horizontalLine, lineIncludes, prefix('y')); rebindAll(crosshair, verticalLine, lineIncludes, prefix('x')); return crosshair; } function fibonacciFan () { var event = d3.dispatch('fansource', 'fantarget', 'fanclear'), xScale = d3.time.scale(), yScale = d3.scale.linear(), snap = function snap(_x, _y) { return noSnap(xScale, yScale)(_x, _y); }, decorate = noop; var x = function x(d) { return d.x; }, y = function y(d) { return d.y; }; var dataJoin$$ = dataJoin().selector('g.fan').element('g').attr('class', 'fan'); var fan = function fan(selection) { selection.each(function (data, index) { var container = d3.select(this).style('pointer-events', 'all').on('mouseenter.fan', mouseenter); var overlay = container.selectAll('rect').data([data]); overlay.enter().append('rect').style('visibility', 'hidden'); container.select('rect').attr('x', xScale.range()[0]).attr('y', yScale.range()[1]).attr('width', xScale.range()[1]).attr('height', yScale.range()[0]); var g = dataJoin$$(container, data); g.each(function (d) { d.x = xScale.range()[1]; d.ay = d.by = d.cy = y(d.target); if (x(d.source) !== x(d.target)) { if (d.state === 'DONE' && x(d.source) > x(d.target)) { var temp = d.source; d.source = d.target; d.target = temp; } var gradient = (y(d.target) - y(d.source)) / (x(d.target) - x(d.source)); var deltaX = d.x - x(d.source); var deltaY = gradient * deltaX; d.ay = 0.618 * deltaY + y(d.source); d.by = 0.500 * deltaY + y(d.source); d.cy = 0.382 * deltaY + y(d.source); } }); var enter = g.enter(); enter.append('line').attr('class', 'trend'); enter.append('line').attr('class', 'a'); enter.append('line').attr('class', 'b'); enter.append('line').attr('class', 'c'); enter.append('polygon').attr('class', 'area'); g.select('line.trend').attr('x1', function (d) { return x(d.source); }).attr('y1', function (d) { return y(d.source); }).attr('x2', function (d) { return x(d.target); }).attr('y2', function (d) { return y(d.target); }); g.select('line.a').attr('x1', function (d) { return x(d.source); }).attr('y1', function (d) { return y(d.source); }).attr('x2', function (d) { return d.x; }).attr('y2', function (d) { return d.ay; }).style('visibility', function (d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; }); g.select('line.b').attr('x1', function (d) { return x(d.source); }).attr('y1', function (d) { return y(d.source); }).attr('x2', function (d) { return d.x; }).attr('y2', function (d) { return d.by; }).style('visibility', function (d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; }); g.select('line.c').attr('x1', function (d) { return x(d.source); }).attr('y1', function (d) { return y(d.source); }).attr('x2', function (d) { return d.x; }).attr('y2', function (d) { return d.cy; }).style('visibility', function (d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; }); g.select('polygon.area').attr('points', function (d) { return x(d.source) + ',' + y(d.source) + ' ' + d.x + ',' + d.ay + ' ' + d.x + ',' + d.cy; }).style('visibility', function (d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; }); decorate(g, data, index); }); }; function updatePositions() { var container = d3.select(this); var datum = container.datum()[0]; if (datum.state !== 'DONE') { var mouse = d3.mouse(this); var snapped = snap.apply(this, mouse); if (datum.state === 'SELECT_SOURCE') { datum.source = datum.target = snapped; } else if (datum.state === 'SELECT_TARGET') { datum.target = snapped; } else { throw new Error('Unknown state ' + datum.state); } } } function mouseenter() { var container = d3.select(this).on('click.fan', mouseclick).on('mousemove.fan', mousemove).on('mouseleave.fan', mouseleave); var data = container.datum(); if (data[0] == null) { data.push({ state: 'SELECT_SOURCE' }); } updatePositions.call(this); container.call(fan); } function mousemove() { var container = d3.select(this); updatePositions.call(this); container.call(fan); } function mouseleave() { var container = d3.select(this); var data = container.datum(); if (data[0] != null && data[0].state === 'SELECT_SOURCE') { data.pop(); } container.on('click.fan', null).on('mousemove.fan', null).on('mouseleave.fan', null); } function mouseclick() { var container = d3.select(this); var datum = container.datum()[0]; switch (datum.state) { case 'SELECT_SOURCE': updatePositions.call(this); event.fansource.apply(this, arguments); datum.state = 'SELECT_TARGET'; break; case 'SELECT_TARGET': updatePositions.call(this); event.fantarget.apply(this, arguments); datum.state = 'DONE'; break; case 'DONE': event.fanclear.apply(this, arguments); datum.state = 'SELECT_SOURCE'; updatePositions.call(this); break; default: throw new Error('Unknown state ' + datum.state); } container.call(fan); } fan.xScale = function (_x) { if (!arguments.length) { return xScale; } xScale = _x; return fan; }; fan.yScale = function (_x) { if (!arguments.length) { return yScale; } yScale = _x; return fan; }; fan.snap = function (_x) { if (!arguments.length) { return snap; } snap = _x; return fan; }; fan.decorate = function (_x) { if (!arguments.length) { return decorate; } decorate = _x; return fan; }; d3.rebind(fan, event, 'on'); return fan; } function measure () { var event = d3.dispatch('measuresource', 'measuretarget', 'measureclear'), xScale = d3.time.scale(), yScale = d3.scale.linear(), snap = function snap(_x, _y) { return noSnap(xScale, yScale)(_x, _y); }, decorate = noop, xLabel = d3.functor(''), yLabel = d3.functor(''), padding = d3.functor(2); var x = function x(d) { return d.x; }, y = function y(d) { return d.y; }; var dataJoin$$ = dataJoin().selector('g.measure').element('g').attr('class', 'measure'); var measure = function measure(selection) { selection.each(function (data, index) { var container = d3.select(this).style('pointer-events', 'all').on('mouseenter.measure', mouseenter); var overlay = container.selectAll('rect').data([data]); overlay.enter().append('rect').style('visibility', 'hidden'); container.select('rect').attr('x', xScale.range()[0]).attr('y', yScale.range()[1]).attr('width', xScale.range()[1]).attr('height', yScale.range()[0]); var g = dataJoin$$(container, data); var enter = g.enter(); enter.append('line').attr('class', 'tangent'); enter.append('line').attr('class', 'horizontal'); enter.append('line').attr('class', 'vertical'); enter.append('text').attr('class', 'horizontal'); enter.append('text').attr('class', 'vertical'); g.select('line.tangent').attr('x1', function (d) { return x(d.source); }).attr('y1', function (d) { return y(d.source); }).attr('x2', function (d) { return x(d.target); }).attr('y2', function (d) { return y(d.target); }); g.select('line.horizontal').attr('x1', function (d) { return x(d.source); }).attr('y1', function (d) { return y(d.source); }).attr('x2', function (d) { return x(d.target); }).attr('y2', function (d) { return y(d.source); }).style('visibility', function (d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; }); g.select('line.vertical').attr('x1', function (d) { return x(d.target); }).attr('y1', function (d) { return y(d.target); }).attr('x2', function (d) { return x(d.target); }).attr('y2', function (d) { return y(d.source); }).style('visibility', function (d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; }); var paddingValue = padding.apply(this, arguments); g.select('text.horizontal').attr('x', function (d) { return x(d.source) + (x(d.target) - x(d.source)) / 2; }).attr('y', function (d) { return y(d.source) - paddingValue; }).style('visibility', function (d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; }).text(xLabel); g.select('text.vertical').attr('x', function (d) { return x(d.target) + paddingValue; }).attr('y', function (d) { return y(d.source) + (y(d.target) - y(d.source)) / 2; }).style('visibility', function (d) { return d.state !== 'DONE' ? 'hidden' : 'visible'; }).text(yLabel); decorate(g, data, index); }); }; function updatePositions() { var container = d3.select(this); var datum = container.datum()[0]; if (datum.state !== 'DONE') { var mouse = d3.mouse(this); var snapped = snap.apply(this, mouse); if (datum.state === 'SELECT_SOURCE') { datum.source = datum.target = snapped; } else if (datum.state === 'SELECT_TARGET') { datum.target = snapped; } else { throw new Error('Unknown state ' + datum.state); } } } function mouseenter() { var container = d3.select(this).on('click.measure', mouseclick).on('mousemove.measure', mousemove).on('mouseleave.measure', mouseleave); var data = container.datum(); if (data[0] == null) { data.push({ state: 'SELECT_SOURCE' }); } updatePositions.call(this); container.call(measure); } function mousemove() { var container = d3.select(this); updatePositions.call(this); container.call(measure); } function mouseleave() { var container = d3.select(this); var data = container.datum(); if (data[0] != null && data[0].state === 'SELECT_SOURCE') { data.pop(); } container.on('click.measure', null).on('mousemove.measure', null).on('mouseleave.measure', null); } function mouseclick() { var container = d3.select(this); var datum = container.datum()[0]; switch (datum.state) { case 'SELECT_SOURCE': updatePositions.call(this); event.measuresource.apply(this, arguments); datum.state = 'SELECT_TARGET'; break; case 'SELECT_TARGET': updatePositions.call(this); event.measuretarget.apply(this, arguments); datum.state = 'DONE'; break; case 'DONE': event.measureclear.apply(this, arguments); datum.state = 'SELECT_SOURCE'; updatePositions.call(this); break; default: throw new Error('Unknown state ' + datum.state); } container.call(measure); } measure.xScale = function (_x) { if (!arguments.length) { return xScale; } xScale = _x; return measure; }; measure.yScale = function (_x) { if (!arguments.length) { return yScale; } yScale = _x; return measure; }; measure.snap = function (_x) { if (!arguments.length) { return snap; } snap = _x; return measure; }; measure.decorate = function (_x) { if (!arguments.length) { return decorate; } decorate = _x; return measure; }; measure.xLabel = function (_x) { if (!arguments.length) { return xLabel; } xLabel = d3.functor(_x); return measure; }; measure.yLabel = function (_x) { if (!arguments.length) { return yLabel; } yLabel = d3.functor(_x); return measure; }; measure.padding = function (_x) { if (!arguments.length) { return padding; } padding = d3.functor(_x); return measure; }; d3.rebind(measure, event, 'on'); return measure; } function container () { var padding = 0, component = noop, decorate = noop; var dataJoin$$ = dataJoin().selector('g.container').element('g').attr({ 'class': 'container', 'layout-style': 'flex: 1' }); var container = function container(selection) { selection.each(function (data, index) { var expandedPadding = expandRect(padding); var g = dataJoin$$(this, [data]); g.enter().append('rect').layout('flex', 1); g.enter().append('g').layout({ position: 'absolute', top: expandedPadding.top, left: expandedPadding.left, bottom: expandedPadding.bottom, right: expandedPadding.right }); d3.select(this).layout(); g.select('g').call(component); decorate(g, data, index); }); }; container.decorate = function (x) { if (!arguments.length) { return decorate; } decorate = x; return container; }; container.padding = function (x) { if (!arguments.length) { return padding; } padding = x; return container; }; container.component = function (x) { if (!arguments.length) { return component; } component = x; return container; }; return container; } var tool = { crosshair: crosshair, fibonacciFan: fibonacciFan, container: container, measure: measure }; /** * The extent function enhances the functionality of the equivalent D3 extent function, allowing * you to pass an array of fields, or accessors, which will be used to derive the extent of the supplied array. For * example, if you have an array of items with properties of 'high' and 'low', you * can use <code>fc.util.extent().fields(['high', 'low'])(data)</code> to compute the extent of your data. * * @memberof fc.util */ function extent$2 () { var fields = [], extraPoints = [], padUnit = 'percent', pad = 0, symmetricalAbout = null; /** * @param {array} data an array of data points, or an array of arrays of data points */ var extents = function extents(data) { // we need an array of arrays if we don't have one already if (!Array.isArray(data[0])) { data = [data]; } // the fields can be a mixed array of property names or accessor functions var mutatedFields = fields.map(function (field) { if (typeof field !== 'string') { return field; } return function (d) { return d[field]; }; }); var dataMin = d3.min(data, function (d0) { return d3.min(d0, function (d1) { return d3.min(mutatedFields.map(function (f) { return f(d1); })); }); }); var dataMax = d3.max(data, function (d0) { return d3.max(d0, function (d1) { return d3.max(mutatedFields.map(function (f) { return f(d1); })); }); }); var dateExtent = Object.prototype.toString.call(dataMin) === '[object Date]'; var min = dateExtent ? dataMin.getTime() : dataMin; var max = dateExtent ? dataMax.getTime() : dataMax; // apply symmetry rules if (symmetricalAbout != null) { var symmetrical = dateExtent ? symmetricalAbout.getTime() : symmetricalAbout; var distanceFromMax = Math.abs(max - symmetrical), distanceFromMin = Math.abs(min - symmetrical), halfRange = Math.max(distanceFromMax, distanceFromMin); min = symmetrical - halfRange; max = symmetrical + halfRange; } if (padUnit === 'domain') { // pad absolutely if (Array.isArray(pad)) { min -= pad[0]; max += pad[1]; } else { min -= pad; max += pad; } } else if (padUnit === 'percent') { // pad percentagely if (Array.isArray(pad)) { var deltaArray = [pad[0] * (max - min), pad[1] * (max - min)]; min -= deltaArray[0]; max += deltaArray[1]; } else { var delta = pad * (max - min) / 2; min -= delta; max += delta; } } if (extraPoints.length) { min = Math.min(min, d3.min(extraPoints)); max = Math.max(max, d3.max(extraPoints)); } if (dateExtent) { min = new Date(min); max = new Date(max); } // Return the smallest and largest return [min, max]; }; /* * @param {array} fields the names of object properties that represent field values, or accessor functions. */ extents.fields = function (x) { if (!arguments.length) { return fields; } fields = x; return extents; }; extents.include = function (x) { if (!arguments.length) { return extraPoints; } extraPoints = x; return extents; }; extents.padUnit = function (x) { if (!arguments.length) { return padUnit; } padUnit = x; return extents; }; extents.pad = function (x) { if (!arguments.length) { return pad; } pad = x; return extents; }; extents.symmetricalAbout = function (x) { if (!arguments.length) { return symmetricalAbout; } symmetricalAbout = x; return extents; }; return extents; } /* global requestAnimationFrame:false */ // Debounce render to only occur once per frame function render (renderInternal) { var rafId = null; return function () { if (rafId == null) { rafId = requestAnimationFrame(function () { rafId = null; renderInternal(); }); } }; } function randomItem$1(array) { return array[randomIndex$1(array)]; } function randomIndex$1(array) { return Math.floor(Math.random() * array.length); } function cloneAndReplace$1(array, index, replacement) { var clone = array.slice(); clone[index] = replacement; return clone; } var array = Object.freeze({ randomItem: randomItem$1, randomIndex: randomIndex$1, cloneAndReplace: cloneAndReplace$1 }); function percentageChange () { var baseIndex = d3.functor(0), value = identity; var percentageChange = function percentageChange(data) { if (data.length === 0) { return []; } var baseValue = value(data[baseIndex(data)]); return data.map(function (d, i) { return (value(d, i) - baseValue) / baseValue; }); }; percentageChange.baseIndex = function (x) { if (!arguments.length) { return baseIndex; } baseIndex = d3.functor(x); return percentageChange; }; percentageChange.value = function (x) { if (!arguments.length) { return value; } value = x; return percentageChange; }; return percentageChange; } var util = { dataJoin: dataJoin, expandRect: expandRect, extent: extent$2, fn: fn, minimum: minimum$1, fractionalBarWidth: fractionalBarWidth, innerDimensions: innerDimensions, scale: scale, noSnap: noSnap, pointSnap: pointSnap, seriesPointSnap: seriesPointSnap, seriesPointSnapXOnly: seriesPointSnapXOnly, seriesPointSnapYOnly: seriesPointSnapYOnly, render: render, array: array, percentageChange: percentageChange }; var fc = { annotation: annotation, chart: chart, data: data, indicator: indicator, scale: scale$1, series: series, svg: svg, tool: tool, util: util, layout: layout }; return fc; }));
app/react-icons/fa/heart-o.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaHeartO extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m37.1 13.3q0-1.8-0.4-3.2t-1.3-2.2-1.8-1.3-2.1-0.7-2.2-0.2-2.5 0.6-2.4 1.4-2 1.6-1.3 1.4q-0.4 0.5-1.1 0.5t-1.1-0.5q-0.5-0.6-1.3-1.4t-2-1.6-2.4-1.4-2.5-0.6-2.2 0.2-2.1 0.7-1.8 1.3-1.3 2.2-0.4 3.2q0 3.8 4.1 7.9l13 12.5 12.9-12.4q4.2-4.2 4.2-8z m2.9 0q0 4.9-5.1 10l-13.9 13.4q-0.4 0.4-1 0.4t-1-0.4l-13.9-13.4q-0.2-0.2-0.6-0.6t-1.3-1.4-1.5-2.2-1.2-2.7-0.5-3.1q0-4.9 2.8-7.7t7.9-2.7q1.4 0 2.8 0.4t2.7 1.3 2.1 1.6 1.7 1.5q0.8-0.8 1.7-1.5t2.1-1.6 2.7-1.3 2.8-0.4q5 0 7.9 2.7t2.8 7.7z"/></g> </IconBase> ); } }
ajax/libs/rxjs/2.3.1/rx.all.compat.js
tharakauka/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; }; // 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; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == 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 Object.prototype.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 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; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * 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); }; /** * 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) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (!onError) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(selector) { return this.map(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } function concatMapObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).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.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.selectConcat = observableProto.concatMap = function (selector, resultSelector) { 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); }); }); } if (typeof selector === 'function') { return concatMap.call(this, selector); } return concatMap.call(this, function () { return selector; }); }; /** * 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)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var map = new Dictionary(), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key, i, len, items; try { key = keySelector(x); } catch (e) { items = map.getValues(); for (i = 0, len = items.length; i < len; i++) { items[i].onError(e); } observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { items = map.getValues(); for (i = 0, len = items.length; i < len; i++) { items[i].onError(e); } observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { items = map.getValues(); for (i = 0, len = items.length; i < len; i++) { items[i].onError(exn); } observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { items = map.getValues(); for (i = 0, len = items.length; i < len; i++) { items[i].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { var items = map.getValues(); for(var i = 0, len = items.length; i < len; i++) { items[i].onError(ex); } observer.onError(ex); }, function () { var items = map.getValues(); for(var i = 0, len = items.length; i < len; i++) { items[i].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } function selectManyObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param 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 = 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)); }); }; 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(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(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 a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * 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. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @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 = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * * @memberOf Observable# * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().select(function (b) { return !b; }); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @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 = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @example * 1 - res = source.contains(42); * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); * @param value The value to locate in the source sequence. * @param {Function} [comparer] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. */ observableProto.contains = function (value, comparer) { comparer || (comparer = defaultComparer); return this.where(function (v) { return comparer(v, value); }).any(); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * 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. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { if (count < len) { equal = comparer(value, second[count++]); } } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * 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); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal, v; if (ql.length > 0) { v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * 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. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate? this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue) }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * 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); }; /** * 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. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var 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); }); }; }; /** * 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); }); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(name, handler); }); } // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (typeof el.item === 'function' && typeof el.length === 'number') { 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; } // 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'; /** * 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) { 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(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.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 = [], previous = true; var subscription = combineLatestSource( this.source, this.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; } }, 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(); } ); this.subject.onNext(false); return subscription; } function PausableBufferedObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.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)); /** * 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 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 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)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription; this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(source.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)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof obj === 'string') { return stringHashFn(valueOf); } } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new Error('out of range'); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { return this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), leftDone = false, leftId = 0, leftMap = new Dictionary(), rightDone = false, rightId = 0, rightMap = new Dictionary(); group.add(left.subscribe(function (value) { var duration, expire, id = leftId++, md = new SingleAssignmentDisposable(), result, values; leftMap.add(id, value); group.add(md); expire = function () { if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) { observer.onCompleted(); } return group.remove(md); }; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); values = rightMap.getValues(); for (var i = 0; i < values.length; i++) { try { result = resultSelector(value, values[i]); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); } }, observer.onError.bind(observer), function () { leftDone = true; if (rightDone || leftMap.count() === 0) { observer.onCompleted(); } })); group.add(right.subscribe(function (value) { var duration, expire, id = rightId++, md = new SingleAssignmentDisposable(), result, values; rightMap.add(id, value); group.add(md); expire = function () { if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) { observer.onCompleted(); } return group.remove(md); }; try { duration = rightDurationSelector(value); } catch (exception) { observer.onError(exception); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); values = leftMap.getValues(); for (var i = 0; i < values.length; i++) { try { result = resultSelector(values[i], value); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); } }, observer.onError.bind(observer), function () { rightDone = true; if (leftDone || rightMap.count() === 0) { observer.onCompleted(); } })); return group; }); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var nothing = function () {}; var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(); var rightMap = new Dictionary(); var leftID = 0; var rightID = 0; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftID++; leftMap.add(id, s); var i, len, leftValues, rightValues; var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } observer.onNext(result); rightValues = rightMap.getValues(); for (i = 0, len = rightValues.length; i < len; i++) { s.onNext(rightValues[i]); } var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { if (leftMap.remove(id)) { s.onCompleted(); } group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( nothing, function (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, expire) ); }, function (e) { var leftValues = leftMap.getValues(); for (var i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, observer.onCompleted.bind(observer))); group.add(right.subscribe( function (value) { var leftValues, i, len; var id = rightID++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( nothing, function (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, expire) ); leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onNext(value); } }, function (e) { var leftValues = leftMap.getValues(); for (var i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); })); return r; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.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, function () { return observableEmpty(); }, function (_, window) { return window; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var window = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); d.add(windowBoundaries.subscribe(function (w) { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var createWindowClose, m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), window = new Subject(); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); observer.onCompleted(); })); createWindowClose = function () { var m1, windowClose; try { windowClose = windowClosingSelector(); } catch (exception) { observer.onError(exception); return; } m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); createWindowClose(); })); }; createWindowClose(); return r; }); } /** * 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)); }); }; /** * 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) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector) { return enumerableFor(sources, resultSelector).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * 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 = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = (function () { /** * @constructor * @private */ function Map() { this.keys = []; this.values = []; } /** * @private * @memberOf Map# */ Map.prototype['delete'] = function (key) { var i = this.keys.indexOf(key); if (i !== -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } return i !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.get = function (key, fallback) { var i = this.keys.indexOf(key); return i !== -1 ? this.values[i] : fallback; }; /** * @private * @memberOf Map# */ Map.prototype.set = function (key, value) { var i = this.keys.indexOf(key); if (i !== -1) { this.values[i] = value; } this.values[this.keys.push(key) - 1] = value; }; /** * @private * @memberOf Map# */ Map.prototype.size = function () { return this.keys.length; }; /** * @private * @memberOf Map# */ Map.prototype.has = function (key) { return this.keys.indexOf(key) !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.getKeys = function () { return this.keys.slice(0); }; /** * @private * @memberOf Map# */ Map.prototype.getValues = function () { return this.values.slice(0); }; 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 object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { var patterns = this.patterns.slice(0); patterns.push(other); return new Pattern(patterns); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * * @param 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 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 (exception) { observer.onError(exception); 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; } // Active Plan function ActivePlan(joinObserverArray, onNext, onCompleted) { var i, joinObserver; this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (i = 0; i < this.joinObserverArray.length; i++) { joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { var values = this.joinObservers.getValues(); for (var i = 0, len = values.length; i < len; i++) { values[i].queue.shift(); } }; ActivePlan.prototype.match = function () { var firstValues, i, len, isCompleted, values, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { firstValues = []; isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); if (this.joinObserverArray[i].queue[0].kind === 'C') { isCompleted = true; } } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); values = []; for (i = 0; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; /** @private */ var JoinObserver = (function (_super) { inherits(JoinObserver, _super); /** * @constructor * @private */ 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; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.error = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.completed = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.removeActivePlan = function (activePlan) { var idx = this.activePlans.indexOf(activePlan); this.activePlans.splice(idx, 1); if (this.activePlans.length === 0) { this.dispose(); } }; /** * @memberOf JoinObserver# * @private */ 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 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 plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(), group, i, len, joinObserver, joinValues, outObserver; outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { var values = externalSubscriptions.getValues(); for (var j = 0, jlen = values.length; j < jlen; j++) { values[j].onError(exception); } observer.onError(exception); }, observer.onCompleted.bind(observer)); try { for (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); if (activePlans.length === 0) { outObserver.onCompleted(); } })); } } catch (e) { observableThrow(e).subscribe(observer); } group = new CompositeDisposable(); joinValues = externalSubscriptions.getValues(); for (i = 0, len = joinValues.length; i < len; i++) { joinObserver = joinValues[i]; joinObserver.subscribe(); group.add(joinObserver); } return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { var p = normalizeTime(period); return new AnonymousObservable(function (observer) { var count = 0, d = dueTime; return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { var now; if (p > 0) { now = scheduler.now(); d = d + p; if (d <= now) { d = now + p; } } observer.onNext(count++); self(d); }); }); } 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) { 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); }) }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (typeof timeShiftOrScheduler === 'object') { 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); q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; 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; isSpan && (nextSpan += timeShift); isShift && (nextShift += timeShift); m.setDisposable(scheduler.scheduleWithRelative(ts, function () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); } }); }; /** * 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. * @example * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items * * @memberOf Observable# * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var createTimer, groupDisposable, n = 0, refCountDisposable, s = new Subject() timerD = new SerialDisposable(), windowId = 0; groupDisposable = new CompositeDisposable(timerD); refCountDisposable = new RefCountDisposable(groupDisposable); observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe(function (x) { var newId = 0, newWindow = false; s.onNext(x); n++; 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; function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { var newId; if (id !== windowId) { return; } n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * 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); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(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} [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; 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(), 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; 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))); }); }; /** * 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]); * 2 - res = source.skipUntilWithTime(5000, [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) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * 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]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (_super) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, _super); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { var next; if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null) { if (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 next; var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { if (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); var dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } 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 Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { var next; while (this.queue.length > 0) { next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this, run = function (scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); }, si = new ScheduledItem(self, state, run, dueTime, self.comparer); self.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; }; /** * @private */ HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { 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 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 GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * 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)); 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/main/app/scripts/components/Siderbar.js
ondrejhudek/hudy-app
import React from 'react' import { LeftNav } from 'material-ui' import FontAwesome from 'react-fontawesome' import Menu from '../components/Menu' class Sidebar extends React.Component { constructor(props) { super(props) this.state = { open: true } } render() { return ( <LeftNav open={this.state.open} className="sidebar"> <header> <h1> <FontAwesome name="thumb-tack" className="app-icon"/> pinboard <small>beta</small> </h1> </header> <Menu/> <footer> <p className="copyright"> &copy; 2016 Made with <FontAwesome name="heart"/> by Ondřej Hudek </p> <p className="github"> <a href="https://github.com/ondrejhudek/hudy-app"> <FontAwesome name="github" size="3x"/> </a> </p> </footer> </LeftNav> ) } } export default Sidebar
src/svg-icons/action/backup.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBackup = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/> </SvgIcon> ); ActionBackup = pure(ActionBackup); ActionBackup.displayName = 'ActionBackup'; ActionBackup.muiName = 'SvgIcon'; export default ActionBackup;
packages/material-ui-icons/src/Drafts.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M21.99 8c0-.72-.37-1.35-.94-1.7L12 1 2.95 6.3C2.38 6.65 2 7.28 2 8v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2l-.01-10zM12 13L3.74 7.84 12 3l8.26 4.84L12 13z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment> , 'Drafts');
packages/mui-icons-material/lib/DnsOutlined.js
oliviertassinari/material-ui
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M19 15v4H5v-4h14m1-2H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-6c0-.55-.45-1-1-1zM7 18.5c-.82 0-1.5-.67-1.5-1.5s.68-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM19 5v4H5V5h14m1-2H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1zM7 8.5c-.82 0-1.5-.67-1.5-1.5S6.18 5.5 7 5.5s1.5.68 1.5 1.5S7.83 8.5 7 8.5z" }), 'DnsOutlined'); exports.default = _default;
codes/chapter05/react-router-official/demo03/app/index.js
atlantis1024/react-step-by-step
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App/>, document.getElementById("root"));
packages/strapi-admin/files/public/app/containers/Content/index.js
skelpook/strapi
/* * * Content * */ import React from 'react'; import { connect } from 'react-redux'; import styles from './styles.scss'; import { createSelector } from 'reselect'; import { selectPlugins } from 'containers/App/selectors'; export class Content extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div className={styles.content}> {React.Children.toArray(this.props.children)} </div> ); } } Content.propTypes = { plugins: React.PropTypes.object, onRegisterPluginClicked: React.PropTypes.func, params: React.PropTypes.object, }; const mapStateToProps = createSelector( selectPlugins(), (plugins) => ({ plugins }) ); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(Content);
js/jquery-1.11.1.js
digitalbliss/sameheightplugin
/*! * 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; }));
packages/material-ui-icons/src/Brightness5Rounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 15.31l2.6-2.6c.39-.39.39-1.02 0-1.41L20 8.69V5c0-.55-.45-1-1-1h-3.69l-2.6-2.6a.9959.9959 0 00-1.41 0L8.69 4H5c-.55 0-1 .45-1 1v3.69l-2.6 2.6c-.39.39-.39 1.02 0 1.41L4 15.3V19c0 .55.45 1 1 1h3.69l2.6 2.6c.39.39 1.02.39 1.41 0l2.6-2.6H19c.55 0 1-.45 1-1v-3.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z" /> , 'Brightness5Rounded');
ajax/libs/highstock/2.1.3/highstock.src.js
KyleMit/cdnjs
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highstock JS v2.1.3 (2015-02-27) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ /*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /(msie|trident)/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () { return UNDEFINED; }, charts = [], chartCount = 0, PRODUCT = 'Highstock', VERSION = '2.1.3', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'], // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getTimezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; // The Highcharts namespace Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {}; Highcharts.seriesTypes = seriesTypes; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ var extend = Highcharts.extend = function (a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; }; /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return obj && typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ var pick = Highcharts.pick = function () { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== UNDEFINED && arg !== null) { return arg; } } }; /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () { return UNDEFINED; }; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ var wrap = Highcharts.wrap = function (obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; }; function getTZOffset(timestamp) { return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - getTZOffset(timestamp)), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 'w': day, // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = Highcharts.numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) { var normalized, i, retInterval = interval; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { retInterval = multiples[i]; if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) { break; } } // multiply back to the correct magnitude retInterval *= magnitude; return retInterval; } /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error (code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } // else ... if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 28 * 24 * 3600000, year: 364 * 24 * 3600000 }; /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ Highcharts.numberFormat = function (number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = +number || 0, c = decimals === -1 ? mathMin((n.toString().split('.')[1] || '').length, 20) : // Preserve decimals. Not huge numbers (#3793). (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(n).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "")); }; /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Fx.step, base; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && $.Tween) { // jQuery 1.8 model obj = $.Tween.propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { var elem; // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // Don't run animations on textual properties like align (#1821) if (fx.prop === 'align') { return; } // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) this.addAnimSetter('d', function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // Interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }); /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i, len = arr.length; for (i = 0; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (this[0]) { if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } } return ret; }; }, /** * Add an animation setter for a specific property */ addAnimSetter: function (prop, setter) { // jQuery 1.8 style if ($.Tween) { $.Tween.propHooks[prop] = { set: setter }; // pre 1.8 } else { $.fx.step[prop] = setter; } }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; delete eventArguments.returnValue; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161) } el.hasAnim = 1; // #3342 $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy $(el).stop(); } } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = Highcharts.each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ' ' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/stock/2.1.3/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/stock/2.1.3/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: { align: 'center', // defer: true, // enabled: false, formatter: function () { return this.y === null ? '' : Highcharts.numberFormat(this.y, -1); }, style: { color: 'contrast', fontSize: '11px', fontWeight: 'bold', textShadow: '0 0 6px contrast, 0 0 3px contrast' }, verticalAlign: 'bottom', // above singular point x: 0, y: 0, // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, padding: 5 // shadow: false }, cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, footerFormat: '', //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var globalOptions = defaultOptions.global, useUTC = globalOptions.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; Date = globalOptions.Date || window.Date; timezoneOffset = useUTC && globalOptions.timezoneOffset; getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset; makeTime = function (year, month, date, hours, minutes, seconds) { var d; if (useUTC) { d = Date.UTC.apply(0, arguments); d += getTZOffset(d); } else { d = new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); } return d; }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = rgbaRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = hexRegEx.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = rgbRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions, {}); //#2625 if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')'); } }, /** * Apply a polyfill to the text-stroke CSS property, by copying the text element * and apply strokes to the copy. * * docs: update default, document the polyfill and the limitations on hex colors and pixel values, document contrast pseudo-color * TODO: * - update defaults */ applyTextShadow: function (textShadow) { var elem = this.element, tspans, hasContrast = textShadow.indexOf('contrast') !== -1, // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check // this again with new IE release. In exports, the rendering is passed to PhantomJS. supports = this.renderer.forExport || (elem.style.textShadow !== UNDEFINED && !isIE); // When the text shadow is set to contrast, use dark stroke for light text and vice versa if (hasContrast) { textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill)); } /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/) if (elem.textContent.indexOf('2.') === 0) { elem.style['text-shadow'] = 'none'; supports = false; } // */ // No reason to polyfill, we've got native support if (supports) { if (hasContrast) { // Apply the altered style css(elem, { textShadow: textShadow }); } } else { this.fakeTS = true; // Fake text shadow // In order to get the right y position of the clones, // copy over the y setter this.ySetter = this.xSetter; tspans = [].slice.call(elem.getElementsByTagName('tspan')); each(textShadow.split(/\s?,\s?/g), function (textShadow) { var firstChild = elem.firstChild, color, strokeWidth; textShadow = textShadow.split(' '); color = textShadow[textShadow.length - 1]; // Approximately tune the settings to the text-shadow behaviour strokeWidth = textShadow[textShadow.length - 2]; if (strokeWidth) { each(tspans, function (tspan, y) { var clone; // Let the first line start at the correct X position if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); y = elem.getAttribute('y'); tspan.setAttribute('y', y || 0); if (y === null) { elem.setAttribute('y', 0); } } // Create the clone and apply shadow properties clone = tspan.cloneNode(1); attr(clone, { 'class': PREFIX + 'text-shadow', 'fill': color, 'stroke': color, 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3), 'stroke-width': strokeWidth, 'stroke-linejoin': 'round' }); elem.insertBefore(clone, firstChild); }); } }); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element); } // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } return ret; }, updateShadows: function (key, value) { var shadows = this.shadows, i = shadows.length; while (i--) { shadows[i].setAttribute( key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) || elemWrapper.textWidth; // #3501 // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { css(elemWrapper.element, styles); } else { /*jslint unparam: true*/ hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); // Delete bBox memo when the rotation changes //delete wrapper.bBox; } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function (reload) { var wrapper = this, bBox,// = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad, textStr = wrapper.textStr, textShadow, elemStyle = element.style, toggleTextShadowShim, cacheKey; if (textStr !== UNDEFINED) { // Properties that affect bounding box cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(','); // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num:' + textStr.toString().length + cacheKey; // Caching all strings reduces rendering time by 4-5%. } else { cacheKey = textStr + cacheKey; } } if (cacheKey && !reload) { bBox = renderer.cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. // When the text shadow shim is used, we need to hide the fake shadows // to get the correct bounding box (#3872) toggleTextShadowShim = this.fakeTS && function (display) { each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) { tspan.style.display = display; }); }; // Workaround for #3842, Firefox reporting wrong bounding box for shadows if (isFirefox && elemStyle.textShadow) { textShadow = elemStyle.textShadow; elemStyle.textShadow = ''; } else if (toggleTextShadowShim) { toggleTextShadowShim(NONE); } bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; // #3842 if (textShadow) { elemStyle.textShadow = textShadow; } else if (toggleTextShadowShim) { toggleTextShadowShim(''); } } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it renderer.cache[cacheKey] = bBox; } return bBox; }, /** * Show the element */ show: function (inherit) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881) if (inherit && this.element.namespaceURI === SVG_NS) { this.element.removeAttribute('visibility'); } else { this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); } return this; }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, element = this.element, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // Mark as added this.added = true; // If we're adding to renderer root, or other elements in the group // have a z index, we need to handle it if (!parent || parent.handleZ || this.zIndex) { inserted = this.zIndexSetter(); } // If zIndex is not handled, append at the end if (!inserted) { (parent ? parent.element : renderer.box).appendChild(element); } // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * this['stroke-width']; } value = value.join(',') .replace('NaN', 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.textContent = (String(pick(value), '')).replace(/<[^>]*>/g, ''); // #3276 #3895 }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, zIndexSetter: function (value, key) { var renderer = this.renderer, parentGroup = this.parentGroup, parentWrapper = parentGroup || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, otherElement, otherZIndex, element = this.element, inserted, i; if (defined(value)) { element.setAttribute(key, value); // So we can read it for other elements in the group this[key] = +value; } // Insert according to this and other elements' zIndex. Before .add() is called, // nothing is done. Then on add, or by later calls to zIndexSetter, the node // is placed on the right place in the DOM. if (this.added) { value = this.zIndex; if (value && parentGroup) { parentGroup.handleZ = true; } childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length && !inserted; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // Insert before the first element with a higher zIndex pInt(otherZIndex) > value || // If no zIndex given, insert before the first element with a zIndex (!defined(value) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; } } if (!inserted) { parentNode.appendChild(element); } } return inserted; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { return (this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style)); }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textShadow = textStyles && textStyles.textShadow, ellipsis = textStyles && textStyles.textOverflow === 'ellipsis', i = childNodes.length, tempParent = width && !wrapper.added && this.box, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }, unescapeAngleBrackets = function (inputStr) { return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr))); return; // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (tempParent) { tempParent.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' '); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } /*if (width) { renderer.breakText(wrapper, width); }*/ // Check width and apply soft breaks or ellipsis if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'), tooLong, wasTooLong, actualWidth, rest = [], dy = getLineHeight(tspan), softLineNo = 1, rotation = wrapper.rotation, wordStr = span, // for ellipsis cursor = wordStr.length, // binary search cursor bBox; while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) { wrapper.rotation = 0; // discard rotation when computing box bBox = wrapper.getBBox(true); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; // For ellipsis, do a binary search for the correct string length if (wasTooLong === undefined) { wasTooLong = tooLong; // First time } if (ellipsis && wasTooLong) { cursor /= 2; if (wordStr === '' || (!tooLong && cursor < 0.5)) { words = []; // All ok, break out } else { if (tooLong) { wasTooLong = true; } wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor)); words = [wordStr + '\u2026']; tspan.removeChild(tspan.firstChild); } // Looping down, this is the first word sequence that is not too long, // so we can move on to build the next line. } else if (!tooLong || words.length === 1) { words = rest; rest = []; if (words.length) { softLineNo++; tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } if (wasTooLong) { wrapper.attr('title', wrapper.textStr); } wrapper.rotation = rotation; } spanNo++; } } }); }); if (tempParent) { tempParent.removeChild(textNode); // attach it to the DOM to read offset width } // Apply the text shadow if (textShadow && wrapper.applyTextShadow) { wrapper.applyTextShadow(textShadow); } } }, /* breakText: function (wrapper, width) { var bBox = wrapper.getBBox(), node = wrapper.element, textLength = node.textContent.length, pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width increment = 0, finalPos; if (bBox.width > width) { while (finalPos === undefined) { textLength = node.getSubStringLength(0, pos); if (textLength <= width) { if (increment === -1) { finalPos = pos; } else { increment = 1; } } else { if (increment === 1) { finalPos = pos - 1; } else { increment = -1; } } pos += increment; } } console.log(finalPos, node.getSubStringLength(0, finalPos)) }, */ /** * Returns white for dark colors and black for bright colors */ getContrast: function (color) { color = Color(color).rgba; return color[0] + color[1] + color[2] > 384 ? '#000' : '#FFF'; }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function () { if (curState !== 3) { callback.call(label); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); wrapper.xSetter = function (value) { this.element.setAttribute('cx', value); }; wrapper.ySetter = function (value) { this.element.setAttribute('cy', value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value) { attr(this.element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]); // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors; x += normalizer; y += normalizer; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; wrapper.count = 0; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { fontSize = fontSize || this.style.fontSize; if (elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement fontSize = win.getComputedStyle(elem, "").fontSize; } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Correct X and Y positioning of a label for rotation (#1764) */ rotCorr: function (baseline, rotation, alterY) { var y = baseline; if (rotation && alterY) { y = mathMax(y * mathCos(rotation * deg2rad), 4); } return { x: (-baseline / 3) * mathSin(rotation * deg2rad), y: y }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) && text.getBBox(); //#3295 && 3514 box failure when string equals 0 wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding); boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.attr('fill', NONE).add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = wrapper.padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } if (styles && styles.textOverflow === 'ellipsis') { styles.whiteSpace = 'nowrap'; styles.overflow = 'hidden'; } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element; // faking getBBox in exported SVG in legacy IE // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows, styles = wrapper.styles; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } width = pick(wrapper.elemWidth, elem.offsetWidth); // Update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: (styles && styles.whiteSpace) || 'normal' // #3331 }); width = textWidth; } wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; }; // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Keep the whiteSpace style outside the wrapper.styles collection element.style.whiteSpace = 'nowrap'; // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, visibilitySetter: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: RELATIVE})); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.cache = {}; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], count: 0, left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; // first call if (!defined(label)) { tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) //.attr(attr) // without position absolute, IE export sometimes is wrong .css(merge(labelOptions.style)) .add(axis.labelGroup) : null; tick.labelLength = label && label.getBBox().width; // Un-rotated length tick.rotation = 0; // Base value to detect change for new calls to getBBox // update } else if (label) { label.attr({ text: str }); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { return this.label ? this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] : 0; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (xy) { var axis = this.axis, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, spacing[3]), rightBound = pick(axis.labelRight, chartWidth - spacing[1]), label = this.label, rotation = this.rotation, factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign], labelWidth = label.getBBox().width, slotWidth = axis.slotWidth, leftPos, rightPos, textWidth; // Check if the label overshoots the chart spacing box. If it does, move it. // If it now overshoots the slotWidth, add ellipsis. if (!rotation) { leftPos = pxPos - factor * labelWidth; rightPos = pxPos + factor * labelWidth; if (leftPos < leftBound) { slotWidth -= leftBound - leftPos; xy.x = leftBound; label.attr({ align: 'left' }); } else if (rightPos > rightBound) { slotWidth -= rightPos - rightBound; xy.x = rightBound; label.attr({ align: 'right' }); } if (labelWidth > slotWidth) { textWidth = slotWidth; } // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) { textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound); } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) { textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad)); } if (textWidth) { label.css({ width: textWidth, textOverflow: 'ellipsis' }); } }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = pick(labelOptions.y, rotCorr.y + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))), line; x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { line = (index / (step || 1) % staggerLines); y += line * (axis.labelOffset / staggerLines); } return { x: x, y: mathRound(y) }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = /*axis.labelStep || */labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { tick.handleOverflow(xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ Highcharts.PlotLineOrBand = function (axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; Highcharts.PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs = {}, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band path = axis.getPlotBandPath(from, to, options); if (color) { attribs.fill = color; } if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; if (label) { plotLine.label = label = label.destroy(); } } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation }; if (defined(zIndex)) { attribs.zIndex = zIndex; } plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .css(optionsLabel.style) .add(); } // get the bounding box and align the label // #3000 changed to better handle choice between plotband or plotline xs = [path[1], path[4], (isBand ? path[6] : path[1])]; ys = [path[2], path[5], (isBand ? path[7] : path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * Object with members for extending the Axis prototype */ AxisPlotLineOrBandExtension = { /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true); if (path && toPath && path.toString() !== toPath.toString()) { // #3836 path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, addPlotBand: function (options) { return this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { return this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new Highcharts.PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ var Axis = Highcharts.Axis = function () { this.init.apply(this, arguments); }; Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#D8D8D8', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: { enabled: true, // rotation: 0, // align: 'center', // step: null, style: { color: '#606060', cursor: 'default', fontSize: '11px' }, x: 0, y: 15 /*formatter: function () { return this.value; },*/ }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return Highcharts.numberFormat(this.total, -1); }, style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' }) } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { autoRotation: [-45], x: 0, y: null // based on font size // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for top axes */ defaultTopAxisOptions: { labels: { autoRotation: [-45], x: 0, y: -15 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = axis.names || []; // Preserve on update (#3830) // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = Highcharts.numberFormat(value, 0); } else { // small numbers ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.ignoreMinPadding = axis.ignoreMaxPadding = null; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, doPostTranslate = (axis.doPostTranslate || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (doPostTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (doPostTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB, /** * Check if x is between a and b. If not, either move to a/b or skip, * depending on the force parameter. */ between = function (x, a, b) { if (x < a || x > b) { if (force) { x = mathMin(mathMax(a, x), b); } else { skip = true; } } return x; }; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; x1 = x2 = between(x1, axisLeft, axisLeft + axis.width); } else { x1 = axisLeft; x2 = cWidth - axis.right; y1 = y2 = between(y1, axisTop, axisTop + axis.height); } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, min = axis.min, max = axis.max, range = max - min, len; // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them. if (range && range / minorTickInterval < axis.len / 3) { // #3875 if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), min, max, options.startOfWeek ) ); } else { for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) { minorTickPositions.push(pos); } } } axis.trimTicks(minorTickPositions); // #3652 #3743 return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (axis.isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (axis.isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); if (!axis.single) { // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); } // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickInterval: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, categories = axis.categories; if (!isDatetimeAxis && !categories && !isLinked) { this.getTickAmount(); } // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) if (axis.pointRange) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange); if (!tickIntervalOption && axis.tickInterval < minTickInterval) { axis.tickInterval = minTickInterval; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 0.5 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount ); } } // Prevent ticks from getting so close that we can't draw the labels if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length axis.tickInterval = axis.unsquish(); } this.setTickPositions(); }, /** * Now we have computed the normalized tickInterval, get the tick positions */ setTickPositions: function () { var options = this.options, tickPositions, tickPositionsOption = options.tickPositions, tickPositioner = options.tickPositioner, startOnTick = options.startOnTick, endOnTick = options.endOnTick, single; // Set the tickmarkOffset this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' && this.tickInterval === 1) ? 0.5 : 0; // #3202 // get minorTickInterval this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ? this.tickInterval / 5 : options.minorTickInterval; // Find the tick positions this.tickPositions = tickPositions = options.tickPositions && options.tickPositions.slice(); // Work on a copy (#1565) if (!tickPositions) { if (this.isDatetimeAxis) { tickPositions = this.getTimeTicks( this.normalizeTimeTickInterval(this.tickInterval, options.units), this.min, this.max, options.startOfWeek, this.ordinalPositions, this.closestPointRange, true ); } else if (this.isLog) { tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max); } else { tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max); } this.tickPositions = tickPositions; // Run the tick positioner callback, that allows modifying auto tick positions. if (tickPositioner) { tickPositioner = tickPositioner.apply(this, [this.min, this.max]); if (tickPositioner) { this.tickPositions = tickPositions = tickPositioner; } } } if (!this.isLinked) { // reset min/max or remove extremes based on start/end on tick this.trimTicks(tickPositions, startOnTick, endOnTick); // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (this.min === this.max && defined(this.min) && !this.tickAmount) { // Substract half a unit (#2619, #2846, #2515, #3390) single = true; this.min -= 0.5; this.max += 0.5; } this.single = single; if (!tickPositionsOption && !tickPositioner) { this.adjustTickAmount(); } } }, /** * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max */ trimTicks: function (tickPositions, startOnTick, endOnTick) { var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = this.minPointOffset || 0; if (startOnTick) { this.min = roundedMin; } else if (this.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (endOnTick) { this.max = roundedMax; } else if (this.max + minPointOffset < roundedMax) { tickPositions.pop(); } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } }, /** * Set the max ticks of either the x and y axis collection */ getTickAmount: function () { var others = {}, // Whether there is another axis to pair with this one hasOther, options = this.options, tickAmount = options.tickAmount, tickPixelInterval = options.tickPixelInterval; if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial && !this.isLog && options.startOnTick && options.endOnTick) { tickAmount = 2; } if (!tickAmount && this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) { // Check if there are multiple axes in the same pane each(this.chart[this.coll], function (axis) { var options = axis.options, horiz = axis.horiz, key = [horiz ? options.left : options.top, horiz ? options.width : options.height, options.pane].join(','); if (others[key]) { hasOther = true; } else { others[key] = 1; } }); if (hasOther) { // Add 1 because 4 tick intervals require 5 ticks (including first and last) tickAmount = mathCeil(this.len / tickPixelInterval) + 1; } } // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This // prevents the axis from adding ticks that are too far away from the data extremes. if (tickAmount < 4) { this.finalTickAmt = tickAmount; tickAmount = 5; } this.tickAmount = tickAmount; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var tickInterval = this.tickInterval, tickPositions = this.tickPositions, tickAmount = this.tickAmount, finalTickAmt = this.finalTickAmt, currentTickAmount = tickPositions && tickPositions.length, i, len; if (currentTickAmount < tickAmount) { // TODO: Check #3411 while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + tickInterval )); } this.transA *= (currentTickAmount - 1) / (tickAmount - 1); this.max = tickPositions[tickPositions.length - 1]; // We have too many ticks, run second pass to try to reduce ticks } else if (currentTickAmount > tickAmount) { this.tickInterval *= 2; this.setTickPositions(); } // The finalTickAmt property is set in getTickAmount if (defined(finalTickAmt)) { i = len = tickPositions.length; while (i--) { if ( (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last ) { tickPositions.splice(i, 1); } } this.finalTickAmt = UNDEFINED; } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickInterval(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (!axis.isXAxis) { if (axis.oldStacks) { stacks = axis.stacks = axis.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true each(axis.series, function (serie) { delete serie.kdTree; }); // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options; // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) { newMin = UNDEFINED; } if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values if (percentRegex.test(height)) { height = parseFloat(height) / 100 * chart.plotHeight; } if (percentRegex.test(top)) { top = parseFloat(top) / 100 * chart.plotHeight + chart.plotTop; } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Prevent the ticks from getting so close we can't draw the labels. On a horizontal * axis, this is handled by rotating the labels, removing ticks and adding ellipsis. * On a vertical axis remove ticks and add ellipsis. */ unsquish: function () { var chart = this.chart, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, tickInterval = this.tickInterval, newTickInterval = tickInterval, slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval), rotation, rotationOption = labelOptions.rotation, labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), step, bestScore = Number.MAX_VALUE, autoRotation, // Return the multiple of tickInterval that is needed to avoid collision getStep = function (spaceNeeded) { var step = spaceNeeded / (slotSize || 1); step = step > 1 ? mathCeil(step) : 1; return step * tickInterval; }; if (horiz) { autoRotation = defined(rotationOption) ? [rotationOption] : slotSize < 80 && !labelOptions.staggerLines && !labelOptions.step && labelOptions.autoRotation; if (autoRotation) { // Loop over the given autoRotation options, and determine which gives the best score. The // best score is that with the lowest number of steps and a rotation closest to horizontal. each(autoRotation, function (rot) { var score; if (rot && rot >= -90 && rot <= 90) { step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot))); score = step + mathAbs(rot / 360); if (score < bestScore) { bestScore = score; rotation = rot; newTickInterval = step; } } }); } } else { newTickInterval = getStep(labelMetrics.h); } this.autoRotation = autoRotation; this.labelRotation = rotation; return newTickInterval; }, renderUnsquish: function () { var chart = this.chart, renderer = chart.renderer, tickPositions = this.tickPositions, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, margin = chart.margin, slotWidth = this.slotWidth = (horiz && !labelOptions.step && !labelOptions.rotation && ((this.staggerLines || 1) * chart.plotWidth) / tickPositions.length) || (!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931, innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))), attr = {}, labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), css, labelLength = 0, label, i, pos; // Set rotation option unless it is "auto", like in gauges if (!isString(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } // Handle auto rotation on horizontal axis if (this.autoRotation) { // Get the longest label length each(tickPositions, function (tick) { tick = ticks[tick]; if (tick && tick.labelLength > labelLength) { labelLength = tick.labelLength; } }); // Apply rotation only if the label is too wide for the slot, and // the label is wider than its height. if (labelLength > innerWidth && labelLength > labelMetrics.h) { attr.rotation = this.labelRotation; } else { this.labelRotation = 0; } // Handle word-wrap or ellipsis on vertical axis } else if (slotWidth) { // For word-wrap or ellipsis css = { width: innerWidth + PX, textOverflow: 'clip' }; // On vertical axis, only allow word wrap if there is room for more lines. i = tickPositions.length; while (!horiz && i--) { pos = tickPositions[i]; label = ticks[pos].label; if (label) { if (this.len / tickPositions.length - 4 < label.getBBox().height) { label.specCss = { textOverflow: 'ellipsis' }; } } } } // Add ellipsis if the label length is significantly longer than ideal if (attr.rotation) { css = { width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX, textOverflow: 'ellipsis' }; } // Set the explicit or automatic label alignment this.labelAlign = attr.align = labelOptions.align || this.autoLabelAlign(this.labelRotation); // Apply general and specific CSS each(tickPositions, function (pos) { var tick = ticks[pos], label = tick && tick.label; if (label) { if (css) { label.css(merge(css, label.specCss)); } delete label.specCss; label.attr(attr); tick.rotation = attr.rotation; } }); // TODO: Why not part of getLabelPosition? this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side === 2); }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n, lineHeightCorrection; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(); } if (hasData || axis.isLinked) { // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); axis.renderUnsquish(); each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0; labelOffsetPadded = labelOffset + titleMargin + (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection)); axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded // #3027 ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, to; // Reset axis.labelEdge.length = 0; //axis.justifyToPlot = overflow === 'justify'; axis.overlap = false; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions, function (pos, i) { // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && (axis.min === 0 || axis.single)) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair */ drawCrosshair: function (e, point) { // docs: Missing docs for Axis.crosshair. Also for properties. var path, options = this.crosshair, animation = options.animation, pos, attribs, categorized; if ( // Disabled in options !this.crosshair || // Snap ((defined(point) || !pick(this.crosshair.snap, true)) === false) ) { this.hideCrosshair(); } else { // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { /*jslint eqeq: true*/ pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834 /*jslint eqeq: false*/ } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189 } else { path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189 } if (path === null) { this.hideCrosshair(); return; } // Draw the cross if (this.cross) { this.cross .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation); } else { categorized = this.categories && !this.isRadial; attribs = { 'stroke-width': options.width || (categorized ? this.transA : 1), stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'), zIndex: options.zIndex || 2 }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min - getTZOffset(min)), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 minDate.setMilliseconds(interval >= timeUnits.second ? 0 : count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654 if (interval >= timeUnits.second) { // second minDate.setSeconds(interval >= timeUnits.minute ? 0 : count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits.minute) { // minute minDate[setMinutes](interval >= timeUnits.hour ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits.hour) { // hour minDate[setHours](interval >= timeUnits.day ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits.day) { // day minDate[setDate](interval >= timeUnits.month ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits.month) { // month minDate[setMonth](interval >= timeUnits.year ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits.year) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits.week) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; if (timezoneOffset || getTimezoneOffset) { minDate = minDate.getTime(); minDate = new Date(minDate + getTZOffset(minDate)); } minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), localTimezoneOffset = (timeUnits.day + (useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000) ) % timeUnits.day; // #950, #3359 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits.year) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits.month) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits.day || interval === timeUnits.week)) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits.day ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset; }), function (time) { higherRanks[time] = 'day'; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; }; /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) { var units = unitsOption || [[ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1, 2] ], [ 'week', [1, 2] ], [ 'month', [1, 2, 3, 4, 6] ], [ 'year', null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits.year && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval( tickInterval / interval, multiples, unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360 ); return { unitRange: interval, count: count, unitName: unit[0] }; };/** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -9999 }); // #2301, #2657 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.label.attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function (delay) { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(delay, this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; this.chart.hoverSeries = null; } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotLeft = chart.plotLeft, plotX = 0, plotY = 0, yAxis, xAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; xAxis = point.series.xAxis; plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0); plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft], // The far side is right or bottom preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = alignedLeft; } else if (roomRight) { ret[dim] = alignedRight; } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { return false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), s; // build the header s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header // build the values s = s.concat(tooltip.bodyFormatter(items)); // footer s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y), point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Get the best X date format based on the closest point range on the axis. */ getXDateFormat: function (point, options, xAxis) { var xDateFormat, dateTimeLabelFormats = options.dateTimeLabelFormats, closestPointRange = xAxis && xAxis.closestPointRange, n, blank = '01-01 00:00:00.000', strpos = { millisecond: 15, second: 12, minute: 9, hour: 6, day: 3 }, date, lastN; if (closestPointRange) { date = dateFormat('%m-%d %H:%M:%S.%L', point.x); for (n in timeUnits) { // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek && date.substr(6) === blank.substr(6)) { n = 'week'; break; // The first format that is too great for the range } else if (timeUnits[n] > closestPointRange) { n = lastN; break; // If the point is placed every day at 23:59, we need to show // the minutes as well. #2637. } else if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) { break; } // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition if (n !== 'week') { lastN = n; } } if (n) { xDateFormat = dateTimeLabelFormats[n]; } } else { xDateFormat = dateTimeLabelFormats.day; } return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 }, /** * Format the footer/header of the tooltip * #3397: abstraction to enable formatting of footer and header */ tooltipFooterHeaderFormatter: function (point, isFooter) { var footOrHead = isFooter ? 'footer' : 'header', series = point.series, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), formatString = tooltipOptions[footOrHead+'Format']; // Guess the best date format based on the closest point distance (#568, #3418) if (isDateTime && !xDateFormat) { xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis); } // Insert the footer date format if any if (isDateTime && xDateFormat) { formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(formatString, { point: point, series: series }); }, /** * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item, * abstracting this functionality allows to easily overwrite and extend it. */ bodyFormatter: function (items) { return map(items, function (item) { var tooltipOptions = item.series.tooltipOptions; return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat); }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = pick(options.tooltip.followTouchMove, true); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || window.event; // Framework specific normalizing (#1165) e = washMouseEvent(e); // More IE normalizing, needs to go after washMouseEvent if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, shared = tooltip ? tooltip.shared : false, followPointer, //point, //points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, trueXkd, trueX, //j, distance = chart.chartWidth, rdistance = chart.chartWidth, anchor, noSharedTooltip, kdpoints = [], kdpoint, kdpointT; // For hovering over the empty parts of the plot area (hoverSeries is undefined). // If there is one series with point tracking (combo chart), don't go to nearest neighbour. if (!shared && !hoverSeries) { for (i = 0; i < series.length; i++) { if (series[i].directTouch || !series[i].options.stickyTracking) { series = []; } } } if (!(hoverSeries && hoverSeries.noSharedTooltip) && (shared || !hoverSeries)) { // #3821 // Find nearest points on all series each(series, function (s) { // Skip hidden series noSharedTooltip = s.noSharedTooltip && shared; if (s.visible && !noSharedTooltip && pick(s.options.enableMouseTracking, true)) { // #3821 kdpointT = s.searchPoint(e); // #3828 if (kdpointT) { kdpoints.push(kdpointT); } } }); // Find absolute nearest point each(kdpoints, function (p) { if (p && defined(p.plotX) && defined(p.plotY)) { if ((p.dist.distX < distance) || ((p.dist.distX === distance || p.series.kdDimensions > 1) && p.dist.distR < rdistance)) { distance = p.dist.distX; rdistance = p.dist.distR; kdpoint = p; } } //point = kdpoints[0]; }); } else { kdpoint = hoverSeries ? hoverSeries.searchPoint(e) : UNDEFINED; } // Refresh tooltip for kdpoint if (kdpoint && kdpoint !== hoverPoint) { // Draw tooltip if necessary if (shared && !kdpoint.series.noSharedTooltip) { i = kdpoints.length; trueXkd = kdpoint.clientX; while (i--) { trueX = kdpoints[i].clientX; if (kdpoints[i].x !== kdpoint.x || trueX !== trueXkd || !defined(kdpoints[i].y) || (kdpoints[i].series.noSharedTooltip || false)) { kdpoints.splice(i, 1); } } if (tooltip) { tooltip.refresh(kdpoints, e); } each(kdpoints, function (point) { point.onMouseOver(e); }); } else { if (tooltip) { tooltip.refresh(kdpoint, e); } kdpoint.onMouseOver(e); } // Update positions (regardless of kdpoint or hoverPoint) } else { followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { pointer.onDocumentMouseMove(e); }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Crosshair each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(kdpoint, hoverPoint)); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); each(chart.axes, function (axis) { if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) { axis.drawCrosshair(null, allowMove); } else { axis.hideCrosshair(); } }); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var pointer = this, chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569 var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes max: mathMax(selectionMin, selectionMax) }); runZoom = true; } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { var chart = charts[hoverChartIndex]; if (chart) { chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; hoverChartIndex = chart.index; e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement, relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499 if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && relatedSeries !== series) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if (hasZoom && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && self.followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, onContainerTouchStart: function (e) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) { // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } else { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, callback) { var p; e = e.originalEvent || e; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { callback(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onContainerTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom || this.followTouchMove) { css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding, itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding = pick(options.padding, 8); legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroy all items. */ clearItems: function () { var legend = this; each(legend.getAllItems(), function (item) { legend.destroyItem(item); }); }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.baseline = renderer.fontMetrics(itemStyle.fontSize, li).f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Adjust the chart margins by reserving space for the legend on only one side * of the chart. If the position is set to a corner, top or bottom is reserved * for horizontal legends and left or right for vertical ones. */ adjustMargins: function (margin, spacing) { var chart = this.chart, options = this.options, // Use the first letter of each alignment option in order to detect the side alignment = options.align[0] + options.verticalAlign[0] + options.layout[0]; if (this.display && !options.floating) { each([ /(lth|ct|rth)/, /(rtv|rm|rbv)/, /(rbh|cb|lbh)/, /(lbv|lm|ltv)/ ], function (alignments, side) { if (alignments.test(alignment) && !defined(margin[side])) { // Now we have detected on which side of the chart we should reserve space for the legend chart[marginNames[side]] = mathMax( chart[marginNames[side]], chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] + pick(options.margin, 12) + spacing[side] ); } }); } }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items legend.lastLineHeight = 0; each(allItems, function (item) { legend.renderItem(item); }); // Get the box legendWidth = (options.width || legend.offsetWidth) + padding; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); legendHeight += padding; // Draw the border and/or background if (legendBorderWidth || legendBackgroundColor) { if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, lastY, allItems = this.allItems; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - this.padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || 12; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 5 - (symbolHeight / 2), legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // TODO: Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ var Chart = Highcharts.Chart = function () { this.init.apply(this, arguments); }; Chart.prototype = { /** * Hook for modules */ callbacks: [], /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Generate stacks for each series and calculate stacks total values */ getStacks: function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(titleOptions.style.fontSize, subtitle).b }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) if (!defined(widthOption)) { chart.containerWidth = adapterRun(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = adapterRun(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) : new Renderer(container, chartWidth, chartHeight, optionsChart.style); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } // Add a reference to the charts index chart.renderer.chartIndex = chart.index; }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function (skipAxes) { var chart = this, spacing = chart.spacing, margin = chart.margin, titleOffset = chart.titleOffset; chart.resetMargins(); // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend chart.legend.adjustMargins(margin, spacing); // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } if (!skipAxes) { this.getAxisMargins(); } }, getAxisMargins: function () { var chart = this, axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left margin = chart.margin; // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } // Add the axis offsets each(marginNames, function (m, side) { if (!defined(margin[side])) { chart[m] += axisOffset[side]; } }); chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win, // #805 - MooTools doesn't supply e doReflow = function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); if (e) { // Called from window.resize chart.reflowTimeout = setTimeout(doReflow, 100); } else { // Called directly (#2224) doReflow(); } } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } // Resize the container with the global animation applied if enabled (#2503) (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this; each(marginNames, function (m, side) { chart[m] = pick(chart.margin[side], chart.spacing[side]); }); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options, tempWidth, tempHeight, redoHorizontal, redoVertical; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); chart.getStacks(); // render stacks // Get chart margins chart.getMargins(true); chart.setChartSize(); // Record preliminary dimensions for later comparison tempWidth = chart.plotWidth; tempHeight = chart.plotHeight = chart.plotHeight - 13; // 13 is the most common height of X axis labels // Get margins by pre-rendering axes each(axes, function (axis) { axis.setScale(); }); chart.getAxisMargins(); // If the plot area size has changed significantly, calculate tick positions again redoHorizontal = tempWidth / chart.plotWidth > 1.2; redoVertical = tempHeight / chart.plotHeight > 1.1; if (redoHorizontal || redoVertical) { chart.maxTicks = null; // reset for second pass each(axes, function (axis) { if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) { axis.setTickInterval(true); // update to reflect the new margins } }); chart.getMargins(); // second pass to check for new labels } // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Highcharts.Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { if (chart.index !== UNDEFINED) { // Chart destroyed in its own callback (#3600) fn.apply(chart, [chart]); } }); // Fire the load event fireEvent(chart, 'load'); // If the chart was rendered outside the top container, put it back in (#3679) chart.cloneRenderTo(true); }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = { /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), isPercent, i, value; for (i = 0; i < 4; ++i) { value = positions[i]; isPercent = /%$/.test(value); handleSlicingRoom = i < 2 || (i === 2 && isPercent); positions[i] = (isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 3: innerSize, relative to size [plotWidth, plotHeight, smallestSize, positions[2]][i] * pInt(value) / 100 : pInt(value)) + (handleSlicingRoom ? slicingRoom : 0); } return positions; } }; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.color = series.color; // #3445 point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, pointArrayMap = series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); } };/** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = Highcharts.Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var options = this.options, xIncrement = this.xIncrement, date, pointInterval, pointIntervalUnit = options.pointIntervalUnit; xIncrement = pick(xIncrement, options.pointStart, 0); this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1); // Added code for pointInterval strings if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') { date = new Date(xIncrement); date = (pointIntervalUnit === 'month') ? +date[setMonth](date[getMonth]() + pointInterval) : +date[setFullYear](date[getFullYear]() + pointInterval); pointInterval = date - xIncrement; } this.xIncrement = xIncrement + pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options, zones; this.userOptions = itemOptions; // General series options take precedence over type options because otherwise, default // type options like column.animation would be overwritten by the general option. // But issues have been raised here (#3881), and the solution may be to distinguish // between default option and userOptions like in the tooltip below. options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } // Handle color zones this.zoneAxis = options.zoneAxis; zones = this.zones = (options.zones || []).slice(); if ((options.negativeColor || options.negativeFillColor) && !options.zones) { zones.push({ value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0, color: options.negativeColor, fillColor: options.negativeFillColor }); } if (zones.length) { // Push one extra zone for the rest if (defined(zones[zones.length - 1].value)) { zones.push({ color: this.color, fillColor: this.fillColor }); } } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (!this.options.colorByPoint) { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) { each(data, function (point, i) { oldData[i].update(point, false, null, false); }); } else { // Reset properties series.xIncrement = null; series.pointRange = hasCategories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); if (hasCategories && pt.name) { xAxis.names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; //series.zData = zData; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, isCartesian = series.isCartesian, xExtremes, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (xData[i] > max) { cropEnd = i + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, dataMin, dataMax, x, y, i, j; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = pick(dataMin, arrayMin(activeYData)); this.dataMax = pick(dataMax, arrayMax(activeYData)); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold, plotX, plotY, lastPlotX, closestPointRangePx = Number.MAX_VALUE; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes (#3434) if (yAxis.isLog && yValue !== null && yValue <= 0) { point.y = yValue = null; error(10); } // Get the plotX translation point.plotX = plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; stackValues = pointStack.points[series.index + ',' + i]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === 0) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ? mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201 UNDEFINED; point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519 plotX >= 0 && plotX <= xAxis.len; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; // Determine auto enabling of markers (#3635) if (i) { closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX)); } lastPlotX = plotX; } series.closestPointRangePx = closestPointRangePx; // now that we have the cropped data, build the segments series.getSegments(); }, /** * Set the clipping for the series. For animated series it is called twice, first to initiate * animating the clip then the second time without the animation to set the final clip. */ setClip: function (animation) { var chart = this.chart, renderer = chart.renderer, inverted = chart.inverted, seriesClipBox = this.clipBox, clipBox = seriesClipBox || chart.clipBox, sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height].join(','), clipRect = chart[sharedClipKey], markerClipRect = chart[sharedClipKey + 'm']; // If a clipping rectangle with the same properties is currently present in the chart, use that. if (!clipRect) { // When animation is set, prepare the initial positions if (animation) { clipBox.width = 0; chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox); } if (animation) { clipRect.count += 1; } if (this.options.clip !== false) { this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect); this.markerGroup.clip(markerClipRect); this.sharedClipKey = sharedClipKey; } // Remove the shared clipping rectancgle when all series are shown if (!animation) { clipRect.count -= 1; if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) { if (!seriesClipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } } }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, clipRect, animation = series.options.animation, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } // Initialize the animation. Set up the clipping rectangle. if (init) { series.setClip(animation); // Run the animation } else { sharedClipKey = this.sharedClipKey; clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { this.setClip(); fireEvent(this, 'afterAnimate'); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, xAxis = series.xAxis, globallyEnabled = pick( seriesMarkerOptions.enabled, xAxis.isRadial, series.closestPointRangePx > 2 * seriesMarkerOptions.radius ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = point.isInside; // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, seriesNegativeColor = series.options.negativeColor, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, zones = series.zones, zoneAxis = series.zoneAxis || 'y', attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); // if no hover negativeColor is given, brighten the normal negativeColor stateOptionsHover.negativeColor = stateOptionsHover.negativeColor || Color(stateOptionsHover.negativeColor || seriesNegativeColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (zones.length) { var j = 0, threshold = zones[j]; while (point[zoneAxis] >= threshold.value) { threshold = zones[++j]; } point.color = point.fillColor = threshold.color; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color, options.dashStyle]], lineWidth = options.lineWidth, roundCap = options.linecap !== 'square', graphPath = this.getGraphPath(), fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph zones = this.zones; each(zones, function (threshold, i) { props.push(['colorGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]); }); // Draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if ((lineWidth || fillColor) && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: fillColor, zIndex: 1 // #1069 }; if (prop[2]) { attribs.dashstyle = prop[2]; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow(!i && options.shadow); } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ applyZones: function () { var series = this, chart = this.chart, renderer = chart.renderer, zones = this.zones, translatedFrom, translatedTo, clips = this.clips || [], clipAttr, graph = this.graph, area = this.area, chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight), zoneAxis = this.zoneAxis || 'y', axis = this[zoneAxis + 'Axis'], reversed = axis.reversed, horiz = axis.horiz, ignoreZones = false; if (zones.length && (graph || area)) { // The use of the Color Threshold assumes there are no gaps // so it is safe to hide the original graph and area graph.hide(); if (area) { area.hide(); } // Create the clips each(zones, function (threshold, i) { translatedFrom = pick(translatedTo, (reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(axis.min)))); translatedTo = mathRound(axis.toPixels(pick(threshold.value, axis.max), true)); if (ignoreZones) { translatedFrom = translatedTo = axis.toPixels(axis.max); } if (axis.isXAxis) { clipAttr = { x: reversed ? translatedTo : translatedFrom, y: 0, width: Math.abs(translatedFrom - translatedTo), height: chartSizeMax }; if (!horiz) { clipAttr.x = chart.plotHeight - clipAttr.x; } } else { clipAttr = { x: 0, y: reversed ? translatedFrom : translatedTo, width: chartSizeMax, height: Math.abs(translatedFrom - translatedTo) }; if (horiz) { clipAttr.y = chart.plotWidth - clipAttr.y; } } /// VML SUPPPORT if (chart.inverted && renderer.isVML) { if (axis.isXAxis) { clipAttr = { x: 0, y: reversed ? translatedFrom : translatedTo, height: clipAttr.width, width: chart.chartWidth }; } else { clipAttr = { x: clipAttr.y - chart.plotLeft - chart.spacingBox.x, y: 0, width: clipAttr.height, height: chart.chartHeight }; } } /// END OF VML SUPPORT if (clips[i]) { clips[i].animate(clipAttr); } else { clips[i] = renderer.clipRect(clipAttr); series['colorGraph' + i].clip(clips[i]); if (area) { series['colorArea' + i].clip(clips[i]); } } // if this zone extends out of the axis, ignore the others ignoreZones = threshold.value > axis.max; }); this.clips = clips; } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.applyZones(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839). if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { if (animDuration) { series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animDuration); } else { series.afterAnimate(); } } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.render(); if (wasDirtyData) { delete this.kdTree; // #3868 recalculate the kdtree with dirty data fireEvent(series, 'updatedData'); } }, /** * KD Tree && PointSearching Implementation */ kdDimensions: 1, kdTree: null, kdAxisArray: ['plotX', 'plotY'], kdComparer: 'distX', searchPoint: function (e) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, inverted = series.chart.inverted; e.plotX = inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos; e.plotY = inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos; return this.searchKDTree(e); }, buildKDTree: function () { var series = this, dimensions = series.kdDimensions; // Internal function function _kdtree(points, depth, dimensions) { var axis, median, length = points && points.length; if (length) { // alternate between the axis axis = series.kdAxisArray[depth % dimensions]; // sort point array points.sort(function(a, b) { return a[axis] - b[axis]; }); median = Math.floor(length / 2); // build and return node return { point: points[median], left: _kdtree(points.slice(0, median), depth + 1, dimensions), right: _kdtree(points.slice(median + 1), depth + 1, dimensions) }; } } // Start the recursive build process with a clone of the points array (#3873) function startRecursive() { series.kdTree = _kdtree(series.points.slice(), dimensions, dimensions); } delete series.kdTree; if (series.options.kdSync) { // For testing tooltips, don't build async startRecursive(); } else { setTimeout(startRecursive); } }, searchKDTree: function (point) { var series = this, kdComparer = this.kdComparer, kdX = this.kdAxisArray[0], kdY = this.kdAxisArray[1]; // Internal function function _distance(p1, p2) { var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null, y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null, r = (x || 0) + (y || 0); return { distX: defined(x) ? Math.sqrt(x) : Number.MAX_VALUE, distY: defined(y) ? Math.sqrt(y) : Number.MAX_VALUE, distR: defined(r) ? Math.sqrt(r) : Number.MAX_VALUE }; } function _search(search, tree, depth, dimensions) { var point = tree.point, axis = series.kdAxisArray[depth % dimensions], tdist, sideA, sideB, ret = point, nPoint1, nPoint2; point.dist = _distance(search, point); // Pick side based on distance to splitting point tdist = search[axis] - point[axis]; sideA = tdist < 0 ? 'left' : 'right'; // End of tree if (tree[sideA]) { nPoint1 =_search(search, tree[sideA], depth + 1, dimensions); ret = (nPoint1.dist[kdComparer] < ret.dist[kdComparer] ? nPoint1 : point); sideB = tdist < 0 ? 'right' : 'left'; if (tree[sideB]) { // compare distance to current best to splitting point to decide wether to check side B or not if (Math.sqrt(tdist*tdist) < ret.dist[kdComparer]) { nPoint2 = _search(search, tree[sideB], depth + 1, dimensions); ret = (nPoint2.dist[kdComparer] < ret.dist[kdComparer] ? nPoint2 : ret); } } } return ret; } if (!this.kdTree) { this.buildKDTree(); } if (this.kdTree) { return _search(point, this.kdTree, this.kdDimensions, this.kdDimensions); } } }; // end Series prototype /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Initialize total value this.total = null; // This will keep each points' extremes stored by series.index and point index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, neg = this.isNegative, // special treatment is needed for negative stacks y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true); } } }; // Stacking methods defined on the Axis prototype /** * Build the stacks from top down */ Axis.prototype.buildStacks = function () { var series = this.series, reversedStacks = pick(this.options.reversedStacks, true), i = series.length; if (!this.isXAxis) { this.usePercentage = false; while (i--) { series[reversedStacks ? i : series.length - i - 1].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }; Axis.prototype.renderStackTotals = function () { var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } }; // Stacking methods defnied for Series prototype /** * Adds series' points value to corresponding stack */ Series.prototype.setStackedPoints = function () { if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) { return; } var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, isNegative, stack, other, key, pointKey, i, x, y; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; pointKey = series.index + ',' + i; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) isNegative = negStacks && y < threshold; key = isNegative ? negKey : stackKey; // Create empty object for this stack if it doesn't exist yet if (!stacks[key]) { stacks[key] = {}; } // Initialize StackItem for this x if (!stacks[key][x]) { if (oldStacks[key] && oldStacks[key][x]) { stacks[key][x] = oldStacks[key][x]; stacks[key][x].total = null; } else { stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; stack.points[pointKey] = [stack.cum || 0]; // Add value to the stack total if (stacking === 'percent') { // Percent stacked column, totals are the same for the positive and negative stacks other = isNegative ? stackKey : negKey; if (negStacks && stacks[other] && stacks[other][x]) { other = stacks[other][x]; stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0; // Percent stacked areas } else { stack.total = correctFloat(stack.total + (mathAbs(y) || 0)); } } else { stack.total = correctFloat(stack.total + (y || 0)); } stack.cum = (stack.cum || 0) + (y || 0); stack.points[pointKey].push(stack.cum); stackedYData[i] = stack.cum; } if (stacking === 'percent') { yAxis.usePercentage = true; } this.stackedYData = stackedYData; // To be used in getExtremes // Reset old stacks yAxis.oldStacks = {}; }; /** * Iterate over all stacks and compute the absolute values to percent */ Series.prototype.setPercentStacks = function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData; each([stackKey, '-' + stackKey], function (key) { var i = processedXData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = processedXData[i]; stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[series.index + ',' + i]; if (pointExtremes) { totalFactor = stack.total ? 100 / stack.total : 0; pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value series.stackedYData[i] = pointExtremes[1]; } } }); }; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length, isX: isX })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options, names = series.xAxis && series.xAxis.names; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (isObject(options) && !isArray(options)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } else { graphic.attr(point.pointAttr[point.state || '']); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); if (names && point.name) { names[point.x] = point.name; } seriesOptions.data[i] = point.options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 series.updateTotals(); chart.legend.clearItems(); } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { this.series.removePoint(inArray(this, this.series.data), redraw, animation); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, x, i; setAnimation(animation, chart); // Make graph animate sideways if (shift) { each([graph, area, series.graphNeg, series.areaNeg], function (shape) { if (shape) { shape.shift = currentShift + 1; } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Remove a point (rendered or not), by index */ removePoint: function (i, redraw, animation) { var series = this, data = series.data, point = data[i], points = series.points, chart = series.chart, remove = function () { if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point || { series: series }, 'splice', i, 1); if (point) { point.destroy(); } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }; setAnimation(animation, chart); redraw = pick(redraw, true); // Fire the event with a default handler of removing the point if (point) { point.firePointEvent('remove', null, remove); } else { remove(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // If we're changing type or zIndex, create new groups (#3380, #3404) if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) { preserve.length = 0; } // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and delete all properties. Reinsert all methods // and properties from the new type prototype (#2270, #3719) this.remove(false); for (n in proto) { this[n] = UNDEFINED; } extend(this, seriesTypes[newOptions.type || oldType].prototype); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = UNDEFINED; // #1611, #2887 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var series = this, segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336) keys.push(+x); } } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { var y = 0, stackPoint; if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836 return; // The point exists, push it to the segment } else if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { // Loop down the stack to find the series below this one that has // a value (#1991) for (i = series.index; i <= yAxis.series.length; i++) { stackPoint = stack[x].points[i + ',' + x]; if (stackPoint) { y = stackPoint[1]; break; } } plotX = xAxis.translate(x); plotY = yAxis.toPixels(y, true); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length, translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181 yBottom; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { yBottom = pick(segment[i].yBottom, translatedThreshold); // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, yBottom); } areaSegmentPath.push(segment[i].plotX, yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment, translatedThreshold); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment, translatedThreshold) { path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, zones = this.zones, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color each(zones, function (threshold, i) { props.push(['colorArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]); }); each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.area = AreaSeries; /** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', //borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1; if (chart.renderer.isVML && chart.inverted) { yCrisp += 1; } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function (point) { var yBottom = pick(point.yBottom, translatedThreshold), plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), right, bottom, fromTop, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485) } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216, #424, #3648) point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop]; // Round off to obtain crisp edges and avoid overlapping with neighbours (#2694) right = mathRound(barX + barW) + xCrisp; barX = mathRound(barX) + xCrisp; barW = right - barX; fromTop = mathAbs(barY) < 0.5; bottom = mathMin(mathRound(barY + barH) + yCrisp, 9e4); // #3575 barY = mathRound(barY) + yCrisp; barH = bottom - barY; // Top edges are exceptions if (fromTop) { barY -= 1; barH += 1; } // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = { x: barX, y: barY, width: barW, height: barH }; }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(borderAttr) .attr(pointAttr) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, marker: { enabled: true // Overrides auto-enabling in line series (#3647) }, tooltip: { headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' } }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 kdDimensions: 2, kdComparer: 'distR', drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { // #2945 return this.point.name; }, // softConnector: true, x: 0 // y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function (e) { point.slice(e.type === 'select'); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis) { var point = this, series = point.series, chart = series.chart, doRedraw = !series.isDirty && series.options.ignoreHiddenPoint; // if called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][vis ? 'show' : 'hide'](true); } }); if (point.legendItem) { if (chart.hasRendered) { series.updateTotals(); chart.legend.clearItems(); if (!doRedraw) { chart.legend.render(); } } chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (doRedraw) { series.isDirty = true; chart.redraw(); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } }, haloPath: function (size) { var shapeArgs = this.shapeArgs, chart = this.series.chart; return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, { innerR: this.shapeArgs.r, start: shapeArgs.start, end: shapeArgs.end }); } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], axisTypes: [], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Pies have one color each point */ getColor: noop, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: series.center[3] / 2, // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw, animation, updatePoints) { Series.prototype.setData.call(this, data, false, animation, updatePoints); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(animation); } }, /** * Recompute total chart sum and update percentages of points. */ updateTotals: function () { var i, total = 0, points, len, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; // Populate local vars points = this.points; len = points.length; // Get the total sum for (i = 0; i < len; i++) { point = points[i]; // Disallow negative values (#1530, #3623) if (point.y < 0) { point.y = null; } total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } this.total = total; // Set each point's properties for (i = 0; i < len; i++) { point = points[i]; //point.percentage = (total <= 0 || ignoreHiddenPoint && !point.visible) ? 0 : point.y / total * 100; point.percentage = (total > 0 && (point.visible || !ignoreHiddenPoint)) ? point.y / total * 100 : 0; point.total = total; } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { Series.prototype.generatePoints.call(this); this.updateTotals(); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngle = options.startAngle || 0, startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90), endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90), circ = endAngleRad - startAngleRad, //2 * mathPI, points = series.points, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle start = startAngleRad + (cumulative * circ); if (!ignoreHiddenPoint || point.visible) { cumulative += point.percentage / 100; } end = startAngleRad + (cumulative * circ); // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: mathRound(start * precision) / precision, end: mathRound(end * precision) / precision }; // The angle must stay within -90 and 270 (#2645) angle = (end + start) / 2; if (angle > 1.5 * mathPI) { angle -= 2 * mathPI; } else if (angle < -mathPI / 2) { angle += 2 * mathPI; } // Center for the sliced out slice point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; } }, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic.animate(extend(shapeArgs, groupTranslation)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' //zIndex: 1 // #2722 (reversed) }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility (#2430) if (point.visible !== undefined) { point.setVisible(point.visible); } }); }, searchPoint: noop, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Use a simple symbol from LegendSymbolMixin */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Use the getCenter method from drawLegendSymbol */ getCenter: CenteredSeriesMixin.getCenter, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup, renderer = series.chart.renderer; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', options.defer ? HIDDEN : VISIBLE, options.zIndex || 6 ); if (pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #3023, #3024 dataLabelsGroup.show(); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true, style, moreStyle = {}; // Determine if each data label is enabled pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); style = options.style; rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color style.color = pick(options.color, style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Get automated contrast color if (style.color === 'contrast') { moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ? renderer.getContrast(point.color || series.color) : '#000000'; } if (cursor) { moreStyle.cursor = cursor; } // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, options.shape, null, null, options.useHTML ) .attr(attr) .css(extend(style, moreStyle)) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), baseline = chart.renderer.fontMetrics(options.style.fontSize).b, rotCorr, // rotation correction // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr; // the final position; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text rotCorr = chart.renderer.rotCorr(baseline, options.rotation); // #3723 dataLabel[isNew ? 'attr' : 'animate']({ x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x, y: alignTo.y + options.y + alignTo.height / 2 }) .attr({ // #3003 align: options.align }); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === 'justify') { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); } else if (pick(options.crop, true)) { // Now check that the data label is within the plot area visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } // When we're using a shape, make it possible with a connector or an arrow pointing to thie point if (options.shape) { dataLabel.attr({ anchorX: point.plotX, anchorY: point.plotY }); } } } // Show or hide based on the final aligned position if (!visible) { dataLabel.attr({ y: -999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified, padding = dataLabel.box ? 0 : (dataLabel.padding || 0); // Off left off = alignAttr.x + padding; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width - padding; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y + padding; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height - padding; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 halves[point.half].push(point); } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = mathMin(mathMax(0, naturalY), chart.plotHeight); } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var inverted = this.chart.inverted, series = point.series, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, series.yAxis.len)), inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: series.yAxis.len - alignTo.y - alignTo.height, y: series.xAxis.len - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * Highstock JS v2.1.3 (2015-02-27) * Highcharts module to hide overlapping data labels. This module is included by default in Highmaps. * * (c) 2010-2014 Torstein Honsi * * License: www.highcharts.com/license */ /*global Highcharts, HighchartsAdapter */ (function (H) { var Chart = H.Chart, each = H.each, addEvent = HighchartsAdapter.addEvent; // Collect potensial overlapping data labels. Stack labels probably don't need to be // considered because they are usually accompanied by data labels that lie inside the columns. Chart.prototype.callbacks.push(function (chart) { function collectAndHide() { var labels = []; each(chart.series, function (series) { var dlOptions = series.options.dataLabels; if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866 each(series.points, function (point) { if (point.dataLabel) { point.dataLabel.labelrank = point.labelrank; labels.push(point.dataLabel); } }); } }); chart.hideOverlappingLabels(labels); } // Do it now ... collectAndHide(); // ... and after each chart redraw addEvent(chart, 'redraw', collectAndHide); }); /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ Chart.prototype.hideOverlappingLabels = function (labels) { var len = labels.length, label, i, j, label1, label2, intersectRect = function (pos1, pos2, size1, size2) { return !( pos2.x > pos1.x + size1.width || pos2.x + size2.width < pos1.x || pos2.y > pos1.y + size1.height || pos2.y + size2.height < pos1.y ); }; // Mark with initial opacity for (i = 0; i < len; i++) { label = labels[i]; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } } // Detect overlapping labels for (i = 0; i < len; i++) { label1 = labels[i]; for (j = i + 1; j < len; ++j) { label2 = labels[j]; if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0 && intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) { (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0; } } } // Hide or show for (i = 0; i < len; i++) { label = labels[i]; if (label) { if (label.oldOpacity !== label.newOpacity && label.placed) { label.alignAttr.opacity = label.newOpacity; label[label.isOld && label.newOpacity ? 'animate' : 'attr'](label.alignAttr); } label.isOld = true; } } }; }(Highcharts));/** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; if (chart.hoverSeries !== series) { series.onMouseOver(); } while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item.series || item, 'checkboxClick', { // #3712 checked: target.checked, item: item }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var mousePos = e[isX ? 'chartX' : 'chartY'], axis = chart[isX ? 'xAxis' : 'yAxis'][0], startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange, goingLeft = startPos > mousePos; // #3613 if (axis.series.length && (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) && (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(chart.seriesGroup); } halo.attr(extend({ fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get() }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted; return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, graphNeg = series.graphNeg, stateOptions = options.states, lineWidth = options.lineWidth, attribs; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = (stateOptions[state].lineWidth || lineWidth) + (stateOptions[state].lineWidthPlus || 0); } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); if (graphNeg) { graphNeg.attr(attribs); } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph });/* **************************************************************************** * Start ordinal axis logic * *****************************************************************************/ wrap(Series.prototype, 'init', function (proceed) { var series = this, xAxis; // call the original function proceed.apply(this, Array.prototype.slice.call(arguments, 1)); xAxis = series.xAxis; // Destroy the extended ordinal index on updated data if (xAxis && xAxis.options.ordinal) { addEvent(series, 'updatedData', function () { delete xAxis.ordinalIndex; }); } }); /** * In an ordinal axis, there might be areas with dense consentrations of points, then large * gaps between some. Creating equally distributed ticks over this entire range * may lead to a huge number of ticks that will later be removed. So instead, break the * positions up in segments, find the tick positions for each segment then concatenize them. * This method is used from both data grouping logic and X axis tick position logic. */ wrap(Axis.prototype, 'getTimeTicks', function (proceed, normalizedInterval, min, max, startOfWeek, positions, closestDistance, findHigherRanks) { var start = 0, end = 0, segmentPositions, higherRanks = {}, hasCrossedHigherRank, info, posLength, outsideMax, groupPositions = [], lastGroupPosition = -Number.MAX_VALUE, tickPixelIntervalOption = this.options.tickPixelInterval; // The positions are not always defined, for example for ordinal positions when data // has regular interval (#1557, #2090) if ((!this.options.ordinal && !this.options.breaks) || !positions || positions.length < 3 || min === UNDEFINED) { return proceed.call(this, normalizedInterval, min, max, startOfWeek); } // Analyze the positions array to split it into segments on gaps larger than 5 times // the closest distance. The closest distance is already found at this point, so // we reuse that instead of computing it again. posLength = positions.length; for (; end < posLength; end++) { outsideMax = end && positions[end - 1] > max; if (positions[end] < min) { // Set the last position before min start = end; } if (end === posLength - 1 || positions[end + 1] - positions[end] > closestDistance * 5 || outsideMax) { // For each segment, calculate the tick positions from the getTimeTicks utility // function. The interval will be the same regardless of how long the segment is. if (positions[end] > lastGroupPosition) { // #1475 segmentPositions = proceed.call(this, normalizedInterval, positions[start], positions[end], startOfWeek); // Prevent duplicate groups, for example for multiple segments within one larger time frame (#1475) while (segmentPositions.length && segmentPositions[0] <= lastGroupPosition) { segmentPositions.shift(); } if (segmentPositions.length) { lastGroupPosition = segmentPositions[segmentPositions.length - 1]; } groupPositions = groupPositions.concat(segmentPositions); } // Set start of next segment start = end + 1; } if (outsideMax) { break; } } // Get the grouping info from the last of the segments. The info is the same for // all segments. info = segmentPositions.info; // Optionally identify ticks with higher rank, for example when the ticks // have crossed midnight. if (findHigherRanks && info.unitRange <= timeUnits.hour) { end = groupPositions.length - 1; // Compare points two by two for (start = 1; start < end; start++) { if (dateFormat('%d', groupPositions[start]) !== dateFormat('%d', groupPositions[start - 1])) { higherRanks[groupPositions[start]] = 'day'; hasCrossedHigherRank = true; } } // If the complete array has crossed midnight, we want to mark the first // positions also as higher rank if (hasCrossedHigherRank) { higherRanks[groupPositions[0]] = 'day'; } info.higherRanks = higherRanks; } // Save the info groupPositions.info = info; // Don't show ticks within a gap in the ordinal axis, where the space between // two points is greater than a portion of the tick pixel interval if (findHigherRanks && defined(tickPixelIntervalOption)) { // check for squashed ticks var length = groupPositions.length, i = length, itemToRemove, translated, translatedArr = [], lastTranslated, medianDistance, distance, distances = []; // Find median pixel distance in order to keep a reasonably even distance between // ticks (#748) while (i--) { translated = this.translate(groupPositions[i]); if (lastTranslated) { distances[i] = lastTranslated - translated; } translatedArr[i] = lastTranslated = translated; } distances.sort(); medianDistance = distances[mathFloor(distances.length / 2)]; if (medianDistance < tickPixelIntervalOption * 0.6) { medianDistance = null; } // Now loop over again and remove ticks where needed i = groupPositions[length - 1] > max ? length - 1 : length; // #817 lastTranslated = undefined; while (i--) { translated = translatedArr[i]; distance = lastTranslated - translated; // Remove ticks that are closer than 0.6 times the pixel interval from the one to the right, // but not if it is close to the median distance (#748). if (lastTranslated && distance < tickPixelIntervalOption * 0.8 && (medianDistance === null || distance < medianDistance * 0.8)) { // Is this a higher ranked position with a normal position to the right? if (higherRanks[groupPositions[i]] && !higherRanks[groupPositions[i + 1]]) { // Yes: remove the lower ranked neighbour to the right itemToRemove = i + 1; lastTranslated = translated; // #709 } else { // No: remove this one itemToRemove = i; } groupPositions.splice(itemToRemove, 1); } else { lastTranslated = translated; } } } return groupPositions; }); // Extend the Axis prototype extend(Axis.prototype, { /** * Calculate the ordinal positions before tick positions are calculated. */ beforeSetTickPositions: function () { var axis = this, len, ordinalPositions = [], useOrdinal = false, dist, extremes = axis.getExtremes(), min = extremes.min, max = extremes.max, minIndex, maxIndex, slope, i; // apply the ordinal logic if (axis.options.ordinal || axis.options.breaks) { each(axis.series, function (series, i) { if (series.visible !== false && (series.takeOrdinalPosition !== false || axis.options.breaks)) { // concatenate the processed X data into the existing positions, or the empty array ordinalPositions = ordinalPositions.concat(series.processedXData); len = ordinalPositions.length; // remove duplicates (#1588) ordinalPositions.sort(function (a, b) { return a - b; // without a custom function it is sorted as strings }); if (len) { i = len - 1; while (i--) { if (ordinalPositions[i] === ordinalPositions[i + 1]) { ordinalPositions.splice(i, 1); } } } } }); // cache the length len = ordinalPositions.length; // Check if we really need the overhead of mapping axis data against the ordinal positions. // If the series consist of evenly spaced data any way, we don't need any ordinal logic. if (len > 2) { // two points have equal distance by default dist = ordinalPositions[1] - ordinalPositions[0]; i = len - 1; while (i-- && !useOrdinal) { if (ordinalPositions[i + 1] - ordinalPositions[i] !== dist) { useOrdinal = true; } } // When zooming in on a week, prevent axis padding for weekends even though the data within // the week is evenly spaced. if (!axis.options.keepOrdinalPadding && (ordinalPositions[0] - min > dist || max - ordinalPositions[ordinalPositions.length - 1] > dist)) { useOrdinal = true; } } // Record the slope and offset to compute the linear values from the array index. // Since the ordinal positions may exceed the current range, get the start and // end positions within it (#719, #665b) if (useOrdinal) { // Register axis.ordinalPositions = ordinalPositions; // This relies on the ordinalPositions being set. Use mathMax and mathMin to prevent // padding on either sides of the data. minIndex = axis.val2lin(mathMax(min, ordinalPositions[0]), true); maxIndex = mathMax(axis.val2lin(mathMin(max, ordinalPositions[ordinalPositions.length - 1]), true), 1); // #3339 // Set the slope and offset of the values compared to the indices in the ordinal positions axis.ordinalSlope = slope = (max - min) / (maxIndex - minIndex); axis.ordinalOffset = min - (minIndex * slope); } else { axis.ordinalPositions = axis.ordinalSlope = axis.ordinalOffset = UNDEFINED; } if (axis.options.ordinal) { axis.doPostTranslate = useOrdinal; // #3818 } } axis.groupIntervalFactor = null; // reset for next run }, /** * Translate from a linear axis value to the corresponding ordinal axis position. If there * are no gaps in the ordinal axis this will be the same. The translated value is the value * that the point would have if the axis were linear, using the same min and max. * * @param Number val The axis value * @param Boolean toIndex Whether to return the index in the ordinalPositions or the new value */ val2lin: function (val, toIndex) { var axis = this, ordinalPositions = axis.ordinalPositions; if (!ordinalPositions) { return val; } else { var ordinalLength = ordinalPositions.length, i, distance, ordinalIndex; // first look for an exact match in the ordinalpositions array i = ordinalLength; while (i--) { if (ordinalPositions[i] === val) { ordinalIndex = i; break; } } // if that failed, find the intermediate position between the two nearest values i = ordinalLength - 1; while (i--) { if (val > ordinalPositions[i] || i === 0) { // interpolate distance = (val - ordinalPositions[i]) / (ordinalPositions[i + 1] - ordinalPositions[i]); // something between 0 and 1 ordinalIndex = i + distance; break; } } return toIndex ? ordinalIndex : axis.ordinalSlope * (ordinalIndex || 0) + axis.ordinalOffset; } }, /** * Translate from linear (internal) to axis value * * @param Number val The linear abstracted value * @param Boolean fromIndex Translate from an index in the ordinal positions rather than a value */ lin2val: function (val, fromIndex) { var axis = this, ordinalPositions = axis.ordinalPositions; if (!ordinalPositions) { // the visible range contains only equally spaced values return val; } else { var ordinalSlope = axis.ordinalSlope, ordinalOffset = axis.ordinalOffset, i = ordinalPositions.length - 1, linearEquivalentLeft, linearEquivalentRight, distance; // Handle the case where we translate from the index directly, used only // when panning an ordinal axis if (fromIndex) { if (val < 0) { // out of range, in effect panning to the left val = ordinalPositions[0]; } else if (val > i) { // out of range, panning to the right val = ordinalPositions[i]; } else { // split it up i = mathFloor(val); distance = val - i; // the decimal } // Loop down along the ordinal positions. When the linear equivalent of i matches // an ordinal position, interpolate between the left and right values. } else { while (i--) { linearEquivalentLeft = (ordinalSlope * i) + ordinalOffset; if (val >= linearEquivalentLeft) { linearEquivalentRight = (ordinalSlope * (i + 1)) + ordinalOffset; distance = (val - linearEquivalentLeft) / (linearEquivalentRight - linearEquivalentLeft); // something between 0 and 1 break; } } } // If the index is within the range of the ordinal positions, return the associated // or interpolated value. If not, just return the value return distance !== UNDEFINED && ordinalPositions[i] !== UNDEFINED ? ordinalPositions[i] + (distance ? distance * (ordinalPositions[i + 1] - ordinalPositions[i]) : 0) : val; } }, /** * Get the ordinal positions for the entire data set. This is necessary in chart panning * because we need to find out what points or data groups are available outside the * visible range. When a panning operation starts, if an index for the given grouping * does not exists, it is created and cached. This index is deleted on updated data, so * it will be regenerated the next time a panning operation starts. */ getExtendedPositions: function () { var axis = this, chart = axis.chart, grouping = axis.series[0].currentDataGrouping, ordinalIndex = axis.ordinalIndex, key = grouping ? grouping.count + grouping.unitName : 'raw', extremes = axis.getExtremes(), fakeAxis, fakeSeries; // If this is the first time, or the ordinal index is deleted by updatedData, // create it. if (!ordinalIndex) { ordinalIndex = axis.ordinalIndex = {}; } if (!ordinalIndex[key]) { // Create a fake axis object where the extended ordinal positions are emulated fakeAxis = { series: [], getExtremes: function () { return { min: extremes.dataMin, max: extremes.dataMax }; }, options: { ordinal: true }, val2lin: Axis.prototype.val2lin // #2590 }; // Add the fake series to hold the full data, then apply processData to it each(axis.series, function (series) { fakeSeries = { xAxis: fakeAxis, xData: series.xData, chart: chart, destroyGroupedData: noop }; fakeSeries.options = { dataGrouping : grouping ? { enabled: true, forced: true, approximation: 'open', // doesn't matter which, use the fastest units: [[grouping.unitName, [grouping.count]]] } : { enabled: false } }; series.processData.apply(fakeSeries); fakeAxis.series.push(fakeSeries); }); // Run beforeSetTickPositions to compute the ordinalPositions axis.beforeSetTickPositions.apply(fakeAxis); // Cache it ordinalIndex[key] = fakeAxis.ordinalPositions; } return ordinalIndex[key]; }, /** * Find the factor to estimate how wide the plot area would have been if ordinal * gaps were included. This value is used to compute an imagined plot width in order * to establish the data grouping interval. * * A real world case is the intraday-candlestick * example. Without this logic, it would show the correct data grouping when viewing * a range within each day, but once moving the range to include the gap between two * days, the interval would include the cut-away night hours and the data grouping * would be wrong. So the below method tries to compensate by identifying the most * common point interval, in this case days. * * An opposite case is presented in issue #718. We have a long array of daily data, * then one point is appended one hour after the last point. We expect the data grouping * not to change. * * In the future, if we find cases where this estimation doesn't work optimally, we * might need to add a second pass to the data grouping logic, where we do another run * with a greater interval if the number of data groups is more than a certain fraction * of the desired group count. */ getGroupIntervalFactor: function (xMin, xMax, series) { var i = 0, processedXData = series.processedXData, len = processedXData.length, distances = [], median, groupIntervalFactor = this.groupIntervalFactor; // Only do this computation for the first series, let the other inherit it (#2416) if (!groupIntervalFactor) { // Register all the distances in an array for (; i < len - 1; i++) { distances[i] = processedXData[i + 1] - processedXData[i]; } // Sort them and find the median distances.sort(function (a, b) { return a - b; }); median = distances[mathFloor(len / 2)]; // Compensate for series that don't extend through the entire axis extent. #1675. xMin = mathMax(xMin, processedXData[0]); xMax = mathMin(xMax, processedXData[len - 1]); this.groupIntervalFactor = groupIntervalFactor = (len * median) / (xMax - xMin); } // Return the factor needed for data grouping return groupIntervalFactor; }, /** * Make the tick intervals closer because the ordinal gaps make the ticks spread out or cluster */ postProcessTickInterval: function (tickInterval) { // TODO: http://jsfiddle.net/highcharts/FQm4E/1/ // This is a case where this algorithm doesn't work optimally. In this case, the // tick labels are spread out per week, but all the gaps reside within weeks. So // we have a situation where the labels are courser than the ordinal gaps, and // thus the tick interval should not be altered var ordinalSlope = this.ordinalSlope; if (ordinalSlope) { if (!this.options.breaks) { return tickInterval / (ordinalSlope / this.closestPointRange); } else { return this.closestPointRange; } } else { return tickInterval; } } }); // Extending the Chart.pan method for ordinal axes wrap(Chart.prototype, 'pan', function (proceed, e) { var chart = this, xAxis = chart.xAxis[0], chartX = e.chartX, runBase = false; if (xAxis.options.ordinal && xAxis.series.length) { var mouseDownX = chart.mouseDownX, extremes = xAxis.getExtremes(), dataMax = extremes.dataMax, min = extremes.min, max = extremes.max, trimmedRange, hoverPoints = chart.hoverPoints, closestPointRange = xAxis.closestPointRange, pointPixelWidth = xAxis.translationSlope * (xAxis.ordinalSlope || closestPointRange), movedUnits = (mouseDownX - chartX) / pointPixelWidth, // how many ordinal units did we move? extendedAxis = { ordinalPositions: xAxis.getExtendedPositions() }, // get index of all the chart's points ordinalPositions, searchAxisLeft, lin2val = xAxis.lin2val, val2lin = xAxis.val2lin, searchAxisRight; if (!extendedAxis.ordinalPositions) { // we have an ordinal axis, but the data is equally spaced runBase = true; } else if (mathAbs(movedUnits) > 1) { // Remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (movedUnits < 0) { searchAxisLeft = extendedAxis; searchAxisRight = xAxis.ordinalPositions ? xAxis : extendedAxis; } else { searchAxisLeft = xAxis.ordinalPositions ? xAxis : extendedAxis; searchAxisRight = extendedAxis; } // In grouped data series, the last ordinal position represents the grouped data, which is // to the left of the real data max. If we don't compensate for this, we will be allowed // to pan grouped data series passed the right of the plot area. ordinalPositions = searchAxisRight.ordinalPositions; if (dataMax > ordinalPositions[ordinalPositions.length - 1]) { ordinalPositions.push(dataMax); } // Get the new min and max values by getting the ordinal index for the current extreme, // then add the moved units and translate back to values. This happens on the // extended ordinal positions if the new position is out of range, else it happens // on the current x axis which is smaller and faster. chart.fixedRange = max - min; trimmedRange = xAxis.toFixedRange(null, null, lin2val.apply(searchAxisLeft, [ val2lin.apply(searchAxisLeft, [min, true]) + movedUnits, // the new index true // translate from index ]), lin2val.apply(searchAxisRight, [ val2lin.apply(searchAxisRight, [max, true]) + movedUnits, // the new index true // translate from index ]) ); // Apply it if it is within the available data range if (trimmedRange.min >= mathMin(extremes.dataMin, min) && trimmedRange.max <= mathMax(dataMax, max)) { xAxis.setExtremes(trimmedRange.min, trimmedRange.max, true, false, { trigger: 'pan' }); } chart.mouseDownX = chartX; // set new reference for next run css(chart.container, { cursor: 'move' }); } } else { runBase = true; } // revert to the linear chart.pan version if (runBase) { // call the original function proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } }); /** * Extend getSegments by identifying gaps in the ordinal data so that we can draw a gap in the * line or area */ wrap(Series.prototype, 'getSegments', function (proceed) { var series = this, segments, gapSize = series.options.gapSize, xAxis = series.xAxis; // call base method proceed.apply(this, Array.prototype.slice.call(arguments, 1)); if (gapSize) { // properties segments = series.segments; // extension for ordinal breaks each(segments, function (segment, no) { var i = segment.length - 1; while (i--) { if (segment[i + 1].x - segment[i].x > xAxis.closestPointRange * gapSize) { segments.splice( // insert after this one no + 1, 0, segment.splice(i + 1, segment.length - i) ); } } }); } }); /* **************************************************************************** * End ordinal axis logic * *****************************************************************************/ /** * Highstock JS v2.1.3 (2015-02-27) * Highcharts Broken Axis module * * Author: Stephane Vanraes, Torstein Honsi * License: www.highcharts.com/license */ /*global HighchartsAdapter*/ (function (H) { "use strict"; var pick = H.pick, wrap = H.wrap, extend = H.extend, fireEvent = HighchartsAdapter.fireEvent, Axis = H.Axis, Series = H.Series; function stripArguments() { return Array.prototype.slice.call(arguments, 1); } extend(Axis.prototype, { isInBreak: function (brk, val) { var repeat = brk.repeat || Infinity, from = brk.from, length = brk.to - brk.from, test = (val >= from ? (val - from) % repeat : repeat - ((from - val) % repeat)); if (!brk.inclusive) { return (test < length && test !== 0); } else { return (test <= length); } }, isInAnyBreak: function (val, testKeep) { // Sanity Check if (!this.options.breaks) { return false; } var breaks = this.options.breaks, i = breaks.length, inbrk = false, keep = false; while (i--) { if (this.isInBreak(breaks[i], val)) { inbrk = true; if (!keep) { keep = pick(breaks[i].showPoints, this.isXAxis ? false : true); } } } if (inbrk && testKeep) { return inbrk && !keep; } else { return inbrk; } } }); wrap(Axis.prototype, 'setTickPositions', function (proceed) { proceed.apply(this, Array.prototype.slice.call(arguments, 1)); if (this.options.breaks) { var axis = this, tickPositions = this.tickPositions, info = this.tickPositions.info, newPositions = [], i; if (info && info.totalRange >= axis.closestPointRange) { return; } for (i = 0; i < tickPositions.length; i++) { if (!axis.isInAnyBreak(tickPositions[i])) { newPositions.push(tickPositions[i]); } } this.tickPositions = newPositions; this.tickPositions.info = info; } }); wrap(Axis.prototype, 'init', function (proceed, chart, userOptions) { // Force Axis to be not-ordinal when breaks are defined if (userOptions.breaks && userOptions.breaks.length) { userOptions.ordinal = false; } proceed.call(this, chart, userOptions); if (this.options.breaks) { var axis = this; axis.doPostTranslate = true; this.val2lin = function (val) { var nval = val, brk, i; for (i = 0; i < axis.breakArray.length; i++) { brk = axis.breakArray[i]; if (brk.to <= val) { nval -= (brk.len); } else if (brk.from >= val) { break; } else if (axis.isInBreak(brk, val)) { nval -= (val - brk.from); break; } } return nval; }; this.lin2val = function (val) { var nval = val, brk, i; for (i = 0; i < axis.breakArray.length; i++) { brk = axis.breakArray[i]; if (brk.from >= nval) { break; } else if (brk.to < nval) { nval += (brk.to - brk.from); } else if (axis.isInBreak(brk, nval)) { nval += (brk.to - brk.from); } } return nval; }; this.setExtremes = function (newMin, newMax, redraw, animation, eventArguments) { // If trying to set extremes inside a break, extend it to before and after the break ( #3857 ) while (this.isInAnyBreak(newMin)) { newMin -= this.closestPointRange; } while (this.isInAnyBreak(newMax)) { newMax -= this.closestPointRange; } Axis.prototype.setExtremes.call(this, newMin, newMax, redraw, animation, eventArguments); }; this.setAxisTranslation = function (saveOld) { Axis.prototype.setAxisTranslation.call(this, saveOld); var breaks = axis.options.breaks, breakArrayT = [], // Temporary one breakArray = [], length = 0, inBrk, repeat, brk, min = axis.userMin || axis.min, max = axis.userMax || axis.max, start, i, j; // Min & Max Check for (i in breaks) { brk = breaks[i]; if (axis.isInBreak(brk, min)) { min += (brk.to % brk.repeat) - (min % brk.repeat); } if (axis.isInBreak(brk, max)) { max -= (max % brk.repeat) - (brk.from % brk.repeat); } } // Construct an array holding all breaks in the axis for (i in breaks) { brk = breaks[i]; start = brk.from; repeat = brk.repeat || Infinity; while (start - repeat > min) { start -= repeat; } while (start < min) { start += repeat; } for (j = start; j < max; j += repeat) { breakArrayT.push({ value: j, move: 'in' }); breakArrayT.push({ value: j + (brk.to - brk.from), move: 'out', size: brk.breakSize }); } } breakArrayT.sort(function (a, b) { if (a.value === b.value) { return (a.move === 'in' ? 0 : 1) - (b.move === 'in' ? 0 : 1); } else { return a.value - b.value; } }); // Simplify the breaks inBrk = 0; start = min; for (i in breakArrayT) { brk = breakArrayT[i]; inBrk += (brk.move === 'in' ? 1 : -1); if (inBrk === 1 && brk.move === 'in') { start = brk.value; } if (inBrk === 0) { breakArray.push({ from: start, to: brk.value, len: brk.value - start - (brk.size || 0) }); length += brk.value - start - (brk.size || 0); } } axis.breakArray = breakArray; fireEvent(axis, 'afterBreaks'); axis.transA *= ((max - axis.min) / (max - min - length)); axis.min = min; axis.max = max; }; } }); wrap(Series.prototype, 'generatePoints', function (proceed) { proceed.apply(this, stripArguments(arguments)); var series = this, xAxis = series.xAxis, yAxis = series.yAxis, points = series.points, point, i = points.length; if (xAxis && yAxis && (xAxis.options.breaks || yAxis.options.breaks)) { while (i--) { point = points[i]; if (xAxis.isInAnyBreak(point.x, true) || yAxis.isInAnyBreak(point.y, true)) { points.splice(i, 1); this.data[i].destroyElements(); // removes the graphics for this point if they exist } } } }); wrap(H.seriesTypes.column.prototype, 'drawPoints', function (proceed) { proceed.apply(this); var series = this, points = series.points, yAxis = series.yAxis, breaks = yAxis.breakArray || [], point, brk, i, j, y; for (i = 0; i < points.length; i++) { point = points[i]; y = point.stackY || point.y; for (j = 0; j < breaks.length; j++) { brk = breaks[j]; if (y < brk.from) { break; } else if (y > brk.to) { fireEvent(yAxis, 'pointBreak', {point: point, brk: brk}); } else { fireEvent(yAxis, 'pointInBreak', {point: point, brk: brk}); } } } }); }(Highcharts)); /* **************************************************************************** * Start data grouping module * ******************************************************************************/ /*jslint white:true */ var DATA_GROUPING = 'dataGrouping', seriesProto = Series.prototype, tooltipProto = Tooltip.prototype, baseProcessData = seriesProto.processData, baseGeneratePoints = seriesProto.generatePoints, baseDestroy = seriesProto.destroy, baseTooltipFooterHeaderFormatter = tooltipProto.tooltipFooterHeaderFormatter, NUMBER = 'number', commonOptions = { approximation: 'average', // average, open, high, low, close, sum //enabled: null, // (true for stock charts, false for basic), //forced: undefined, groupPixelWidth: 2, // the first one is the point or start value, the second is the start value if we're dealing with range, // the third one is the end value if dealing with a range dateTimeLabelFormats: { millisecond: ['%A, %b %e, %H:%M:%S.%L', '%A, %b %e, %H:%M:%S.%L', '-%H:%M:%S.%L'], second: ['%A, %b %e, %H:%M:%S', '%A, %b %e, %H:%M:%S', '-%H:%M:%S'], minute: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'], hour: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'], day: ['%A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'], week: ['Week from %A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'], month: ['%B %Y', '%B', '-%B %Y'], year: ['%Y', '%Y', '-%Y'] } // smoothed = false, // enable this for navigator series only }, specificOptions = { // extends common options line: {}, spline: {}, area: {}, areaspline: {}, column: { approximation: 'sum', groupPixelWidth: 10 }, arearange: { approximation: 'range' }, areasplinerange: { approximation: 'range' }, columnrange: { approximation: 'range', groupPixelWidth: 10 }, candlestick: { approximation: 'ohlc', groupPixelWidth: 10 }, ohlc: { approximation: 'ohlc', groupPixelWidth: 5 } }, // units are defined in a separate array to allow complete overriding in case of a user option defaultDataGroupingUnits = [[ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1] ], [ 'week', [1] ], [ 'month', [1, 3, 6] ], [ 'year', null ] ], /** * Define the available approximation types. The data grouping approximations takes an array * or numbers as the first parameter. In case of ohlc, four arrays are sent in as four parameters. * Each array consists only of numbers. In case null values belong to the group, the property * .hasNulls will be set to true on the array. */ approximations = { sum: function (arr) { var len = arr.length, ret; // 1. it consists of nulls exclusively if (!len && arr.hasNulls) { ret = null; // 2. it has a length and real values } else if (len) { ret = 0; while (len--) { ret += arr[len]; } } // 3. it has zero length, so just return undefined // => doNothing() return ret; }, average: function (arr) { var len = arr.length, ret = approximations.sum(arr); // If we have a number, return it divided by the length. If not, return // null or undefined based on what the sum method finds. if (typeof ret === NUMBER && len) { ret = ret / len; } return ret; }, open: function (arr) { return arr.length ? arr[0] : (arr.hasNulls ? null : UNDEFINED); }, high: function (arr) { return arr.length ? arrayMax(arr) : (arr.hasNulls ? null : UNDEFINED); }, low: function (arr) { return arr.length ? arrayMin(arr) : (arr.hasNulls ? null : UNDEFINED); }, close: function (arr) { return arr.length ? arr[arr.length - 1] : (arr.hasNulls ? null : UNDEFINED); }, // ohlc and range are special cases where a multidimensional array is input and an array is output ohlc: function (open, high, low, close) { open = approximations.open(open); high = approximations.high(high); low = approximations.low(low); close = approximations.close(close); if (typeof open === NUMBER || typeof high === NUMBER || typeof low === NUMBER || typeof close === NUMBER) { return [open, high, low, close]; } // else, return is undefined }, range: function (low, high) { low = approximations.low(low); high = approximations.high(high); if (typeof low === NUMBER || typeof high === NUMBER) { return [low, high]; } // else, return is undefined } }; /*jslint white:false */ /** * Takes parallel arrays of x and y data and groups the data into intervals defined by groupPositions, a collection * of starting x values for each group. */ seriesProto.groupData = function (xData, yData, groupPositions, approximation) { var series = this, data = series.data, dataOptions = series.options.data, groupedXData = [], groupedYData = [], dataLength = xData.length, pointX, pointY, groupedY, handleYData = !!yData, // when grouping the fake extended axis for panning, we don't need to consider y values = [[], [], [], []], approximationFn = typeof approximation === 'function' ? approximation : approximations[approximation], pointArrayMap = series.pointArrayMap, pointArrayMapLength = pointArrayMap && pointArrayMap.length, i; // Start with the first point within the X axis range (#2696) for (i = 0; i <= dataLength; i++) { if (xData[i] >= groupPositions[0]) { break; } } for (; i <= dataLength; i++) { // when a new group is entered, summarize and initiate the previous group while ((groupPositions[1] !== UNDEFINED && xData[i] >= groupPositions[1]) || i === dataLength) { // get the last group // get group x and y pointX = groupPositions.shift(); groupedY = approximationFn.apply(0, values); // push the grouped data if (groupedY !== UNDEFINED) { groupedXData.push(pointX); groupedYData.push(groupedY); } // reset the aggregate arrays values[0] = []; values[1] = []; values[2] = []; values[3] = []; // don't loop beyond the last group if (i === dataLength) { break; } } // break out if (i === dataLength) { break; } // for each raw data point, push it to an array that contains all values for this specific group if (pointArrayMap) { var index = series.cropStart + i, point = (data && data[index]) || series.pointClass.prototype.applyOptions.apply({ series: series }, [dataOptions[index]]), j, val; for (j = 0; j < pointArrayMapLength; j++) { val = point[pointArrayMap[j]]; if (typeof val === NUMBER) { values[j].push(val); } else if (val === null) { values[j].hasNulls = true; } } } else { pointY = handleYData ? yData[i] : null; if (typeof pointY === NUMBER) { values[0].push(pointY); } else if (pointY === null) { values[0].hasNulls = true; } } } return [groupedXData, groupedYData]; }; /** * Extend the basic processData method, that crops the data to the current zoom * range, with data grouping logic. */ seriesProto.processData = function () { var series = this, chart = series.chart, options = series.options, dataGroupingOptions = options[DATA_GROUPING], groupingEnabled = series.allowDG !== false && dataGroupingOptions && pick(dataGroupingOptions.enabled, chart.options._stock), hasGroupedData; // run base method series.forceCrop = groupingEnabled; // #334 series.groupPixelWidth = null; // #2110 series.hasProcessed = true; // #2692 // skip if processData returns false or if grouping is disabled (in that order) if (baseProcessData.apply(series, arguments) === false || !groupingEnabled) { return; } else { series.destroyGroupedData(); } var i, processedXData = series.processedXData, processedYData = series.processedYData, plotSizeX = chart.plotSizeX, xAxis = series.xAxis, ordinal = xAxis.options.ordinal, groupPixelWidth = series.groupPixelWidth = xAxis.getGroupPixelWidth && xAxis.getGroupPixelWidth(), nonGroupedPointRange = series.pointRange; // Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth if (groupPixelWidth) { hasGroupedData = true; series.points = null; // force recreation of point instances in series.translate var extremes = xAxis.getExtremes(), xMin = extremes.min, xMax = extremes.max, groupIntervalFactor = (ordinal && xAxis.getGroupIntervalFactor(xMin, xMax, series)) || 1, interval = (groupPixelWidth * (xMax - xMin) / plotSizeX) * groupIntervalFactor, groupPositions = xAxis.getTimeTicks( xAxis.normalizeTimeTickInterval(interval, dataGroupingOptions.units || defaultDataGroupingUnits), xMin, xMax, xAxis.options.startOfWeek, processedXData, series.closestPointRange ), groupedXandY = seriesProto.groupData.apply(series, [processedXData, processedYData, groupPositions, dataGroupingOptions.approximation]), groupedXData = groupedXandY[0], groupedYData = groupedXandY[1]; // prevent the smoothed data to spill out left and right, and make // sure data is not shifted to the left if (dataGroupingOptions.smoothed) { i = groupedXData.length - 1; groupedXData[i] = xMax; while (i-- && i > 0) { groupedXData[i] += interval / 2; } groupedXData[0] = xMin; } // record what data grouping values were used series.currentDataGrouping = groupPositions.info; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = groupPositions.info.totalRange; } series.closestPointRange = groupPositions.info.totalRange; // Make sure the X axis extends to show the first group (#2533) if (defined(groupedXData[0]) && groupedXData[0] < xAxis.dataMin) { if (xAxis.min === xAxis.dataMin) { xAxis.min = groupedXData[0]; } xAxis.dataMin = groupedXData[0]; } // set series props series.processedXData = groupedXData; series.processedYData = groupedYData; } else { series.currentDataGrouping = null; series.pointRange = nonGroupedPointRange; } series.hasGroupedData = hasGroupedData; }; /** * Destroy the grouped data points. #622, #740 */ seriesProto.destroyGroupedData = function () { var groupedData = this.groupedData; // clear previous groups each(groupedData || [], function (point, i) { if (point) { groupedData[i] = point.destroy ? point.destroy() : null; } }); this.groupedData = null; }; /** * Override the generatePoints method by adding a reference to grouped data */ seriesProto.generatePoints = function () { baseGeneratePoints.apply(this); // record grouped data in order to let it be destroyed the next time processData runs this.destroyGroupedData(); // #622 this.groupedData = this.hasGroupedData ? this.points : null; }; /** * Extend the original method, make the tooltip's header reflect the grouped range */ tooltipProto.tooltipFooterHeaderFormatter = function (point, isFooter) { var tooltip = this, series = point.series, options = series.options, tooltipOptions = series.tooltipOptions, dataGroupingOptions = options.dataGrouping, xDateFormat = tooltipOptions.xDateFormat, xDateFormatEnd, xAxis = series.xAxis, currentDataGrouping, dateTimeLabelFormats, labelFormats, formattedKey, ret; // apply only to grouped series if (xAxis && xAxis.options.type === 'datetime' && dataGroupingOptions && isNumber(point.key)) { // set variables currentDataGrouping = series.currentDataGrouping; dateTimeLabelFormats = dataGroupingOptions.dateTimeLabelFormats; // if we have grouped data, use the grouping information to get the right format if (currentDataGrouping) { labelFormats = dateTimeLabelFormats[currentDataGrouping.unitName]; if (currentDataGrouping.count === 1) { xDateFormat = labelFormats[0]; } else { xDateFormat = labelFormats[1]; xDateFormatEnd = labelFormats[2]; } // if not grouped, and we don't have set the xDateFormat option, get the best fit, // so if the least distance between points is one minute, show it, but if the // least distance is one day, skip hours and minutes etc. } else if (!xDateFormat && dateTimeLabelFormats) { xDateFormat = tooltip.getXDateFormat(point, tooltipOptions, xAxis); } // now format the key formattedKey = dateFormat(xDateFormat, point.key); if (xDateFormatEnd) { formattedKey += dateFormat(xDateFormatEnd, point.key + currentDataGrouping.totalRange - 1); } // return the replaced format ret = tooltipOptions[(isFooter ? 'footer' : 'header') + 'Format'].replace('{point.key}', formattedKey); // else, fall back to the regular formatter } else { ret = baseTooltipFooterHeaderFormatter.call(tooltip, point, isFooter); } return ret; }; /** * Extend the series destroyer */ seriesProto.destroy = function () { var series = this, groupedData = series.groupedData || [], i = groupedData.length; while (i--) { if (groupedData[i]) { groupedData[i].destroy(); } } baseDestroy.apply(series); }; // Handle default options for data grouping. This must be set at runtime because some series types are // defined after this. wrap(seriesProto, 'setOptions', function (proceed, itemOptions) { var options = proceed.call(this, itemOptions), type = this.type, plotOptions = this.chart.options.plotOptions, defaultOptions = defaultPlotOptions[type].dataGrouping; if (specificOptions[type]) { // #1284 if (!defaultOptions) { defaultOptions = merge(commonOptions, specificOptions[type]); } options.dataGrouping = merge( defaultOptions, plotOptions.series && plotOptions.series.dataGrouping, // #1228 plotOptions[type].dataGrouping, // Set by the StockChart constructor itemOptions.dataGrouping ); } if (this.chart.options._stock) { this.requireSorting = true; } return options; }); /** * When resetting the scale reset the hasProccessed flag to avoid taking previous data grouping * of neighbour series into accound when determining group pixel width (#2692). */ wrap(Axis.prototype, 'setScale', function (proceed) { proceed.call(this); each(this.series, function (series) { series.hasProcessed = false; }); }); /** * Get the data grouping pixel width based on the greatest defined individual width * of the axis' series, and if whether one of the axes need grouping. */ Axis.prototype.getGroupPixelWidth = function () { var series = this.series, len = series.length, i, groupPixelWidth = 0, doGrouping = false, dataLength, dgOptions; // If multiple series are compared on the same x axis, give them the same // group pixel width (#334) i = len; while (i--) { dgOptions = series[i].options.dataGrouping; if (dgOptions) { groupPixelWidth = mathMax(groupPixelWidth, dgOptions.groupPixelWidth); } } // If one of the series needs grouping, apply it to all (#1634) i = len; while (i--) { dgOptions = series[i].options.dataGrouping; if (dgOptions && series[i].hasProcessed) { // #2692 dataLength = (series[i].processedXData || series[i].data).length; // Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth if (series[i].groupPixelWidth || dataLength > (this.chart.plotSizeX / groupPixelWidth) || (dataLength && dgOptions.forced)) { doGrouping = true; } } } return doGrouping ? groupPixelWidth : 0; }; /* **************************************************************************** * End data grouping module * ******************************************************************************//* **************************************************************************** * Start OHLC series code * *****************************************************************************/ // 1 - Set default options defaultPlotOptions.ohlc = merge(defaultPlotOptions.column, { lineWidth: 1, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span> <b> {series.name}</b><br/>' + // docs 'Open: {point.open}<br/>' + 'High: {point.high}<br/>' + 'Low: {point.low}<br/>' + 'Close: {point.close}<br/>' }, states: { hover: { lineWidth: 3 } }, threshold: null //upColor: undefined }); // 2 - Create the OHLCSeries object var OHLCSeries = extendClass(seriesTypes.column, { type: 'ohlc', pointArrayMap: ['open', 'high', 'low', 'close'], // array point configs are mapped to this toYData: function (point) { // return a plain array for speedy calculation return [point.open, point.high, point.low, point.close]; }, pointValKey: 'high', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'color', 'stroke-width': 'lineWidth' }, upColorProp: 'stroke', /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.column.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upColor = options.upColor || series.color, seriesDownPointAttr = merge(series.pointAttr), upColorProp = series.upColorProp; seriesDownPointAttr[''][upColorProp] = upColor; seriesDownPointAttr.hover[upColorProp] = stateOptions.hover.upColor || upColor; seriesDownPointAttr.select[upColorProp] = stateOptions.select.upColor || upColor; each(series.points, function (point) { if (point.open < point.close && !point.options.color) { point.pointAttr = seriesDownPointAttr; } }); }, /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis; seriesTypes.column.prototype.translate.apply(series); // do the translation each(series.points, function (point) { // the graphics if (point.open !== null) { point.plotOpen = yAxis.translate(point.open, 0, 1, 0, 1); } if (point.close !== null) { point.plotClose = yAxis.translate(point.close, 0, 1, 0, 1); } }); }, /** * Draw the data points */ drawPoints: function () { var series = this, points = series.points, chart = series.chart, pointAttr, plotOpen, plotClose, crispCorr, halfWidth, path, graphic, crispX; each(points, function (point) { if (point.plotY !== UNDEFINED) { graphic = point.graphic; pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || series.pointAttr[NORMAL_STATE]; // crisp vector coordinates crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathRound(point.plotX) - crispCorr; // #2596 halfWidth = mathRound(point.shapeArgs.width / 2); // the vertical stem path = [ 'M', crispX, mathRound(point.yBottom), 'L', crispX, mathRound(point.plotY) ]; // open if (point.open !== null) { plotOpen = mathRound(point.plotOpen) + crispCorr; path.push( 'M', crispX, plotOpen, 'L', crispX - halfWidth, plotOpen ); } // close if (point.close !== null) { plotClose = mathRound(point.plotClose) + crispCorr; path.push( 'M', crispX, plotClose, 'L', crispX + halfWidth, plotClose ); } // create and/or update the graphic if (graphic) { graphic.animate({ d: path }); } else { point.graphic = chart.renderer.path(path) .attr(pointAttr) .add(series.group); } } }); }, /** * Disable animation */ animate: null }); seriesTypes.ohlc = OHLCSeries; /* **************************************************************************** * End OHLC series code * *****************************************************************************/ /* **************************************************************************** * Start Candlestick series code * *****************************************************************************/ // 1 - set default options defaultPlotOptions.candlestick = merge(defaultPlotOptions.column, { lineColor: 'black', lineWidth: 1, states: { hover: { lineWidth: 2 } }, tooltip: defaultPlotOptions.ohlc.tooltip, threshold: null, upColor: 'white' // upLineColor: null }); // 2 - Create the CandlestickSeries object var CandlestickSeries = extendClass(OHLCSeries, { type: 'candlestick', /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'color', stroke: 'lineColor', 'stroke-width': 'lineWidth' }, upColorProp: 'fill', /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.ohlc.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upLineColor = options.upLineColor || options.lineColor, hoverStroke = stateOptions.hover.upLineColor || upLineColor, selectStroke = stateOptions.select.upLineColor || upLineColor; // Add custom line color for points going up (close > open). // Fill is handled by OHLCSeries' getAttribs. each(series.points, function (point) { if (point.open < point.close) { point.pointAttr[''].stroke = upLineColor; point.pointAttr.hover.stroke = hoverStroke; point.pointAttr.select.stroke = selectStroke; } }); }, /** * Draw the data points */ drawPoints: function () { var series = this, //state = series.state, points = series.points, chart = series.chart, pointAttr, seriesPointAttr = series.pointAttr[''], plotOpen, plotClose, topBox, bottomBox, hasTopWhisker, hasBottomWhisker, crispCorr, crispX, graphic, path, halfWidth; each(points, function (point) { graphic = point.graphic; if (point.plotY !== UNDEFINED) { pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || seriesPointAttr; // crisp vector coordinates crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathRound(point.plotX) - crispCorr; // #2596 plotOpen = point.plotOpen; plotClose = point.plotClose; topBox = math.min(plotOpen, plotClose); bottomBox = math.max(plotOpen, plotClose); halfWidth = mathRound(point.shapeArgs.width / 2); hasTopWhisker = mathRound(topBox) !== mathRound(point.plotY); hasBottomWhisker = bottomBox !== point.yBottom; topBox = mathRound(topBox) + crispCorr; bottomBox = mathRound(bottomBox) + crispCorr; // create the path path = [ 'M', crispX - halfWidth, bottomBox, 'L', crispX - halfWidth, topBox, 'L', crispX + halfWidth, topBox, 'L', crispX + halfWidth, bottomBox, 'Z', // Use a close statement to ensure a nice rectangle #2602 'M', crispX, topBox, 'L', crispX, hasTopWhisker ? mathRound(point.plotY) : topBox, // #460, #2094 'M', crispX, bottomBox, 'L', crispX, hasBottomWhisker ? mathRound(point.yBottom) : bottomBox // #460, #2094 ]; if (graphic) { graphic.animate({ d: path }); } else { point.graphic = chart.renderer.path(path) .attr(pointAttr) .add(series.group) .shadow(series.options.shadow); } } }); } }); seriesTypes.candlestick = CandlestickSeries; /* **************************************************************************** * End Candlestick series code * *****************************************************************************/ /* **************************************************************************** * Start Flags series code * *****************************************************************************/ var symbols = SVGRenderer.prototype.symbols; // 1 - set default options defaultPlotOptions.flags = merge(defaultPlotOptions.column, { fillColor: 'white', lineWidth: 1, pointRange: 0, // #673 //radius: 2, shape: 'flag', stackDistance: 12, states: { hover: { lineColor: 'black', fillColor: '#FCFFC5' } }, style: { fontSize: '11px', fontWeight: 'bold', textAlign: 'center' }, tooltip: { pointFormat: '{point.text}<br/>' }, threshold: null, y: -30 }); // 2 - Create the CandlestickSeries object seriesTypes.flags = extendClass(seriesTypes.column, { type: 'flags', sorted: false, noSharedTooltip: true, allowDG: false, takeOrdinalPosition: false, // #1074 trackerGroups: ['markerGroup'], forceCrop: true, /** * Inherit the initialization from base Series */ init: Series.prototype.init, /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'fillColor', stroke: 'color', 'stroke-width': 'lineWidth', r: 'radius' }, /** * Extend the translate method by placing the point on the related series */ translate: function () { seriesTypes.column.prototype.translate.apply(this); var series = this, options = series.options, chart = series.chart, points = series.points, cursor = points.length - 1, point, lastPoint, optionsOnSeries = options.onSeries, onSeries = optionsOnSeries && chart.get(optionsOnSeries), step = onSeries && onSeries.options.step, onData = onSeries && onSeries.points, i = onData && onData.length, xAxis = series.xAxis, xAxisExt = xAxis.getExtremes(), leftPoint, lastX, rightPoint, currentDataGrouping; // relate to a master series if (onSeries && onSeries.visible && i) { currentDataGrouping = onSeries.currentDataGrouping; lastX = onData[i - 1].x + (currentDataGrouping ? currentDataGrouping.totalRange : 0); // #2374 // sort the data points points.sort(function (a, b) { return (a.x - b.x); }); while (i-- && points[cursor]) { point = points[cursor]; leftPoint = onData[i]; if (leftPoint.x <= point.x && leftPoint.plotY !== UNDEFINED) { if (point.x <= lastX) { // #803 point.plotY = leftPoint.plotY; // interpolate between points, #666 if (leftPoint.x < point.x && !step) { rightPoint = onData[i + 1]; if (rightPoint && rightPoint.plotY !== UNDEFINED) { point.plotY += ((point.x - leftPoint.x) / (rightPoint.x - leftPoint.x)) * // the distance ratio, between 0 and 1 (rightPoint.plotY - leftPoint.plotY); // the y distance } } } cursor--; i++; // check again for points in the same x position if (cursor < 0) { break; } } } } // Add plotY position and handle stacking each(points, function (point, i) { var stackIndex; // Undefined plotY means the point is either on axis, outside series range or hidden series. // If the series is outside the range of the x axis it should fall through with // an undefined plotY, but then we must remove the shapeArgs (#847). if (point.plotY === UNDEFINED) { if (point.x >= xAxisExt.min && point.x <= xAxisExt.max) { // we're inside xAxis range point.plotY = chart.chartHeight - xAxis.bottom - (xAxis.opposite ? xAxis.height : 0) + xAxis.offset - chart.plotTop; } else { point.shapeArgs = {}; // 847 } } // if multiple flags appear at the same x, order them into a stack lastPoint = points[i - 1]; if (lastPoint && lastPoint.plotX === point.plotX) { if (lastPoint.stackIndex === UNDEFINED) { lastPoint.stackIndex = 0; } stackIndex = lastPoint.stackIndex + 1; } point.stackIndex = stackIndex; // #3639 }); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, seriesPointAttr = series.pointAttr[''], points = series.points, chart = series.chart, renderer = chart.renderer, plotX, plotY, options = series.options, optionsY = options.y, shape, i, point, graphic, stackIndex, crisp = (options.lineWidth % 2 / 2), anchorX, anchorY, outsideRight; i = points.length; while (i--) { point = points[i]; outsideRight = point.plotX > series.xAxis.len; plotX = point.plotX + (outsideRight ? crisp : -crisp); stackIndex = point.stackIndex; shape = point.options.shape || options.shape; plotY = point.plotY; if (plotY !== UNDEFINED) { plotY = point.plotY + optionsY + crisp - (stackIndex !== UNDEFINED && stackIndex * options.stackDistance); } anchorX = stackIndex ? UNDEFINED : point.plotX + crisp; // skip connectors for higher level stacked points anchorY = stackIndex ? UNDEFINED : point.plotY; graphic = point.graphic; // only draw the point if y is defined and the flag is within the visible area if (plotY !== UNDEFINED && plotX >= 0 && !outsideRight) { // shortcuts pointAttr = point.pointAttr[point.selected ? 'select' : ''] || seriesPointAttr; if (graphic) { // update graphic.attr({ x: plotX, y: plotY, r: pointAttr.r, anchorX: anchorX, anchorY: anchorY }); } else { graphic = point.graphic = renderer.label( point.options.title || options.title || 'A', plotX, plotY, shape, anchorX, anchorY, options.useHTML ) .css(merge(options.style, point.style)) .attr(pointAttr) .attr({ align: shape === 'flag' ? 'left' : 'center', width: options.width, height: options.height }) .add(series.markerGroup) .shadow(options.shadow); } // Set the tooltip anchor position point.tooltipPos = [plotX, plotY]; } else if (graphic) { point.graphic = graphic.destroy(); } } }, /** * Extend the column trackers with listeners to expand and contract stacks */ drawTracker: function () { var series = this, points = series.points; TrackerMixin.drawTrackerPoint.apply(this); // Bring each stacked flag up on mouse over, this allows readability of vertically // stacked elements as well as tight points on the x axis. #1924. each(points, function (point) { var graphic = point.graphic; if (graphic) { addEvent(graphic.element, 'mouseover', function () { // Raise this point if (point.stackIndex > 0 && !point.raised) { point._y = graphic.y; graphic.attr({ y: point._y - 8 }); point.raised = true; } // Revert other raised points each(points, function (otherPoint) { if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) { otherPoint.graphic.attr({ y: otherPoint._y }); otherPoint.raised = false; } }); }); } }); }, /** * Disable animation */ animate: noop, buildKDTree: noop, setClip: noop }); // create the flag icon with anchor symbols.flag = function (x, y, w, h, options) { var anchorX = (options && options.anchorX) || x, anchorY = (options && options.anchorY) || y; return [ 'M', anchorX, anchorY, 'L', x, y + h, x, y, x + w, y, x + w, y + h, x, y + h, 'M', anchorX, anchorY, 'Z' ]; }; // create the circlepin and squarepin icons with anchor each(['circle', 'square'], function (shape) { symbols[shape + 'pin'] = function (x, y, w, h, options) { var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path = symbols[shape](x, y, w, h), labelTopOrBottomY; if (anchorX && anchorY) { // if the label is below the anchor, draw the connecting line from the top edge of the label // otherwise start drawing from the bottom edge labelTopOrBottomY = (y > anchorY) ? y : y + h; path.push('M', anchorX, labelTopOrBottomY, 'L', anchorX, anchorY); } return path; }; }); // The symbol callbacks are generated on the SVGRenderer object in all browsers. Even // VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === Highcharts.VMLRenderer) { each(['flag', 'circlepin', 'squarepin'], function (shape) { VMLRenderer.prototype.symbols[shape] = symbols[shape]; }); } /* **************************************************************************** * End Flags series code * *****************************************************************************/ /* **************************************************************************** * Start Scroller code * *****************************************************************************/ var units = [].concat(defaultDataGroupingUnits), // copy defaultSeriesType, // Finding the min or max of a set of variables where we don't know if they are defined, // is a pattern that is repeated several places in Highcharts. Consider making this // a global utility method. numExt = function (extreme) { var numbers = grep(arguments, function (n) { return typeof n === 'number'; }); if (numbers.length) { return Math[extreme].apply(0, numbers); } }; // add more resolution to units units[4] = ['day', [1, 2, 3, 4]]; // allow more days units[5] = ['week', [1, 2, 3]]; // allow more weeks defaultSeriesType = seriesTypes.areaspline === UNDEFINED ? 'line' : 'areaspline'; extend(defaultOptions, { navigator: { //enabled: true, handles: { backgroundColor: '#ebe7e8', borderColor: '#b2b1b6' }, height: 40, margin: 25, maskFill: 'rgba(128,179,236,0.3)', maskInside: true, outlineColor: '#b2b1b6', outlineWidth: 1, series: { type: defaultSeriesType, color: '#4572A7', compare: null, fillOpacity: 0.05, dataGrouping: { approximation: 'average', enabled: true, groupPixelWidth: 2, smoothed: true, units: units }, dataLabels: { enabled: false, zIndex: 2 // #1839 }, id: PREFIX + 'navigator-series', lineColor: '#4572A7', lineWidth: 1, marker: { enabled: false }, pointRange: 0, shadow: false, threshold: null }, //top: undefined, xAxis: { tickWidth: 0, lineWidth: 0, gridLineColor: '#EEE', gridLineWidth: 1, tickPixelInterval: 200, labels: { align: 'left', style: { color: '#888' }, x: 3, y: -4 }, crosshair: false }, yAxis: { gridLineWidth: 0, startOnTick: false, endOnTick: false, minPadding: 0.1, maxPadding: 0.1, labels: { enabled: false }, crosshair: false, title: { text: null }, tickWidth: 0 } }, scrollbar: { //enabled: true height: isTouchDevice ? 20 : 14, barBackgroundColor: '#bfc8d1', barBorderRadius: 0, barBorderWidth: 1, barBorderColor: '#bfc8d1', buttonArrowColor: '#666', buttonBackgroundColor: '#ebe7e8', buttonBorderColor: '#bbb', buttonBorderRadius: 0, buttonBorderWidth: 1, minWidth: 6, rifleColor: '#666', trackBackgroundColor: '#eeeeee', trackBorderColor: '#eeeeee', trackBorderWidth: 1, // trackBorderRadius: 0 liveRedraw: hasSVG && !isTouchDevice } }); /** * The Scroller class * @param {Object} chart */ function Scroller(chart) { var chartOptions = chart.options, navigatorOptions = chartOptions.navigator, navigatorEnabled = navigatorOptions.enabled, scrollbarOptions = chartOptions.scrollbar, scrollbarEnabled = scrollbarOptions.enabled, height = navigatorEnabled ? navigatorOptions.height : 0, scrollbarHeight = scrollbarEnabled ? scrollbarOptions.height : 0; this.handles = []; this.scrollbarButtons = []; this.elementsToDestroy = []; // Array containing the elements to destroy when Scroller is destroyed this.chart = chart; this.setBaseSeries(); this.height = height; this.scrollbarHeight = scrollbarHeight; this.scrollbarEnabled = scrollbarEnabled; this.navigatorEnabled = navigatorEnabled; this.navigatorOptions = navigatorOptions; this.scrollbarOptions = scrollbarOptions; this.outlineHeight = height + scrollbarHeight; // Run scroller this.init(); } Scroller.prototype = { /** * Draw one of the handles on the side of the zoomed range in the navigator * @param {Number} x The x center for the handle * @param {Number} index 0 for left and 1 for right */ drawHandle: function (x, index) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, elementsToDestroy = scroller.elementsToDestroy, handles = scroller.handles, handlesOptions = scroller.navigatorOptions.handles, attr = { fill: handlesOptions.backgroundColor, stroke: handlesOptions.borderColor, 'stroke-width': 1 }, tempElem; // create the elements if (!scroller.rendered) { // the group handles[index] = renderer.g('navigator-handle-' + ['left', 'right'][index]) .css({ cursor: 'ew-resize' }) .attr({ zIndex: 4 - index }) // zIndex = 3 for right handle, 4 for left .add(); // the rectangle tempElem = renderer.rect(-4.5, 0, 9, 16, 0, 1) .attr(attr) .add(handles[index]); elementsToDestroy.push(tempElem); // the rifles tempElem = renderer.path([ 'M', -1.5, 4, 'L', -1.5, 12, 'M', 0.5, 4, 'L', 0.5, 12 ]).attr(attr) .add(handles[index]); elementsToDestroy.push(tempElem); } // Place it handles[index][chart.isResizing ? 'animate' : 'attr']({ translateX: scroller.scrollerLeft + scroller.scrollbarHeight + parseInt(x, 10), translateY: scroller.top + scroller.height / 2 - 8 }); }, /** * Draw the scrollbar buttons with arrows * @param {Number} index 0 is left, 1 is right */ drawScrollbarButton: function (index) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, elementsToDestroy = scroller.elementsToDestroy, scrollbarButtons = scroller.scrollbarButtons, scrollbarHeight = scroller.scrollbarHeight, scrollbarOptions = scroller.scrollbarOptions, tempElem; if (!scroller.rendered) { scrollbarButtons[index] = renderer.g().add(scroller.scrollbarGroup); tempElem = renderer.rect( -0.5, -0.5, scrollbarHeight + 1, // +1 to compensate for crispifying in rect method scrollbarHeight + 1, scrollbarOptions.buttonBorderRadius, scrollbarOptions.buttonBorderWidth ).attr({ stroke: scrollbarOptions.buttonBorderColor, 'stroke-width': scrollbarOptions.buttonBorderWidth, fill: scrollbarOptions.buttonBackgroundColor }).add(scrollbarButtons[index]); elementsToDestroy.push(tempElem); tempElem = renderer.path([ 'M', scrollbarHeight / 2 + (index ? -1 : 1), scrollbarHeight / 2 - 3, 'L', scrollbarHeight / 2 + (index ? -1 : 1), scrollbarHeight / 2 + 3, scrollbarHeight / 2 + (index ? 2 : -2), scrollbarHeight / 2 ]).attr({ fill: scrollbarOptions.buttonArrowColor }).add(scrollbarButtons[index]); elementsToDestroy.push(tempElem); } // adjust the right side button to the varying length of the scroll track if (index) { scrollbarButtons[index].attr({ translateX: scroller.scrollerWidth - scrollbarHeight }); } }, /** * Render the navigator and scroll bar * @param {Number} min X axis value minimum * @param {Number} max X axis value maximum * @param {Number} pxMin Pixel value minimum * @param {Number} pxMax Pixel value maximum */ render: function (min, max, pxMin, pxMax) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, navigatorLeft, navigatorWidth, scrollerLeft, scrollerWidth, scrollbarGroup = scroller.scrollbarGroup, navigatorGroup = scroller.navigatorGroup, scrollbar = scroller.scrollbar, xAxis = scroller.xAxis, scrollbarTrack = scroller.scrollbarTrack, scrollbarHeight = scroller.scrollbarHeight, scrollbarEnabled = scroller.scrollbarEnabled, navigatorOptions = scroller.navigatorOptions, scrollbarOptions = scroller.scrollbarOptions, scrollbarMinWidth = scrollbarOptions.minWidth, height = scroller.height, top = scroller.top, navigatorEnabled = scroller.navigatorEnabled, outlineWidth = navigatorOptions.outlineWidth, halfOutline = outlineWidth / 2, zoomedMin, zoomedMax, range, scrX, scrWidth, scrollbarPad = 0, outlineHeight = scroller.outlineHeight, barBorderRadius = scrollbarOptions.barBorderRadius, strokeWidth, scrollbarStrokeWidth = scrollbarOptions.barBorderWidth, centerBarX, outlineTop = top + halfOutline, verb, unionExtremes; // don't render the navigator until we have data (#486) if (isNaN(min)) { return; } scroller.navigatorLeft = navigatorLeft = pick( xAxis.left, chart.plotLeft + scrollbarHeight // in case of scrollbar only, without navigator ); scroller.navigatorWidth = navigatorWidth = pick(xAxis.len, chart.plotWidth - 2 * scrollbarHeight); scroller.scrollerLeft = scrollerLeft = navigatorLeft - scrollbarHeight; scroller.scrollerWidth = scrollerWidth = scrollerWidth = navigatorWidth + 2 * scrollbarHeight; // Set the scroller x axis extremes to reflect the total. The navigator extremes // should always be the extremes of the union of all series in the chart as // well as the navigator series. if (xAxis.getExtremes) { unionExtremes = scroller.getUnionExtremes(true); if (unionExtremes && (unionExtremes.dataMin !== xAxis.min || unionExtremes.dataMax !== xAxis.max)) { xAxis.setExtremes(unionExtremes.dataMin, unionExtremes.dataMax, true, false); } } // Get the pixel position of the handles pxMin = pick(pxMin, xAxis.translate(min)); pxMax = pick(pxMax, xAxis.translate(max)); if (isNaN(pxMin) || mathAbs(pxMin) === Infinity) { // Verify (#1851, #2238) pxMin = 0; pxMax = scrollerWidth; } // Are we below the minRange? (#2618) if (xAxis.translate(pxMax, true) - xAxis.translate(pxMin, true) < chart.xAxis[0].minRange) { return; } // handles are allowed to cross, but never exceed the plot area scroller.zoomedMax = mathMin(mathMax(pxMin, pxMax), navigatorWidth); scroller.zoomedMin = mathMax(scroller.fixedWidth ? scroller.zoomedMax - scroller.fixedWidth : mathMin(pxMin, pxMax), 0); scroller.range = scroller.zoomedMax - scroller.zoomedMin; zoomedMax = mathRound(scroller.zoomedMax); zoomedMin = mathRound(scroller.zoomedMin); range = zoomedMax - zoomedMin; // on first render, create all elements if (!scroller.rendered) { if (navigatorEnabled) { // draw the navigator group scroller.navigatorGroup = navigatorGroup = renderer.g('navigator') .attr({ zIndex: 3 }) .add(); scroller.leftShade = renderer.rect() .attr({ fill: navigatorOptions.maskFill }).add(navigatorGroup); if (navigatorOptions.maskInside) { scroller.leftShade.css({ cursor: 'ew-resize '}); } else { scroller.rightShade = renderer.rect() .attr({ fill: navigatorOptions.maskFill }).add(navigatorGroup); } scroller.outline = renderer.path() .attr({ 'stroke-width': outlineWidth, stroke: navigatorOptions.outlineColor }) .add(navigatorGroup); } if (scrollbarEnabled) { // draw the scrollbar group scroller.scrollbarGroup = scrollbarGroup = renderer.g('scrollbar').add(); // the scrollbar track strokeWidth = scrollbarOptions.trackBorderWidth; scroller.scrollbarTrack = scrollbarTrack = renderer.rect().attr({ x: 0, y: -strokeWidth % 2 / 2, fill: scrollbarOptions.trackBackgroundColor, stroke: scrollbarOptions.trackBorderColor, 'stroke-width': strokeWidth, r: scrollbarOptions.trackBorderRadius || 0, height: scrollbarHeight }).add(scrollbarGroup); // the scrollbar itself scroller.scrollbar = scrollbar = renderer.rect() .attr({ y: -scrollbarStrokeWidth % 2 / 2, height: scrollbarHeight, fill: scrollbarOptions.barBackgroundColor, stroke: scrollbarOptions.barBorderColor, 'stroke-width': scrollbarStrokeWidth, r: barBorderRadius }) .add(scrollbarGroup); scroller.scrollbarRifles = renderer.path() .attr({ stroke: scrollbarOptions.rifleColor, 'stroke-width': 1 }) .add(scrollbarGroup); } } // place elements verb = chart.isResizing ? 'animate' : 'attr'; if (navigatorEnabled) { scroller.leftShade[verb](navigatorOptions.maskInside ? { x: navigatorLeft + zoomedMin, y: top, width: zoomedMax - zoomedMin, height: height } : { x: navigatorLeft, y: top, width: zoomedMin, height: height }); if (scroller.rightShade) { scroller.rightShade[verb]({ x: navigatorLeft + zoomedMax, y: top, width: navigatorWidth - zoomedMax, height: height }); } scroller.outline[verb]({ d: [ M, scrollerLeft, outlineTop, // left L, navigatorLeft + zoomedMin - halfOutline, outlineTop, // upper left of zoomed range navigatorLeft + zoomedMin - halfOutline, outlineTop + outlineHeight, // lower left of z.r. L, navigatorLeft + zoomedMax - halfOutline, outlineTop + outlineHeight, // lower right of z.r. L, navigatorLeft + zoomedMax - halfOutline, outlineTop, // upper right of z.r. scrollerLeft + scrollerWidth, outlineTop // right ].concat(navigatorOptions.maskInside ? [ M, navigatorLeft + zoomedMin + halfOutline, outlineTop, // upper left of zoomed range L, navigatorLeft + zoomedMax - halfOutline, outlineTop // upper right of z.r. ] : [])}); // draw handles scroller.drawHandle(zoomedMin + halfOutline, 0); scroller.drawHandle(zoomedMax + halfOutline, 1); } // draw the scrollbar if (scrollbarEnabled && scrollbarGroup) { // draw the buttons scroller.drawScrollbarButton(0); scroller.drawScrollbarButton(1); scrollbarGroup[verb]({ translateX: scrollerLeft, translateY: mathRound(outlineTop + height) }); scrollbarTrack[verb]({ width: scrollerWidth }); // prevent the scrollbar from drawing to small (#1246) scrX = scrollbarHeight + zoomedMin; scrWidth = range - scrollbarStrokeWidth; if (scrWidth < scrollbarMinWidth) { scrollbarPad = (scrollbarMinWidth - scrWidth) / 2; scrWidth = scrollbarMinWidth; scrX -= scrollbarPad; } scroller.scrollbarPad = scrollbarPad; scrollbar[verb]({ x: mathFloor(scrX) + (scrollbarStrokeWidth % 2 / 2), width: scrWidth }); centerBarX = scrollbarHeight + zoomedMin + range / 2 - 0.5; scroller.scrollbarRifles .attr({ visibility: range > 12 ? VISIBLE : HIDDEN })[verb]({ d: [ M, centerBarX - 3, scrollbarHeight / 4, L, centerBarX - 3, 2 * scrollbarHeight / 3, M, centerBarX, scrollbarHeight / 4, L, centerBarX, 2 * scrollbarHeight / 3, M, centerBarX + 3, scrollbarHeight / 4, L, centerBarX + 3, 2 * scrollbarHeight / 3 ] }); } scroller.scrollbarPad = scrollbarPad; scroller.rendered = true; }, /** * Set up the mouse and touch events for the navigator and scrollbar */ addEvents: function () { var container = this.chart.container, mouseDownHandler = this.mouseDownHandler, mouseMoveHandler = this.mouseMoveHandler, mouseUpHandler = this.mouseUpHandler, _events; // Mouse events _events = [ [container, 'mousedown', mouseDownHandler], [container, 'mousemove', mouseMoveHandler], [document, 'mouseup', mouseUpHandler] ]; // Touch events if (hasTouch) { _events.push( [container, 'touchstart', mouseDownHandler], [container, 'touchmove', mouseMoveHandler], [document, 'touchend', mouseUpHandler] ); } // Add them all each(_events, function (args) { addEvent.apply(null, args); }); this._events = _events; }, /** * Removes the event handlers attached previously with addEvents. */ removeEvents: function () { each(this._events, function (args) { removeEvent.apply(null, args); }); this._events = UNDEFINED; if (this.navigatorEnabled && this.baseSeries) { removeEvent(this.baseSeries, 'updatedData', this.updatedDataHandler); } }, /** * Initiate the Scroller object */ init: function () { var scroller = this, chart = scroller.chart, xAxis, yAxis, scrollbarHeight = scroller.scrollbarHeight, navigatorOptions = scroller.navigatorOptions, height = scroller.height, top = scroller.top, dragOffset, hasDragged, baseSeries = scroller.baseSeries; /** * Event handler for the mouse down event. */ scroller.mouseDownHandler = function (e) { e = chart.pointer.normalize(e); var zoomedMin = scroller.zoomedMin, zoomedMax = scroller.zoomedMax, top = scroller.top, scrollbarHeight = scroller.scrollbarHeight, scrollerLeft = scroller.scrollerLeft, scrollerWidth = scroller.scrollerWidth, navigatorLeft = scroller.navigatorLeft, navigatorWidth = scroller.navigatorWidth, scrollbarPad = scroller.scrollbarPad, range = scroller.range, chartX = e.chartX, chartY = e.chartY, baseXAxis = chart.xAxis[0], fixedMax, ext, handleSensitivity = isTouchDevice ? 10 : 7, left, isOnNavigator; if (chartY > top && chartY < top + height + scrollbarHeight) { // we're vertically inside the navigator isOnNavigator = !scroller.scrollbarEnabled || chartY < top + height; // grab the left handle if (isOnNavigator && math.abs(chartX - zoomedMin - navigatorLeft) < handleSensitivity) { scroller.grabbedLeft = true; scroller.otherHandlePos = zoomedMax; scroller.fixedExtreme = baseXAxis.max; chart.fixedRange = null; // grab the right handle } else if (isOnNavigator && math.abs(chartX - zoomedMax - navigatorLeft) < handleSensitivity) { scroller.grabbedRight = true; scroller.otherHandlePos = zoomedMin; scroller.fixedExtreme = baseXAxis.min; chart.fixedRange = null; // grab the zoomed range } else if (chartX > navigatorLeft + zoomedMin - scrollbarPad && chartX < navigatorLeft + zoomedMax + scrollbarPad) { scroller.grabbedCenter = chartX; scroller.fixedWidth = range; dragOffset = chartX - zoomedMin; // shift the range by clicking on shaded areas, scrollbar track or scrollbar buttons } else if (chartX > scrollerLeft && chartX < scrollerLeft + scrollerWidth) { // Center around the clicked point if (isOnNavigator) { left = chartX - navigatorLeft - range / 2; // Click on scrollbar } else { // Click left scrollbar button if (chartX < navigatorLeft) { left = zoomedMin - range * 0.2; // Click right scrollbar button } else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) { left = zoomedMin + range * 0.2; // Click on scrollbar track, shift the scrollbar by one range } else { left = chartX < navigatorLeft + zoomedMin ? // on the left zoomedMin - range : zoomedMax; } } if (left < 0) { left = 0; } else if (left + range >= navigatorWidth) { left = navigatorWidth - range; fixedMax = scroller.getUnionExtremes().dataMax; // #2293, #3543 } if (left !== zoomedMin) { // it has actually moved scroller.fixedWidth = range; // #1370 ext = xAxis.toFixedRange(left, left + range, null, fixedMax); baseXAxis.setExtremes( ext.min, ext.max, true, false, { trigger: 'navigator' } ); } } } }; /** * Event handler for the mouse move event. */ scroller.mouseMoveHandler = function (e) { var scrollbarHeight = scroller.scrollbarHeight, navigatorLeft = scroller.navigatorLeft, navigatorWidth = scroller.navigatorWidth, scrollerLeft = scroller.scrollerLeft, scrollerWidth = scroller.scrollerWidth, range = scroller.range, chartX; // In iOS, a mousemove event with e.pageX === 0 is fired when holding the finger // down in the center of the scrollbar. This should be ignored. if (e.pageX !== 0) { e = chart.pointer.normalize(e); chartX = e.chartX; // validation for handle dragging if (chartX < navigatorLeft) { chartX = navigatorLeft; } else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) { chartX = scrollerLeft + scrollerWidth - scrollbarHeight; } // drag left handle if (scroller.grabbedLeft) { hasDragged = true; scroller.render(0, 0, chartX - navigatorLeft, scroller.otherHandlePos); // drag right handle } else if (scroller.grabbedRight) { hasDragged = true; scroller.render(0, 0, scroller.otherHandlePos, chartX - navigatorLeft); // drag scrollbar or open area in navigator } else if (scroller.grabbedCenter) { hasDragged = true; if (chartX < dragOffset) { // outside left chartX = dragOffset; } else if (chartX > navigatorWidth + dragOffset - range) { // outside right chartX = navigatorWidth + dragOffset - range; } scroller.render(0, 0, chartX - dragOffset, chartX - dragOffset + range); } if (hasDragged && scroller.scrollbarOptions.liveRedraw) { setTimeout(function () { scroller.mouseUpHandler(e); }, 0); } } }; /** * Event handler for the mouse up event. */ scroller.mouseUpHandler = function (e) { var ext, fixedMin, fixedMax; if (hasDragged) { // When dragging one handle, make sure the other one doesn't change if (scroller.zoomedMin === scroller.otherHandlePos) { fixedMin = scroller.fixedExtreme; } else if (scroller.zoomedMax === scroller.otherHandlePos) { fixedMax = scroller.fixedExtreme; } ext = xAxis.toFixedRange(scroller.zoomedMin, scroller.zoomedMax, fixedMin, fixedMax); chart.xAxis[0].setExtremes( ext.min, ext.max, true, false, { trigger: 'navigator', triggerOp: 'navigator-drag', DOMEvent: e // #1838 } ); } if (e.type !== 'mousemove') { scroller.grabbedLeft = scroller.grabbedRight = scroller.grabbedCenter = scroller.fixedWidth = scroller.fixedExtreme = scroller.otherHandlePos = hasDragged = dragOffset = null; } }; var xAxisIndex = chart.xAxis.length, yAxisIndex = chart.yAxis.length; // make room below the chart chart.extraBottomMargin = scroller.outlineHeight + navigatorOptions.margin; if (scroller.navigatorEnabled) { // an x axis is required for scrollbar also scroller.xAxis = xAxis = new Axis(chart, merge({ // inherit base xAxis' break and ordinal options breaks: baseSeries && baseSeries.xAxis.options.breaks, ordinal: baseSeries && baseSeries.xAxis.options.ordinal }, navigatorOptions.xAxis, { id: 'navigator-x-axis', isX: true, type: 'datetime', index: xAxisIndex, height: height, offset: 0, offsetLeft: scrollbarHeight, offsetRight: -scrollbarHeight, keepOrdinalPadding: true, // #2436 startOnTick: false, endOnTick: false, minPadding: 0, maxPadding: 0, zoomEnabled: false })); scroller.yAxis = yAxis = new Axis(chart, merge(navigatorOptions.yAxis, { id: 'navigator-y-axis', alignTicks: false, height: height, offset: 0, index: yAxisIndex, zoomEnabled: false })); // If we have a base series, initialize the navigator series if (baseSeries || navigatorOptions.series.data) { scroller.addBaseSeries(); // If not, set up an event to listen for added series } else if (chart.series.length === 0) { wrap(chart, 'redraw', function (proceed, animation) { // We've got one, now add it as base and reset chart.redraw if (chart.series.length > 0 && !scroller.series) { scroller.setBaseSeries(); chart.redraw = proceed; // reset } proceed.call(chart, animation); }); } // in case of scrollbar only, fake an x axis to get translation } else { scroller.xAxis = xAxis = { translate: function (value, reverse) { var axis = chart.xAxis[0], ext = axis.getExtremes(), scrollTrackWidth = chart.plotWidth - 2 * scrollbarHeight, min = numExt('min', axis.options.min, ext.dataMin), valueRange = numExt('max', axis.options.max, ext.dataMax) - min; return reverse ? // from pixel to value (value * valueRange / scrollTrackWidth) + min : // from value to pixel scrollTrackWidth * (value - min) / valueRange; }, toFixedRange: Axis.prototype.toFixedRange }; } /** * For stock charts, extend the Chart.getMargins method so that we can set the final top position * of the navigator once the height of the chart, including the legend, is determined. #367. */ wrap(chart, 'getMargins', function (proceed) { var legend = this.legend, legendOptions = legend.options; proceed.apply(this, [].slice.call(arguments, 1)); // Compute the top position scroller.top = top = scroller.navigatorOptions.top || this.chartHeight - scroller.height - scroller.scrollbarHeight - this.spacing[2] - (legendOptions.verticalAlign === 'bottom' && legendOptions.enabled && !legendOptions.floating ? legend.legendHeight + pick(legendOptions.margin, 10) : 0); if (xAxis && yAxis) { // false if navigator is disabled (#904) xAxis.options.top = yAxis.options.top = top; xAxis.setAxisSize(); yAxis.setAxisSize(); } }); scroller.addEvents(); }, /** * Get the union data extremes of the chart - the outer data extremes of the base * X axis and the navigator axis. */ getUnionExtremes: function (returnFalseOnNoBaseSeries) { var baseAxis = this.chart.xAxis[0], navAxis = this.xAxis, navAxisOptions = navAxis.options, baseAxisOptions = baseAxis.options; if (!returnFalseOnNoBaseSeries || baseAxis.dataMin !== null) { return { dataMin: numExt( 'min', navAxisOptions && navAxisOptions.min, baseAxisOptions.min, baseAxis.dataMin, navAxis.dataMin ), dataMax: numExt( 'max', navAxisOptions && navAxisOptions.max, baseAxisOptions.max, baseAxis.dataMax, navAxis.dataMax ) }; } }, /** * Set the base series. With a bit of modification we should be able to make * this an API method to be called from the outside */ setBaseSeries: function (baseSeriesOption) { var chart = this.chart; baseSeriesOption = baseSeriesOption || chart.options.navigator.baseSeries; // If we're resetting, remove the existing series if (this.series) { this.series.remove(); } // Set the new base series this.baseSeries = chart.series[baseSeriesOption] || (typeof baseSeriesOption === 'string' && chart.get(baseSeriesOption)) || chart.series[0]; // When run after render, this.xAxis already exists if (this.xAxis) { this.addBaseSeries(); } }, addBaseSeries: function () { var baseSeries = this.baseSeries, baseOptions = baseSeries ? baseSeries.options : {}, baseData = baseOptions.data, mergedNavSeriesOptions, navigatorSeriesOptions = this.navigatorOptions.series, navigatorData; // remove it to prevent merging one by one navigatorData = navigatorSeriesOptions.data; this.hasNavigatorData = !!navigatorData; // Merge the series options mergedNavSeriesOptions = merge(baseOptions, navigatorSeriesOptions, { enableMouseTracking: false, group: 'nav', // for columns padXAxis: false, xAxis: 'navigator-x-axis', yAxis: 'navigator-y-axis', name: 'Navigator', showInLegend: false, isInternal: true, visible: true }); // set the data back mergedNavSeriesOptions.data = navigatorData || baseData; // add the series this.series = this.chart.initSeries(mergedNavSeriesOptions); // Respond to updated data in the base series. // Abort if lazy-loading data from the server. if (baseSeries && this.navigatorOptions.adaptToUpdatedData !== false) { addEvent(baseSeries, 'updatedData', this.updatedDataHandler); // Survive Series.update() baseSeries.userOptions.events = extend(baseSeries.userOptions.event, { updatedData: this.updatedDataHandler }); } }, updatedDataHandler: function () { var scroller = this.chart.scroller, baseSeries = scroller.baseSeries, baseXAxis = baseSeries.xAxis, baseExtremes = baseXAxis.getExtremes(), baseMin = baseExtremes.min, baseMax = baseExtremes.max, baseDataMin = baseExtremes.dataMin, baseDataMax = baseExtremes.dataMax, range = baseMax - baseMin, stickToMin, stickToMax, newMax, newMin, doRedraw, navigatorSeries = scroller.series, navXData = navigatorSeries.xData, hasSetExtremes = !!baseXAxis.setExtremes; // detect whether to move the range stickToMax = baseMax >= navXData[navXData.length - 1] - (this.closestPointRange || 0); // #570 stickToMin = baseMin <= baseDataMin; // set the navigator series data to the new data of the base series if (!scroller.hasNavigatorData) { navigatorSeries.options.pointStart = baseSeries.xData[0]; navigatorSeries.setData(baseSeries.options.data, false); doRedraw = true; } // if the zoomed range is already at the min, move it to the right as new data // comes in if (stickToMin) { newMin = baseDataMin; newMax = newMin + range; } // if the zoomed range is already at the max, move it to the right as new data // comes in if (stickToMax) { newMax = baseDataMax; if (!stickToMin) { // if stickToMin is true, the new min value is set above newMin = mathMax(newMax - range, navigatorSeries.xData[0]); } } // update the extremes if (hasSetExtremes && (stickToMin || stickToMax)) { if (!isNaN(newMin)) { baseXAxis.setExtremes(newMin, newMax, true, false, { trigger: 'updatedData' }); } // if it is not at any edge, just move the scroller window to reflect the new series data } else { if (doRedraw) { this.chart.redraw(false); } scroller.render( mathMax(baseMin, baseDataMin), mathMin(baseMax, baseDataMax) ); } }, /** * Destroys allocated elements. */ destroy: function () { var scroller = this; // Disconnect events added in addEvents scroller.removeEvents(); // Destroy properties each([scroller.xAxis, scroller.yAxis, scroller.leftShade, scroller.rightShade, scroller.outline, scroller.scrollbarTrack, scroller.scrollbarRifles, scroller.scrollbarGroup, scroller.scrollbar], function (prop) { if (prop && prop.destroy) { prop.destroy(); } }); scroller.xAxis = scroller.yAxis = scroller.leftShade = scroller.rightShade = scroller.outline = scroller.scrollbarTrack = scroller.scrollbarRifles = scroller.scrollbarGroup = scroller.scrollbar = null; // Destroy elements in collection each([scroller.scrollbarButtons, scroller.handles, scroller.elementsToDestroy], function (coll) { destroyObjectProperties(coll); }); } }; Highcharts.Scroller = Scroller; /** * For Stock charts, override selection zooming with some special features because * X axis zooming is already allowed by the Navigator and Range selector. */ wrap(Axis.prototype, 'zoom', function (proceed, newMin, newMax) { var chart = this.chart, chartOptions = chart.options, zoomType = chartOptions.chart.zoomType, previousZoom, navigator = chartOptions.navigator, rangeSelector = chartOptions.rangeSelector, ret; if (this.isXAxis && ((navigator && navigator.enabled) || (rangeSelector && rangeSelector.enabled))) { // For x only zooming, fool the chart.zoom method not to create the zoom button // because the property already exists if (zoomType === 'x') { chart.resetZoomButton = 'blocked'; // For y only zooming, ignore the X axis completely } else if (zoomType === 'y') { ret = false; // For xy zooming, record the state of the zoom before zoom selection, then when // the reset button is pressed, revert to this state } else if (zoomType === 'xy') { previousZoom = this.previousZoom; if (defined(newMin)) { this.previousZoom = [this.min, this.max]; } else if (previousZoom) { newMin = previousZoom[0]; newMax = previousZoom[1]; delete this.previousZoom; } } } return ret !== UNDEFINED ? ret : proceed.call(this, newMin, newMax); }); // Initialize scroller for stock charts wrap(Chart.prototype, 'init', function (proceed, options, callback) { addEvent(this, 'beforeRender', function () { var options = this.options; if (options.navigator.enabled || options.scrollbar.enabled) { this.scroller = new Scroller(this); } }); proceed.call(this, options, callback); }); // Pick up badly formatted point options to addPoint wrap(Series.prototype, 'addPoint', function (proceed, options, redraw, shift, animation) { var turboThreshold = this.options.turboThreshold; if (turboThreshold && this.xData.length > turboThreshold && isObject(options) && !isArray(options) && this.chart.scroller) { error(20, true); } proceed.call(this, options, redraw, shift, animation); }); /* **************************************************************************** * End Scroller code * *****************************************************************************/ /* **************************************************************************** * Start Range Selector code * *****************************************************************************/ extend(defaultOptions, { rangeSelector: { // allButtonsEnabled: false, // enabled: true, // buttons: {Object} // buttonSpacing: 0, buttonTheme: { width: 28, height: 18, fill: '#f7f7f7', padding: 2, r: 0, 'stroke-width': 0, style: { color: '#444', cursor: 'pointer', fontWeight: 'normal' }, zIndex: 7, // #484, #852 states: { hover: { fill: '#e7e7e7' }, select: { fill: '#e7f0f9', style: { color: 'black', fontWeight: 'bold' } } } }, inputPosition: { align: 'right' }, // inputDateFormat: '%b %e, %Y', // inputEditDateFormat: '%Y-%m-%d', // inputEnabled: true, // inputStyle: {}, labelStyle: { color: '#666' } // selected: undefined } }); defaultOptions.lang = merge(defaultOptions.lang, { rangeSelectorZoom: 'Zoom', rangeSelectorFrom: 'From', rangeSelectorTo: 'To' }); /** * The object constructor for the range selector * @param {Object} chart */ function RangeSelector(chart) { // Run RangeSelector this.init(chart); } RangeSelector.prototype = { /** * The method to run when one of the buttons in the range selectors is clicked * @param {Number} i The index of the button * @param {Object} rangeOptions * @param {Boolean} redraw */ clickButton: function (i, redraw) { var rangeSelector = this, selected = rangeSelector.selected, chart = rangeSelector.chart, buttons = rangeSelector.buttons, rangeOptions = rangeSelector.buttonOptions[i], baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis || {}, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, newMin, newMax = baseAxis && mathRound(mathMin(baseAxis.max, pick(dataMax, baseAxis.max))), // #1568 now, date = new Date(newMax), type = rangeOptions.type, count = rangeOptions.count, baseXAxisOptions, range = rangeOptions._range, rangeMin, year, timeName; if (dataMin === null || dataMax === null || // chart has no data, base series is removed i === rangeSelector.selected) { // same button is clicked twice return; } if (type === 'month' || type === 'year') { timeName = { month: 'Month', year: 'FullYear'}[type]; date['set' + timeName](date['get' + timeName]() - count); newMin = date.getTime(); dataMin = pick(dataMin, Number.MIN_VALUE); if (isNaN(newMin) || newMin < dataMin) { newMin = dataMin; newMax = mathMin(newMin + range, dataMax); } else { range = newMax - newMin; } // Fixed times like minutes, hours, days } else if (range) { newMin = mathMax(newMax - range, dataMin); newMax = mathMin(newMin + range, dataMax); } else if (type === 'ytd') { // On user clicks on the buttons, or a delayed action running from the beforeRender // event (below), the baseAxis is defined. if (baseAxis) { // When "ytd" is the pre-selected button for the initial view, its calculation // is delayed and rerun in the beforeRender event (below). When the series // are initialized, but before the chart is rendered, we have access to the xData // array (#942). if (dataMax === UNDEFINED) { dataMin = Number.MAX_VALUE; dataMax = Number.MIN_VALUE; each(chart.series, function (series) { var xData = series.xData; // reassign it to the last item dataMin = mathMin(xData[0], dataMin); dataMax = mathMax(xData[xData.length - 1], dataMax); }); redraw = false; } now = new Date(dataMax); year = now.getFullYear(); newMin = rangeMin = mathMax(dataMin || 0, Date.UTC(year, 0, 1)); now = now.getTime(); newMax = mathMin(dataMax || now, now); // "ytd" is pre-selected. We don't yet have access to processed point and extremes data // (things like pointStart and pointInterval are missing), so we delay the process (#942) } else { addEvent(chart, 'beforeRender', function () { rangeSelector.clickButton(i); }); return; } } else if (type === 'all' && baseAxis) { newMin = dataMin; newMax = dataMax; } // Deselect previous button if (buttons[selected]) { buttons[selected].setState(0); } // Select this button if (buttons[i]) { buttons[i].setState(2); } chart.fixedRange = range; // update the chart if (!baseAxis) { // axis not yet instanciated baseXAxisOptions = chart.options.xAxis; baseXAxisOptions[0] = merge( baseXAxisOptions[0], { range: range, min: rangeMin } ); rangeSelector.setSelected(i); } else { // existing axis object; after render time baseAxis.setExtremes( newMin, newMax, pick(redraw, 1), 0, { trigger: 'rangeSelectorButton', rangeSelectorButton: rangeOptions } ); rangeSelector.setSelected(i); } }, /** * Set the selected option. This method only sets the internal flag, it doesn't * update the buttons or the actual zoomed range. */ setSelected: function (selected) { this.selected = this.options.selected = selected; }, /** * The default buttons for pre-selecting time frames */ defaultButtons: [{ type: 'month', count: 1, text: '1m' }, { type: 'month', count: 3, text: '3m' }, { type: 'month', count: 6, text: '6m' }, { type: 'ytd', text: 'YTD' }, { type: 'year', count: 1, text: '1y' }, { type: 'all', text: 'All' }], /** * Initialize the range selector */ init: function (chart) { var rangeSelector = this, options = chart.options.rangeSelector, buttonOptions = options.buttons || [].concat(rangeSelector.defaultButtons), selectedOption = options.selected, blurInputs = rangeSelector.blurInputs = function () { var minInput = rangeSelector.minInput, maxInput = rangeSelector.maxInput; if (minInput && minInput.blur) { //#3274 in some case blur is not defined fireEvent(minInput, 'blur'); //#3274 } if (maxInput && maxInput.blur) { //#3274 in some case blur is not defined fireEvent(maxInput, 'blur'); //#3274 } }; rangeSelector.chart = chart; rangeSelector.options = options; rangeSelector.buttons = []; chart.extraTopMargin = 35; rangeSelector.buttonOptions = buttonOptions; addEvent(chart.container, 'mousedown', blurInputs); addEvent(chart, 'resize', blurInputs); // Extend the buttonOptions with actual range each(buttonOptions, rangeSelector.computeButtonRange); // zoomed range based on a pre-selected button index if (selectedOption !== UNDEFINED && buttonOptions[selectedOption]) { this.clickButton(selectedOption, false); } // normalize the pressed button whenever a new range is selected addEvent(chart, 'load', function () { addEvent(chart.xAxis[0], 'afterSetExtremes', function () { rangeSelector.updateButtonStates(true); }); }); }, /** * Dynamically update the range selector buttons after a new range has been set */ updateButtonStates: function (updating) { var rangeSelector = this, chart = this.chart, baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, selected = rangeSelector.selected, allButtonsEnabled = rangeSelector.options.allButtonsEnabled, buttons = rangeSelector.buttons; if (updating && chart.fixedRange !== mathRound(baseAxis.max - baseAxis.min)) { if (buttons[selected]) { buttons[selected].setState(0); } rangeSelector.setSelected(null); } each(rangeSelector.buttonOptions, function (rangeOptions, i) { var range = rangeOptions._range, // Disable buttons where the range exceeds what is allowed in the current view isTooGreatRange = range > dataMax - dataMin, // Disable buttons where the range is smaller than the minimum range isTooSmallRange = range < baseAxis.minRange, // Disable the All button if we're already showing all isAllButAlreadyShowingAll = rangeOptions.type === 'all' && baseAxis.max - baseAxis.min >= dataMax - dataMin && buttons[i].state !== 2, // Disable the YTD button if the complete range is within the same year isYTDButNotAvailable = rangeOptions.type === 'ytd' && dateFormat('%Y', dataMin) === dateFormat('%Y', dataMax); // The new zoom area happens to match the range for a button - mark it selected. // This happens when scrolling across an ordinal gap. It can be seen in the intraday // demos when selecting 1h and scroll across the night gap. if (range === mathRound(baseAxis.max - baseAxis.min) && i !== selected) { rangeSelector.setSelected(i); buttons[i].setState(2); } else if (!allButtonsEnabled && (isTooGreatRange || isTooSmallRange || isAllButAlreadyShowingAll || isYTDButNotAvailable)) { buttons[i].setState(3); } else if (buttons[i].state === 3) { buttons[i].setState(0); } }); }, /** * Compute and cache the range for an individual button */ computeButtonRange: function (rangeOptions) { var type = rangeOptions.type, count = rangeOptions.count || 1, // these time intervals have a fixed number of milliseconds, as opposed // to month, ytd and year fixedTimes = { millisecond: 1, second: 1000, minute: 60 * 1000, hour: 3600 * 1000, day: 24 * 3600 * 1000, week: 7 * 24 * 3600 * 1000 }; // Store the range on the button object if (fixedTimes[type]) { rangeOptions._range = fixedTimes[type] * count; } else if (type === 'month' || type === 'year') { rangeOptions._range = { month: 30, year: 365 }[type] * 24 * 36e5 * count; } }, /** * Set the internal and displayed value of a HTML input for the dates * @param {String} name * @param {Number} time */ setInputValue: function (name, time) { var options = this.chart.options.rangeSelector; if (defined(time)) { this[name + 'Input'].HCTime = time; } this[name + 'Input'].value = dateFormat(options.inputEditDateFormat || '%Y-%m-%d', this[name + 'Input'].HCTime); this[name + 'DateBox'].attr({ text: dateFormat(options.inputDateFormat || '%b %e, %Y', this[name + 'Input'].HCTime) }); }, /** * Draw either the 'from' or the 'to' HTML input box of the range selector * @param {Object} name */ drawInput: function (name) { var rangeSelector = this, chart = rangeSelector.chart, chartStyle = chart.renderer.style, renderer = chart.renderer, options = chart.options.rangeSelector, lang = defaultOptions.lang, div = rangeSelector.div, isMin = name === 'min', input, label, dateBox, inputGroup = this.inputGroup; // Create the text label this[name + 'Label'] = label = renderer.label(lang[isMin ? 'rangeSelectorFrom' : 'rangeSelectorTo'], this.inputGroup.offset) .attr({ padding: 2 }) .css(merge(chartStyle, options.labelStyle)) .add(inputGroup); inputGroup.offset += label.width + 5; // Create an SVG label that shows updated date ranges and and records click events that // bring in the HTML input. this[name + 'DateBox'] = dateBox = renderer.label('', inputGroup.offset) .attr({ padding: 2, width: options.inputBoxWidth || 90, height: options.inputBoxHeight || 17, stroke: options.inputBoxBorderColor || 'silver', 'stroke-width': 1 }) .css(merge({ textAlign: 'center', color: '#444' }, chartStyle, options.inputStyle)) .on('click', function () { rangeSelector[name + 'Input'].focus(); }) .add(inputGroup); inputGroup.offset += dateBox.width + (isMin ? 10 : 0); // Create the HTML input element. This is rendered as 1x1 pixel then set to the right size // when focused. this[name + 'Input'] = input = createElement('input', { name: name, className: PREFIX + 'range-selector', type: 'text' }, extend({ position: ABSOLUTE, border: 0, width: '1px', // Chrome needs a pixel to see it height: '1px', padding: 0, textAlign: 'center', fontSize: chartStyle.fontSize, fontFamily: chartStyle.fontFamily, top: chart.plotTop + PX // prevent jump on focus in Firefox }, options.inputStyle), div); // Blow up the input box input.onfocus = function () { css(this, { left: (inputGroup.translateX + dateBox.x) + PX, top: inputGroup.translateY + PX, width: (dateBox.width - 2) + PX, height: (dateBox.height - 2) + PX, border: '2px solid silver' }); }; // Hide away the input box input.onblur = function () { css(this, { border: 0, width: '1px', height: '1px' }); rangeSelector.setInputValue(name); }; // handle changes in the input boxes input.onchange = function () { var inputValue = input.value, value = (options.inputDateParser || Date.parse)(inputValue), xAxis = chart.xAxis[0], dataMin = xAxis.dataMin, dataMax = xAxis.dataMax; // If the value isn't parsed directly to a value by the browser's Date.parse method, // like YYYY-MM-DD in IE, try parsing it a different way if (isNaN(value)) { value = inputValue.split('-'); value = Date.UTC(pInt(value[0]), pInt(value[1]) - 1, pInt(value[2])); } if (!isNaN(value)) { // Correct for timezone offset (#433) if (!defaultOptions.global.useUTC) { value = value + new Date().getTimezoneOffset() * 60 * 1000; } // Validate the extremes. If it goes beyound the data min or max, use the // actual data extreme (#2438). if (isMin) { if (value > rangeSelector.maxInput.HCTime) { value = UNDEFINED; } else if (value < dataMin) { value = dataMin; } } else { if (value < rangeSelector.minInput.HCTime) { value = UNDEFINED; } else if (value > dataMax) { value = dataMax; } } // Set the extremes if (value !== UNDEFINED) { chart.xAxis[0].setExtremes( isMin ? value : xAxis.min, isMin ? xAxis.max : value, UNDEFINED, UNDEFINED, { trigger: 'rangeSelectorInput' } ); } } }; }, /** * Render the range selector including the buttons and the inputs. The first time render * is called, the elements are created and positioned. On subsequent calls, they are * moved and updated. * @param {Number} min X axis minimum * @param {Number} max X axis maximum */ render: function (min, max) { var rangeSelector = this, chart = rangeSelector.chart, renderer = chart.renderer, container = chart.container, chartOptions = chart.options, navButtonOptions = chartOptions.exporting && chartOptions.navigation && chartOptions.navigation.buttonOptions, options = chartOptions.rangeSelector, buttons = rangeSelector.buttons, lang = defaultOptions.lang, div = rangeSelector.div, inputGroup = rangeSelector.inputGroup, buttonTheme = options.buttonTheme, buttonPosition = options.buttonPosition || {}, inputEnabled = options.inputEnabled, states = buttonTheme && buttonTheme.states, plotLeft = chart.plotLeft, yAlign, buttonLeft, buttonTop, buttonGroup = rangeSelector.group, buttonBBox; // create the elements if (!rangeSelector.rendered) { rangeSelector.group = buttonGroup = renderer.g('range-selector-buttons').add(); rangeSelector.zoomText = renderer.text(lang.rangeSelectorZoom, pick(buttonPosition.x, plotLeft), pick(buttonPosition.y, chart.plotTop - 35) + 15) .css(options.labelStyle) .add(buttonGroup); // button starting position buttonLeft = pick(buttonPosition.x, plotLeft) + rangeSelector.zoomText.getBBox().width + 5; buttonTop = pick(buttonPosition.y, chart.plotTop - 35); each(rangeSelector.buttonOptions, function (rangeOptions, i) { buttons[i] = renderer.button( rangeOptions.text, buttonLeft, buttonTop, function () { rangeSelector.clickButton(i); rangeSelector.isActive = true; }, buttonTheme, states && states.hover, states && states.select, states && states.disabled ) .css({ textAlign: 'center' }) .add(buttonGroup); // increase button position for the next button buttonLeft += buttons[i].width + pick(options.buttonSpacing, 5); if (rangeSelector.selected === i) { buttons[i].setState(2); } }); rangeSelector.updateButtonStates(); // first create a wrapper outside the container in order to make // the inputs work and make export correct if (inputEnabled !== false) { rangeSelector.div = div = createElement('div', null, { position: 'relative', height: 0, zIndex: 1 // above container }); container.parentNode.insertBefore(div, container); // Create the group to keep the inputs rangeSelector.inputGroup = inputGroup = renderer.g('input-group') .add(); inputGroup.offset = 0; rangeSelector.drawInput('min'); rangeSelector.drawInput('max'); } } if (inputEnabled !== false) { // Update the alignment to the updated spacing box yAlign = chart.plotTop - 45; inputGroup.align(extend({ y: yAlign, width: inputGroup.offset, // Detect collision with the exporting buttons x: navButtonOptions && (yAlign < (navButtonOptions.y || 0) + navButtonOptions.height - chart.spacing[0]) ? -40 : 0 }, options.inputPosition), true, chart.spacingBox); // Hide if overlapping - inputEnabled is null or undefined if (!defined(inputEnabled)) { buttonBBox = buttonGroup.getBBox(); inputGroup[inputGroup.translateX < buttonBBox.x + buttonBBox.width + 10 ? 'hide' : 'show'](); } // Set or reset the input values rangeSelector.setInputValue('min', min); rangeSelector.setInputValue('max', max); } rangeSelector.rendered = true; }, /** * Destroys allocated elements. */ destroy: function () { var minInput = this.minInput, maxInput = this.maxInput, chart = this.chart, blurInputs = this.blurInputs, key; removeEvent(chart.container, 'mousedown', blurInputs); removeEvent(chart, 'resize', blurInputs); // Destroy elements in collections destroyObjectProperties(this.buttons); // Clear input element events if (minInput) { minInput.onfocus = minInput.onblur = minInput.onchange = null; } if (maxInput) { maxInput.onfocus = maxInput.onblur = maxInput.onchange = null; } // Destroy HTML and SVG elements for (key in this) { if (this[key] && key !== 'chart') { if (this[key].destroy) { // SVGElement this[key].destroy(); } else if (this[key].nodeType) { // HTML element discardElement(this[key]); } } this[key] = null; } } }; /** * Add logic to normalize the zoomed range in order to preserve the pressed state of range selector buttons */ Axis.prototype.toFixedRange = function (pxMin, pxMax, fixedMin, fixedMax) { var fixedRange = this.chart && this.chart.fixedRange, newMin = pick(fixedMin, this.translate(pxMin, true)), newMax = pick(fixedMax, this.translate(pxMax, true)), changeRatio = fixedRange && (newMax - newMin) / fixedRange; // If the difference between the fixed range and the actual requested range is // too great, the user is dragging across an ordinal gap, and we need to release // the range selector button. if (changeRatio > 0.7 && changeRatio < 1.3) { if (fixedMax) { newMin = newMax - fixedRange; } else { newMax = newMin + fixedRange; } } return { min: newMin, max: newMax }; }; // Initialize scroller for stock charts wrap(Chart.prototype, 'init', function (proceed, options, callback) { addEvent(this, 'init', function () { if (this.options.rangeSelector.enabled) { this.rangeSelector = new RangeSelector(this); } }); proceed.call(this, options, callback); }); Highcharts.RangeSelector = RangeSelector; /* **************************************************************************** * End Range Selector code * *****************************************************************************/ Chart.prototype.callbacks.push(function (chart) { var extremes, scroller = chart.scroller, rangeSelector = chart.rangeSelector; function renderScroller() { extremes = chart.xAxis[0].getExtremes(); scroller.render(extremes.min, extremes.max); } function renderRangeSelector() { extremes = chart.xAxis[0].getExtremes(); if (!isNaN(extremes.min)) { rangeSelector.render(extremes.min, extremes.max); } } function afterSetExtremesHandlerScroller(e) { if (e.triggerOp !== 'navigator-drag') { scroller.render(e.min, e.max); } } function afterSetExtremesHandlerRangeSelector(e) { rangeSelector.render(e.min, e.max); } function destroyEvents() { if (scroller) { removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerScroller); } if (rangeSelector) { removeEvent(chart, 'resize', renderRangeSelector); removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector); } } // initiate the scroller if (scroller) { // redraw the scroller on setExtremes addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerScroller); // redraw the scroller on chart resize or box resize wrap(chart, 'drawChartBox', function (proceed) { var isDirtyBox = this.isDirtyBox; proceed.call(this); if (isDirtyBox) { renderScroller(); } }); // do it now renderScroller(); } if (rangeSelector) { // redraw the scroller on setExtremes addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector); // redraw the scroller chart resize addEvent(chart, 'resize', renderRangeSelector); // do it now renderRangeSelector(); } // Remove resize/afterSetExtremes at chart destroy addEvent(chart, 'destroy', destroyEvents); }); /** * A wrapper for Chart with all the default values for a Stock chart */ Highcharts.StockChart = function (options, callback) { var seriesOptions = options.series, // to increase performance, don't merge the data opposite, // Always disable startOnTick:true on the main axis when the navigator is enabled (#1090) navigatorEnabled = pick(options.navigator && options.navigator.enabled, true), disableStartOnTick = navigatorEnabled ? { startOnTick: false, endOnTick: false } : null, lineOptions = { marker: { enabled: false, radius: 2 }, // gapSize: 0, states: { hover: { lineWidth: 2 } } }, columnOptions = { shadow: false, borderWidth: 0 }; // apply X axis options to both single and multi y axes options.xAxis = map(splat(options.xAxis || {}), function (xAxisOptions) { return merge({ // defaults minPadding: 0, maxPadding: 0, ordinal: true, title: { text: null }, labels: { overflow: 'justify' }, showLastLabel: true }, xAxisOptions, // user options { // forced options type: 'datetime', categories: null }, disableStartOnTick ); }); // apply Y axis options to both single and multi y axes options.yAxis = map(splat(options.yAxis || {}), function (yAxisOptions) { opposite = pick(yAxisOptions.opposite, true); return merge({ // defaults labels: { y: -2 }, opposite: opposite, showLastLabel: false, title: { text: null } }, yAxisOptions // user options ); }); options.series = null; options = merge({ chart: { panning: true, pinchType: 'x' }, navigator: { enabled: true }, scrollbar: { enabled: true }, rangeSelector: { enabled: true }, title: { text: null, style: { fontSize: '16px' } }, tooltip: { shared: true, crosshairs: true }, legend: { enabled: false }, plotOptions: { line: lineOptions, spline: lineOptions, area: lineOptions, areaspline: lineOptions, arearange: lineOptions, areasplinerange: lineOptions, column: columnOptions, columnrange: columnOptions, candlestick: columnOptions, ohlc: columnOptions } }, options, // user's options { // forced options _stock: true, // internal flag chart: { inverted: false } }); options.series = seriesOptions; return new Chart(options, callback); }; // Implement the pinchType option wrap(Pointer.prototype, 'init', function (proceed, chart, options) { var pinchType = options.chart.pinchType || ''; proceed.call(this, chart, options); // Pinch status this.pinchX = this.pinchHor = pinchType.indexOf('x') !== -1; this.pinchY = this.pinchVert = pinchType.indexOf('y') !== -1; this.hasZoom = this.hasZoom || this.pinchHor || this.pinchVert; }); // Override the automatic label alignment so that the first Y axis' labels // are drawn on top of the grid line, and subsequent axes are drawn outside wrap(Axis.prototype, 'autoLabelAlign', function (proceed) { var chart = this.chart, options = this.options, panes = chart._labelPanes = chart._labelPanes || {}, key, labelOptions = this.options.labels; if (this.chart.options._stock && this.coll === 'yAxis') { key = options.top + ',' + options.height; if (!panes[key] && labelOptions.enabled) { // do it only for the first Y axis of each pane if (labelOptions.x === 15) { // default labelOptions.x = 0; } if (labelOptions.align === undefined) { labelOptions.align = 'right'; } panes[key] = 1; return 'right'; } } return proceed.call(this, [].slice.call(arguments, 1)); }); // Override getPlotLinePath to allow for multipane charts wrap(Axis.prototype, 'getPlotLinePath', function (proceed, value, lineWidth, old, force, translatedValue) { var axis = this, series = (this.isLinked && !this.series ? this.linkedParent.series : this.series), chart = axis.chart, renderer = chart.renderer, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, result = [], axes = [], //#3416 need a default array axes2, uniqueAxes; // Ignore in case of color Axis. #3360, #3524 if (axis.coll === 'colorAxis') { return proceed.apply(this, [].slice.call(arguments, 1)); } // Get the related axes based on series axes = (axis.isXAxis ? (defined(axis.options.yAxis) ? [chart.yAxis[axis.options.yAxis]] : map(series, function (S) { return S.yAxis; }) ) : (defined(axis.options.xAxis) ? [chart.xAxis[axis.options.xAxis]] : map(series, function (S) { return S.xAxis; }) ) ); // Get the related axes based options.*Axis setting #2810 axes2 = (axis.isXAxis ? chart.yAxis : chart.xAxis); each(axes2, function (A) { if (defined(A.options.id) ? A.options.id.indexOf('navigator') === -1 : true) { var a = (A.isXAxis ? 'yAxis' : 'xAxis'), rax = (defined(A.options[a]) ? chart[a][A.options[a]] : chart[a][0]); if (axis === rax) { axes.push(A); } } }); // Remove duplicates in the axes array. If there are no axes in the axes array, // we are adding an axis without data, so we need to populate this with grid // lines (#2796). uniqueAxes = axes.length ? [] : [axis.isXAxis ? chart.yAxis[0] : chart.xAxis[0]]; //#3742 each(axes, function (axis2) { if (inArray(axis2, uniqueAxes) === -1) { uniqueAxes.push(axis2); } }); translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); if (!isNaN(translatedValue)) { if (axis.horiz) { each(uniqueAxes, function (axis2) { var skip; y1 = axis2.pos; y2 = y1 + axis2.len; x1 = x2 = mathRound(translatedValue + axis.transB); if (x1 < axisLeft || x1 > axisLeft + axis.width) { // outside plot area if (force) { x1 = x2 = mathMin(mathMax(axisLeft, x1), axisLeft + axis.width); } else { skip = true; } } if (!skip) { result.push('M', x1, y1, 'L', x2, y2); } }); } else { each(uniqueAxes, function (axis2) { var skip; x1 = axis2.pos; x2 = x1 + axis2.len; y1 = y2 = mathRound(axisTop + axis.height - translatedValue); if (y1 < axisTop || y1 > axisTop + axis.height) { // outside plot area if (force) { y1 = y2 = mathMin(mathMax(axisTop, y1), axis.top + axis.height); } else { skip = true; } } if (!skip) { result.push('M', x1, y1, 'L', x2, y2); } }); } } if (result.length > 0) { return renderer.crispPolyLine(result, lineWidth || 1); } else { return null; //#3557 getPlotLinePath in regular Highcharts also returns null } }); // Override getPlotBandPath to allow for multipane charts Axis.prototype.getPlotBandPath = function (from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true), result = [], i; if (path && toPath) { // Go over each subpath for (i = 0; i < path.length; i += 6) { result.push('M', path[i + 1], path[i + 2], 'L', path[i + 4], path[i + 5], toPath[i + 4], toPath[i + 5], toPath[i + 1], toPath[i + 2]); } } else { // outside the axis area result = null; } return result; }; // Function to crisp a line with multiple segments SVGRenderer.prototype.crispPolyLine = function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line var i; for (i = 0; i < points.length; i = i + 6) { if (points[i + 1] === points[i + 4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[i + 1] = points[i + 4] = mathRound(points[i + 1]) - (width % 2 / 2); } if (points[i + 2] === points[i + 5]) { points[i + 2] = points[i + 5] = mathRound(points[i + 2]) + (width % 2 / 2); } } return points; }; if (Renderer === Highcharts.VMLRenderer) { VMLRenderer.prototype.crispPolyLine = SVGRenderer.prototype.crispPolyLine; } // Wrapper to hide the label wrap(Axis.prototype, 'hideCrosshair', function (proceed, i) { proceed.call(this, i); if (!defined(this.crossLabelArray)) { return; } if (defined(i)) { if (this.crossLabelArray[i]) { this.crossLabelArray[i].hide(); } } else { each(this.crossLabelArray, function (crosslabel) { crosslabel.hide(); }); } }); // Wrapper to draw the label wrap(Axis.prototype, 'drawCrosshair', function (proceed, e, point) { // Draw the crosshair proceed.call(this, e, point); // Check if the label has to be drawn if (!defined(this.crosshair.label) || !this.crosshair.label.enabled || !defined(point)) { return; } var chart = this.chart, options = this.options.crosshair.label, // the label's options axis = this.isXAxis ? 'x' : 'y', // axis name horiz = this.horiz, // axis orientation opposite = this.opposite, // axis position left = this.left, // left position top = this.top, // top position crossLabel = this.crossLabel, // reference to the svgElement posx, posy, crossBox, formatOption = options.format, formatFormat = '', limit; // If the label does not exist yet, create it. if (!crossLabel) { crossLabel = this.crossLabel = chart.renderer.label() .attr({ align: options.align || (horiz ? 'center' : opposite ? (this.labelAlign === 'right' ? 'right' : 'left') : (this.labelAlign === 'left' ? 'left' : 'center')), zIndex: 12, height: horiz ? 16 : UNDEFINED, fill: options.backgroundColor || (this.series[0] && this.series[0].color) || 'gray', padding: pick(options.padding, 2), stroke: options.borderColor || null, 'stroke-width': options.borderWidth || 0 }) .css(extend({ color: 'white', fontWeight: 'normal', fontSize: '11px', textAlign: 'center' }, options.style)) .add(); } if (horiz) { posx = point.plotX + left; posy = top + (opposite ? 0 : this.height); } else { posx = opposite ? this.width + left : 0; posy = point.plotY + top; } // if the crosshair goes out of view (too high or too low, hide it and hide the label) if (posy < top || posy > top + this.height) { this.hideCrosshair(); return; } // TODO: Dynamic date formats like in Series.tooltipHeaderFormat. if (!formatOption && !options.formatter) { if (this.isDatetimeAxis) { formatFormat = '%b %d, %Y'; } formatOption = '{value' + (formatFormat ? ':' + formatFormat : '') + '}'; } // show the label crossLabel.attr({ text: formatOption ? format(formatOption, {value: point[axis]}) : options.formatter.call(this, point[axis]), x: posx, y: posy, visibility: VISIBLE }); crossBox = crossLabel.getBBox(); // now it is placed we can correct its position if (horiz) { if (((this.options.tickPosition === 'inside') && !opposite) || ((this.options.tickPosition !== 'inside') && opposite)) { posy = crossLabel.y - crossBox.height; } } else { posy = crossLabel.y - (crossBox.height / 2); } // check the edges if (horiz) { limit = { left: left - crossBox.x, right: left + this.width - crossBox.x }; } else { limit = { left: this.labelAlign === 'left' ? left : 0, right: this.labelAlign === 'right' ? left + this.width : chart.chartWidth }; } // left edge if (crossLabel.translateX < limit.left) { posx += limit.left - crossLabel.translateX; } // right edge if (crossLabel.translateX + crossBox.width >= limit.right) { posx -= crossLabel.translateX + crossBox.width - limit.right; } // show the crosslabel crossLabel.attr({x: posx, y: posy, visibility: VISIBLE}); }); /* **************************************************************************** * Start value compare logic * *****************************************************************************/ var seriesInit = seriesProto.init, seriesProcessData = seriesProto.processData, pointTooltipFormatter = Point.prototype.tooltipFormatter; /** * Extend series.init by adding a method to modify the y value used for plotting * on the y axis. This method is called both from the axis when finding dataMin * and dataMax, and from the series.translate method. */ seriesProto.init = function () { // Call base method seriesInit.apply(this, arguments); // Set comparison mode this.setCompare(this.options.compare); }; /** * The setCompare method can be called also from the outside after render time */ seriesProto.setCompare = function (compare) { // Set or unset the modifyValue method this.modifyValue = (compare === 'value' || compare === 'percent') ? function (value, point) { var compareValue = this.compareValue; if (value !== UNDEFINED) { // #2601 // get the modified value value = compare === 'value' ? value - compareValue : // compare value value = 100 * (value / compareValue) - 100; // compare percent // record for tooltip etc. if (point) { point.change = value; } } return value; } : null; // Mark dirty if (this.chart.hasRendered) { this.isDirty = true; } }; /** * Extend series.processData by finding the first y value in the plot area, * used for comparing the following values */ seriesProto.processData = function () { var series = this, i = 0, processedXData, processedYData, length; // call base method seriesProcessData.apply(this, arguments); if (series.xAxis && series.processedYData) { // not pies // local variables processedXData = series.processedXData; processedYData = series.processedYData; length = processedYData.length; // find the first value for comparison for (; i < length; i++) { if (typeof processedYData[i] === NUMBER && processedXData[i] >= series.xAxis.min) { series.compareValue = processedYData[i]; break; } } } }; /** * Modify series extremes */ wrap(seriesProto, 'getExtremes', function (proceed) { proceed.apply(this, [].slice.call(arguments, 1)); if (this.modifyValue) { this.dataMax = this.modifyValue(this.dataMax); this.dataMin = this.modifyValue(this.dataMin); } }); /** * Add a utility method, setCompare, to the Y axis */ Axis.prototype.setCompare = function (compare, redraw) { if (!this.isXAxis) { each(this.series, function (series) { series.setCompare(compare); }); if (pick(redraw, true)) { this.chart.redraw(); } } }; /** * Extend the tooltip formatter by adding support for the point.change variable * as well as the changeDecimals option */ Point.prototype.tooltipFormatter = function (pointFormat) { var point = this; pointFormat = pointFormat.replace( '{point.change}', (point.change > 0 ? '+' : '') + Highcharts.numberFormat(point.change, pick(point.series.tooltipOptions.changeDecimals, 2)) ); return pointTooltipFormatter.apply(this, [pointFormat]); }; /* **************************************************************************** * End value compare logic * *****************************************************************************/ /** * Extend the Series prototype to create a separate series clip box. This is related * to using multiple panes, and a future pane logic should incorporate this feature (#2754). */ wrap(Series.prototype, 'render', function (proceed) { // Only do this on stock charts (#2939), and only if the series type handles clipping // in the animate method (#2975). if (this.chart.options._stock) { // First render, initial clip box if (!this.clipBox && this.animate && this.animate.toString().indexOf('sharedClip') !== -1) { this.clipBox = merge(this.chart.clipBox); this.clipBox.width = this.xAxis.len; this.clipBox.height = this.yAxis.len; // On redrawing, resizing etc, update the clip rectangle } else if (this.chart[this.sharedClipKey]) { this.chart[this.sharedClipKey].attr({ width: this.xAxis.len, height: this.yAxis.len }); } } proceed.call(this); }); // global variables extend(Highcharts, { // Constructors Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, error: error, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, map: map, merge: merge, splat: splat, extendClass: extendClass, pInt: pInt, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
dist/1.10.0/jquery-ajax-css-effects.min.js
eric-seekas/jquery-builder
/*! jQuery v1.10.0 -css,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],d="1.10.0 -css,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions",f=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=d.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,N=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,C=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,A=/(?:^|:|,)(?:\s*\[)+/g,D=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,S=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,L=/^-ms-/,j=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},_=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(B(),x.ready())},B=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",_,!1),e.removeEventListener("load",_,!1)):(a.detachEvent("onreadystatechange",_),e.detachEvent("onload",_))};x.fn=x.prototype={jquery:d,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]:C.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)),E.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"+(d+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=E.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&&k.test(n.replace(D,"@").replace(S,"]").replace(A,"")))?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(L,"ms-").replace(j,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(T,"")},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 f.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",_,!1),e.addEventListener("load",_,!1);else{a.attachEvent("onreadystatechange",_),e.attachEvent("onload",_);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)}B(),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,d,f,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,N=0,T=0,C=lt(),E=lt(),k=lt(),A=!1,D=function(){return 0},S=typeof t,L=1<<31,j={}.hasOwnProperty,H=[],_=H.pop,B=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},q="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",$="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",I=$.replace("w","w#"),R="\\["+P+"*("+$+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+I+")|)|)"+P+"*\\]",W=":("+$+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+R.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),J=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),Q=RegExp(W),K=RegExp("^"+I+"$"),Y={ID:RegExp("^#("+$+")"),CLASS:RegExp("^\\.("+$+")"),TAG:RegExp("^("+$.replace("w","w*")+")"),ATTR:RegExp("^"+R),PSEUDO:RegExp("^"+W),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+q+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},G=/^[^{]+\{\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){B.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,f,m,y,x;if((t?t.ownerDocument||t:w)!==d&&p(t),t=t||d,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=f=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=bt(e),(f=t.getAttribute("id"))?m=f.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+xt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(N){}finally{f||t.removeAttribute("id")}}}return Dt(e.replace(z,"$1"),t,n,i)}function st(e){return G.test(e+"")}function lt(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function ut(e){return e[b]=!0,e}function ct(e){var t=d.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function pt(e,t,n){e=e.split("|");var r,i=e.length,a=n?null:t;while(i--)(r=o.attrHandle[e[i]])&&r!==t||(o.attrHandle[e[i]]=a)}function dt(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:e[t]===!0?t.toLowerCase():null}function ft(e,t){return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}function ht(e){return"input"===e.nodeName.toLowerCase()?e.defaultValue:t}function gt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||L)-(~e.sourceIndex||L);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function mt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function yt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function vt(e){return ut(function(t){return t=+t,ut(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==d&&9===n.nodeType&&n.documentElement?(d=n,f=n.documentElement,h=!s(n),r.attributes=ct(function(e){return e.innerHTML="<a href='#'></a>",pt("type|href|height|width",ft,"#"===e.firstChild.getAttribute("href")),pt(q,dt,null==e.getAttribute("disabled")),e.className="i",!e.getAttribute("className")}),r.input=ct(function(e){return e.innerHTML="<input>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")}),pt("value",ht,r.attributes&&r.input),r.getElementsByTagName=ct(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ct(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ct(function(e){return f.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==S&&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!==S&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==S?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!==S&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=st(n.querySelectorAll))&&(ct(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+q+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ct(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=st(y=f.webkitMatchesSelector||f.mozMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&ct(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",W)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=st(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},r.sortDetached=ct(function(e){return 1&e.compareDocumentPosition(n.createElement("div"))}),D=f.compareDocumentPosition?function(e,t){if(e===t)return A=!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 A=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return gt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?gt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):d},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==d&&p(e),t=t.replace(J,"='$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,d,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==d&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==d&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&j.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(A=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(D),A){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:ut,match:Y,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 Y.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&Q.test(r)&&(n=bt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=C[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&C(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==S&&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,d,f,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]||[],f=u[0]===N&&u[1],d=u[0]===N&&u[2],p=f&&m.childNodes[f];while(p=++f&&p&&p[g]||(d=f=0)||h.pop())if(1===p.nodeType&&++d&&p===t){c[e]=[N,f,d];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===N)d=u[1];else while(p=++f&&p&&p[g]||(d=f=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++d&&(v&&((p[b]||(p[b]={}))[e]=[N,d]),p===t))break;return d-=i,d===r||0===d%r&&d/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?ut(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ut(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?ut(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ut(function(e){return function(t){return at(e,t).length>0}}),contains:ut(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:ut(function(e){return K.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===f},focus:function(e){return e===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:vt(function(){return[0]}),last:vt(function(e,t){return[t-1]}),eq:vt(function(e,t,n){return[0>n?n+t:n]}),even:vt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:vt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:vt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:vt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=mt(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=yt(n);function bt(e,t){var n,r,i,a,s,l,u,c=E[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=Y[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):E(e,l).slice(0)}function xt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function wt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=T++;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=N+" "+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 Nt(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 Tt(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 Ct(e,t,n,r,i,o){return r&&!r[b]&&(r=Ct(r)),i&&!i[b]&&(i=Ct(i,o)),ut(function(o,a,s,l){var u,c,p,d=[],f=[],h=a.length,g=o||At(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:Tt(g,d,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=Tt(y,f),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[f[c]]=!(m[f[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):d[c])>-1&&(o[u]=!(a[u]=p))}}else y=Tt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Et(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=wt(function(e){return e===t},s,!0),p=wt(function(e){return F.call(t,e)>-1},s,!0),d=[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])d=[wt(Nt(d),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 Ct(l>1&&Nt(d),l>1&&xt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Et(e.slice(l,r)),i>r&&Et(e=e.slice(r)),i>r&&xt(e))}d.push(n)}return Nt(d)}function kt(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,f){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=f,T=u,C=s||a&&o.find.TAG("*",f&&l.parentNode||l),E=N+=null==T?1:Math.random()||.1;for(w&&(u=l!==d&&l,i=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(N=E,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]=_.call(p));y=Tt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(N=E,u=T),x};return r?ut(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=k[e+" "];if(!o){t||(t=bt(e)),n=t.length;while(n--)o=Et(t[n]),o[b]?r.push(o):i.push(o);o=k(e,kt(i,r))}return o};function At(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function Dt(e,t,n,i){var a,s,u,c,p,d=bt(e);if(!i&&1===d.length){if(s=d[0]=d[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=Y.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&xt(s),!e)return M.apply(n,i),n;break}}}return l(e,d)(i,t,!h,n,V.test(e)),n}o.pseudos.nth=o.pseudos.eq;function St(){}St.prototype=o.filters=o.pseudos,o.setFilters=new St,r.sortStable=b.split("").sort(D).join("")===b,p(),[0,0].sort(D),r.detectDuplicates=A,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(N)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!l||i&&!u||(n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,d,f=a.createElement("div");if(f.setAttribute("className","t"),f.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=f.getElementsByTagName("*")||[],r=f.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=f.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==f.className,t.leadingWhitespace=3===f.firstChild.nodeType,t.tbody=!f.getElementsByTagName("tbody").length,t.htmlSerialize=!!f.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 f.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,f.attachEvent&&(f.attachEvent("onclick",function(){t.noCloneEvent=!1}),f.cloneNode(!0).click());for(d in{submit:!0,change:!0,focusin:!0})f.setAttribute(c="on"+d,"t"),t[d+"Bubbles"]=c in e||f.attributes[c].expando===!1;f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===f.style.backgroundClip;for(d in x(t))break;return t.ownLast="0"!==d,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(f),f.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=f.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,f.innerHTML="",f.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===f.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(f,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(f,null)||{width:"4px"}).width,r=f.appendChild(a.createElement("div")),r.style.cssText=f.style.cssText=s,r.style.marginRight=r.style.width="0",f.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof f.style.zoom!==i&&(f.innerHTML="",f.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===f.offsetWidth,f.style.display="block",f.innerHTML="<div></div>",f.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==f.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=f=o=r=null)}),n=s=l=u=r=o=null,t }({});var q=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function $(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 I(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?!W(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,W(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&&!W(e)},data:function(e,t,n){return $(e,t,n)},removeData:function(e,t){return I(e,t)},_data:function(e,t,n){return $(e,t,n,!0)},_removeData:function(e,t){return I(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)),R(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?R(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function R(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:q.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function W(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--),o.cur=i,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,J=/^(?:input|select|textarea|button|object)$/i,Q=/^(?:a|area)$/i,K=/^(?:checked|selected)$/i,Y=x.support.getSetAttribute,G=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(N)||[];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(N)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=x(this),l=t,u=e.match(N)||[];while(o=u[a++])l=r?l:!s.hasClass(o),s[l?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(N);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?G&&Y||!K.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Y?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):J.test(e.nodeName)||Q.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):G&&Y||!K.test(n)?e.setAttribute(!Y&&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]=G&&Y||!K.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}}),G&&Y||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Y||(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,d,f,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={}),(d=v.handle)||(d=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(d.elem,arguments)},d.elem=e),n=(n||"").match(N)||[""],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]||{},f=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,d)!==!1||(e.addEventListener?e.addEventListener(g,d,!1):e.attachEvent&&e.attachEvent("on"+g,d))),p.add&&(p.add.call(e,f),f.handler.guid||(f.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,f):h.push(f),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,d,f,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(N)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],f=g=s[1],h=(s[2]||"").split(".").sort(),f){p=x.event.special[f]||{},f=(r?p.delegateType:p.bindType)||f,d=c[f]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=d.length;while(o--)a=d[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(d.splice(o,1),a.selector&&d.delegateCount--,p.remove&&p.remove.call(e,a));l&&!d.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,f,m.handle),delete c[f])}else for(f in c)x.event.remove(e,f+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,d,f,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=d=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),d=u;d===(i.ownerDocument||a)&&h.push(d.defaultView||d.parentWindow||e)}f=0;while((u=h[f++])&&!n.isPropagationStopped())n.type=f>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)){d=i[l],d&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,d&&(i[l]=d)}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(dt(this,e||[],!0))},filter:function(e){return this.pushStack(dt(this,e||[],!1))},is:function(e){return!!dt(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 dt(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 ft(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+;/,Nt=/<(?:script|style|link)/i,Tt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,Et=/^$|\/(?:java|ecma)script/i,kt=/^true\/(.*)/,At=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Dt={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>"]},St=ft(a),Lt=St.appendChild(a.createElement("div"));Dt.optgroup=Dt.option,Dt.tbody=Dt.tfoot=Dt.colgroup=Dt.caption=Dt.thead,Dt.th=Dt.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=jt(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=jt(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)&&Bt(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||Nt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||Dt[(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=f.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,d=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Ct.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!==d&&(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,_t),u=0;o>u;u++)i=a[u],Et.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(At,"")));l=r=null}return this}});function jt(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 _t(e){var t=kt.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Bt(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,_t(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Tt.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 qt(e){Tt.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):(Lt.innerHTML=e.outerHTML,Lt.removeChild(o=Lt.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&&Bt(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,d=ft(t),f=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(f,o.nodeType?[o]:o);else if(wt.test(o)){s=s||d.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=Dt[l]||Dt._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)&&f.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(f,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=d.lastChild}else f.push(t.createTextNode(o));s&&d.removeChild(s),x.support.appendChecked||x.grep(Ft(f,"input"),qt),h=0;while(o=f[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(d.appendChild(o),"script"),a&&Bt(s),n)){i=0;while(o=s[i++])Et.test(o.type||"")&&n.push(o)}return s=null,d},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,d=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)d[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=/%20/g,$t=/\[\]$/,It=/\r?\n/g,Rt=/^(?:submit|button|image|reset|file)$/i,Wt=/^(?: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")&&Wt.test(this.nodeName)&&!Rt.test(e)&&(this.checked||!Tt.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(It,"\r\n")}}):{name:t.name,value:n.replace(It,"\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)zt(r,e[r],n,o);return i.join("&").replace(Pt,"+")};function zt(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||$t.test(e)?r(e,i):zt(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)zt(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)}}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
src/List/ListItemIcon.js
dsslimshaddy/material-ui
// @flow import React from 'react'; import type { Element } from 'react'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = (theme: Object) => ({ root: { height: 24, marginRight: theme.spacing.unit * 2, width: 24, color: theme.palette.action.active, }, }); type DefaultProps = { classes: Object, }; export type Props = { /** * The content of the component, normally `Icon`, `SvgIcon`, * or a `material-ui-icons` SVG icon component. */ children: Element<*>, /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, }; type AllProps = DefaultProps & Props; /** * A simple wrapper to apply `List` styles to an `Icon` or `SvgIcon`. */ function ListItemIcon(props: AllProps) { const { children, classes, className: classNameProp, ...other } = props; return React.cloneElement(children, { className: classNames(classes.root, classNameProp, children.props.className), ...other, }); } export default withStyles(styles, { name: 'MuiListItemIcon' })(ListItemIcon);
src/svg-icons/image/grain.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageGrain = (props) => ( <SvgIcon {...props}> <path d="M10 12c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-4 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); ImageGrain = pure(ImageGrain); ImageGrain.displayName = 'ImageGrain'; ImageGrain.muiName = 'SvgIcon'; export default ImageGrain;
src/app/Layout/Components/LoginField.js
aayush-k/airAssist
import React from 'react'; import ReactDom from "react-dom"; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; export default class LoginField extends React.Component { constructor() { super(); } render() { return ( <div> <h2>Welcome</h2> <TextField floatingLabelText="Last Name" /> <br /> <TextField floatingLabelText="Seat Number" /> <br/> </div> ); } }
src/Parser/DemonHunter/Vengeance/Modules/Tier/Tier20/Tier20-2P.js
enragednuke/WoWAnalyzer
import React from 'react'; import Combatants from 'Parser/Core/Modules/Combatants'; import Enemies from 'Parser/Core/Modules/Enemies'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import Analyzer from 'Parser/Core/Analyzer'; import { formatPercentage, formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class Tier202PBonus extends Analyzer { static dependencies = { combatants: Combatants, enemies: Enemies, }; on_initialized() { this.active = this.combatants.selected.hasBuff(SPELLS.VENG_DH_T20_2P_BONUS.id); } suggestions(when) { const tormentedPercentage = this.enemies.getBuffUptime(SPELLS.VENG_DH_T20_2P_BONUS_BUFF.id) / this.owner.fightDuration; when(tormentedPercentage).isLessThan(0.85) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Try to consume <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> more often. This is a great damage reduction by applying <SpellLink id={SPELLS.VENG_DH_T20_2P_BONUS_BUFF.id} /> debuff. Try to refresh it even if you have just one <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> available.</span>) .icon('ability_demonhunter_vengefulretreat2') .actual(`${formatPercentage(tormentedPercentage)}% debuff total uptime.`) .recommended(`>${formatPercentage(recommended)}% is recommended`) .regular(recommended - 0.05) .major(recommended - 0.15); }); } statistic() { const tormented = this.enemies.getBuffUptime(SPELLS.VENG_DH_T20_2P_BONUS_BUFF.id); const tormentedPercentage = tormented / this.owner.fightDuration; return ( <StatisticBox icon={<SpellIcon id={SPELLS.VENG_DH_T20_2P_BONUS_BUFF.id} />} value={`${formatPercentage(tormentedPercentage)}%`} label="Tormented debuff Uptime" tooltip={`The Tormented total uptime was ${formatDuration(tormented / 1000)}.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(11); } export default Tier202PBonus;
src/svg-icons/action/receipt.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionReceipt = (props) => ( <SvgIcon {...props}> <path d="M18 17H6v-2h12v2zm0-4H6v-2h12v2zm0-4H6V7h12v2zM3 22l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2v20z"/> </SvgIcon> ); ActionReceipt = pure(ActionReceipt); ActionReceipt.displayName = 'ActionReceipt'; export default ActionReceipt;
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
shenhzou654321/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import AvatarItem from 'components/common/AvatarItem.react'; var ContactItem = React.createClass({ displayName: 'ContactItem', propTypes: { contact: React.PropTypes.object, onSelect: React.PropTypes.func }, mixins: [PureRenderMixin], _onSelect() { this.props.onSelect(this.props.contact); }, render() { let contact = this.props.contact; return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this._onSelect}>add</a> </div> </li> ); } }); export default ContactItem;
__scripts__/__tests__/builds/should_build_for_web_target_->_{name}.js_+_{name}.min.js/.eslintrc.js
artisin/js-library-setup-guide
module.exports = { "parser": "babel-eslint", "extends": [ // A configuration file can extend the set of enabled rules from base configurations. "eslint:recommended", "plugin:node/recommended", "plugin:lodash/recommended", ], "plugins": [ // third-party plugin e.g. "react" (must run `npm install eslint-plugin-react`) "node", "lodash", ], "env": { "browser": true, // browser global variables. "node": true, // Node.js global variables and Node.js scoping. "commonjs": true, // CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack). "shared-node-browser": true, // Globals common to both Node and Browser. "es6": true, // enable all ECMAScript 6 features except for modules (this automatically sets the ecmaVersion parser option to 6). "worker": true, // web workers global variables. "amd": false, // defines require() and define() as global variables as per the amd spec. "mocha": true, // adds all of the Mocha testing global variables. "jasmine": false, // adds all of the Jasmine testing global variables for version 1.3 and 2.0. "jest": false, // Jest global variables. "phantomjs": false, // PhantomJS global variables. "protractor": false, // Protractor global variables. "qunit": false, // QUnit global variables. "jquery": false, // jQuery global variables. "prototypejs": false, // Prototype.js global variables. "shelljs": false, // ShellJS global variables. "meteor": false, // Meteor global variables. "mongo": false, // MongoDB global variables. "applescript": false, // AppleScript global variables. "nashorn": false, // Java 8 Nashorn global variables. "serviceworker": false, // Service Worker global variables. "atomtest": false, // Atom test helper globals. "embertest": false, // Ember test helper globals. "webextensions": false, // WebExtensions globals. "greasemonkey": false, // GreaseMonkey globals. }, "parserOptions": { "ecmaVersion": 7, "sourceType": "module", "ecmaFeatures": { "binaryLiterals": true, // enable binary literals "blockBindings": true, // enable let and const (aka block bindings) "defaultParams": true, // enable default function parameters "forOf": true, // enable for-of loops "generators": true, // enable generators "objectLiteralComputedProperties": true, // enable computed object literal property names "objectLiteralDuplicateProperties": true, // enable duplicate object literal properties in strict mode "objectLiteralShorthandMethods": true, // enable object literal shorthand methods "objectLiteralShorthandProperties": true, // enable object literal shorthand properties "octalLiterals": true, // enable octal literals "regexUFlag": true, // enable the regular expression u flag "regexYFlag": true, // enable the regular expression y flag "templateStrings": true, // enable template strings "unicodeCodePointEscapes": true, // enable code point escapes "jsx": true // enable JSX } }, "globals": { "_": true, "Immutable": true, "React": true, "log": true }, "rules": { ////////// Possible Errors ////////// "comma-dangle": 0, // disallow trailing commas in object literals "no-cond-assign": 2, // disallow assignment in conditional expressions "no-console": 2, // disallow use of console (off by default in the node environment) "no-constant-condition": 2, // disallow use of constant expressions in conditions "no-control-regex": 2, // disallow control characters in regular expressions "no-debugger": 2, // disallow use of debugger "no-dupe-args": 2, // disallow duplicate arguments in functions "no-dupe-keys": 2, // disallow duplicate keys when creating object literals "no-duplicate-case": 2, // disallow a duplicate case label "no-empty-character-class": 2, // disallow the use of empty character classes in regular expressions "no-empty": 2, // disallow empty statements "no-ex-assign": 2, // disallow assigning to the exception in a catch block "no-extra-boolean-cast": 2, // disallow double-negation boolean casts in a boolean context "no-extra-parens": 0, // disallow unnecessary parentheses (off by default) "no-extra-semi": 2, // disallow unnecessary semicolons "no-func-assign": 2, // disallow overwriting functions written as function declarations "no-inner-declarations": 2, // disallow function or variable declarations in nested blocks "no-invalid-regexp": 2, // disallow invalid regular expression strings in the RegExp constructor "no-irregular-whitespace": 2, // disallow irregular whitespace outside of strings and comments "no-negated-in-lhs": 2, // disallow negation of the left operand of an in expression "no-obj-calls": 2, // disallow the use of object properties of the global object (Math and JSON) as functions "no-regex-spaces": 2, // disallow multiple spaces in a regular expression literal "no-reserved-keys": 0, // disallow reserved words being used as object literal keys (off by default) "no-sparse-arrays": 2, // disallow sparse arrays "no-unreachable": 2, // disallow unreachable statements after a return, throw, continue, or break statement "use-isnan": 2, // disallow comparisons with the value NaN "valid-jsdoc": 0, // Ensure JSDoc comments are valid (off by default) "valid-typeof": 0, // Ensure that the results of typeof are compared against a valid string "no-unexpected-multiline": 2, // Avoid code that looks like two expressions but is actually one (off by default) ////////// Best Practices ////////// "accessor-pairs": 2, // enforces getter/setter pairs in objects (off by default) "block-scoped-var": 2, // treat var statements as if they were block scoped (off by default) "complexity": 2, // specify the maximum cyclomatic complexity allowed in a program (off by default) "consistent-return": 0, // require return statements to either always or never specify values "curly": 2, // specify curly brace conventions for all control statements "default-case": 2, // require default case in switch statements (off by default) "dot-notation": 2, // encourages use of dot notation whenever possible "dot-location": 0, // enforces consistent newlines before or after dots (off by default) "eqeqeq": 2, // require the use of === and !== "guard-for-in": 2, // make sure for-in loops have an if statement (off by default) "no-alert": 2, // disallow the use of alert, confirm, and prompt "no-caller": 2, // disallow use of arguments.caller or arguments.callee "no-div-regex": 2, // disallow division operators explicitly at beginning of regular expression (off by default) "no-else-return": 2, // disallow else after a return in an if (off by default) "no-eq-null": 2, // disallow comparisons to null without a type-checking operator (off by default) "no-eval": 2, // disallow use of eval() "no-extend-native": 2, // disallow adding to native types "no-extra-bind": 2, // disallow unnecessary function binding "no-fallthrough": 2, // disallow fallthrough of case statements "no-floating-decimal": 2, // disallow the use of leading or trailing decimal points in numeric literals (off by default) "no-implied-eval": 2, // disallow use of eval()-like methods "no-iterator": 2, // disallow usage of __iterator__ property "no-labels": 2, // disallow use of labeled statements "no-lone-blocks": 2, // disallow unnecessary nested blocks "no-loop-func": 2, // disallow creation of functions within loops "no-multi-spaces": 0, // disallow use of multiple spaces "no-multi-str": 2, // disallow use of multiline strings "no-native-reassign": 2, // disallow reassignments of native objects "no-new-func": 2, // disallow use of new operator for Function object "no-new-wrappers": 2, // disallows creating new instances of String, Number, and Boolean "no-new": 2, // disallow use of new operator when not part of the assignment or comparison "no-octal-escape": 2, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251"; "no-octal": 2, // disallow use of octal literals "no-param-reassign": 0, // disallow reassignment of function parameters (off by default) "no-process-env": 2, // disallow use of process.env (off by default) "no-proto": 2, // disallow usage of __proto__ property "no-redeclare": 2, // disallow declaring the same variable more then once "no-return-assign": 2, // disallow use of assignment in return statement "no-script-url": 2, // disallow use of javascript: urls "no-self-compare": 2, // disallow comparisons where both sides are exactly the same (off by default) "no-sequences": 2, // disallow use of comma operator "no-throw-literal": 2, // restrict what can be thrown as an exception (off by default) "no-unused-expressions": 2, // disallow usage of expressions in statement position "no-void": 2, // disallow use of void operator (off by default) "no-warning-comments": 2, // disallow usage of configurable warning terms in comments, e.g. TODO or FIXME (off by default) "no-with": 2, // disallow use of the with statement "radix": 2, // require use of the second argument for parseInt() (off by default) "vars-on-top": 2, // requires to declare all vars on top of their containing scope (off by default) "wrap-iife": 2, // require immediate function invocation to be wrapped in parentheses (off by default) "yoda": 2, // require or disallow Yoda conditions ////////// Variables ////////// "no-catch-shadow": 2, // disallow the catch clause parameter name being the same as a variable in the outer scope (off by default in the node environment) "no-delete-var": 2, // disallow deletion of variables "no-label-var": 2, // disallow labels that share a name with a variable "no-shadow": 2, // disallow declaration of variables already declared in the outer scope "no-shadow-restricted-names": 2, // disallow shadowing of names such as arguments "no-undef": 2, // disallow use of undeclared variables unless mentioned in a /*global */ block "no-undef-init": 2, // disallow use of undefined when initializing variables "no-undefined": 2, // disallow use of undefined variable (off by default) "no-unused-vars": 1, // disallow declaration of variables that are not used in the code "no-use-before-define": 2, // disallow use of variables before they are defined ////////// Node.js ////////// "handle-callback-err": 2, // enforces error handling in callbacks (off by default) (on by default in the node environment) "no-mixed-requires": 2, // disallow mixing regular variable and require declarations (off by default) (on by default in the node environment) "no-new-require": 2, // disallow use of new operator with the require function (off by default) (on by default in the node environment) "no-path-concat": 2, // disallow string concatenation with __dirname and __filename (off by default) (on by default in the node environment) "no-process-exit": 2, // disallow process.exit() (on by default in the node environment) "no-restricted-modules": 2, // restrict usage of specified node modules (off by default) "no-sync": 2, // disallow use of synchronous methods (off by default) ////////// Stylistic Issues ////////// "array-bracket-spacing": 2, // enforce spacing inside array brackets (off by default) "brace-style": [2, // enforce one true brace style (off by default) "1tbs", { "allowSingleLine": true } ], "camelcase": 2, // require camel case names "comma-spacing": 2, // enforce spacing before and after comma "comma-style": 2, // enforce one true comma style (off by default) "computed-property-spacing": 2, // require or disallow padding inside computed properties (off by default) "consistent-this": 0, // enforces consistent naming when capturing the current execution context (off by default) "eol-last": 2, // enforce newline at the end of file, with no multiple empty lines "func-names": 0, // require function expressions to have a name (off by default) "func-style": 2, // enforces use of function declarations or expressions (off by default) "indent": [1, 2, { // this option sets a specific tab width for your code (off by default) "SwitchCase": 2, "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } } ], "key-spacing": 2, // enforces spacing between keys and values in object literal properties "lines-around-comment": 0, // enforces empty lines around comments (off by default) "linebreak-style": 2, // disallow mixed 'LF' and 'CRLF' as linebreaks (off by default) "max-nested-callbacks": 2, // specify the maximum depth callbacks can be nested (off by default) "new-cap": 1, // require a capital letter for constructors "new-parens": 2, // disallow the omission of parentheses when invoking a constructor with no arguments "new-parens": 2, // disallow the omission of parentheses when invoking a constructor with no arguments "newline-after-var": 0, // allow/disallow an empty newline after var statement (off by default) "no-array-constructor": 2, // disallow use of the Array constructor "no-continue": 1, // disallow use of the continue statement (off by default) "no-inline-comments": 0, // disallow comments inline after code (off by default) "no-lonely-if": 2, // disallow if as the only statement in an else block (off by default) "no-mixed-spaces-and-tabs": 2, // disallow mixed spaces and tabs for indentation "no-multiple-empty-lines": 0, // disallow multiple empty lines (off by default) "no-nested-ternary": 2, // disallow nested ternary expressions (off by default) "no-new-object": 2, // disallow use of the Object constructor "no-spaced-func": 2, // disallow space between function identifier and application "no-ternary": 0, // disallow the use of ternary operators (off by default) "no-trailing-spaces": 2, // disallow trailing whitespace at the end of lines "no-underscore-dangle": 0, // disallow dangling underscores in identifiers "one-var": 0, // allow just one var statement per function (off by default) "operator-assignment": 2, // require assignment operator shorthand where possible or prohibit it entirely (off by default) "operator-linebreak": 0, // enforce operators to be placed before or after line breaks (off by default) "padded-blocks": 0, // enforce padding within blocks (off by default) "quotes": [2, "single"], // require quotes around object literal property names (off by default) "quote-props": [2, "as-needed"], // specify whether double or single quotes should be used "semi-spacing": [2, { // enforce spacing before and after semicolons "before": false, "after": true }], "semi": [2, "always"], // require or disallow use of semicolons instead of ASI "sort-vars": 0, // sort variables within the same declaration block (off by default) "space-after-keywords": 0, // require a space after certain keywords (off by default) "space-before-blocks": 2, // require or disallow space before blocks (off by default) "space-before-function-paren": 0, // require or disallow space before function opening parenthesis (off by default) "space-in-parens": 2, // require or disallow spaces inside parentheses (off by default) "space-infix-ops": 2, // require spaces around operators "space-unary-ops": 2, // require or disallow spaces before/after unary operators (words on by default, nonwords off by default) "spaced-comment": 0, // require or disallow a space immediately following the // or /* in a comment (off by default) "wrap-regex": 2, // require regex literals to be wrapped in parentheses (off by default) ////////// ECMAScript 6 ////////// "constructor-super": 2, // verify super() callings in constructors (off by default) "generator-star-spacing": 2, // enforce the spacing around the * in generator functions (off by default) "no-this-before-super": 2, // disallow to use this/super before super() calling in constructors (off by default) "no-var": 2, // require let or const instead of var (off by default) "object-shorthand": 0, // require method and property shorthand syntax for object literals (off by default) "prefer-const": 1, // suggest using of const declaration for variables that are never modified after declared (off by default) "require-await": 0, // warns async functions which have no await expression. ////////// Lodash PLugin ////////// "lodash/import-scope": [2, "member"], ////////// Node PLugin ////////// "node/no-extraneous-import": 0, "node/no-unsupported-features": 0, } };
src/lib/animation.js
jameskraus/react-vis
import React from 'react'; import {interpolate} from 'd3-interpolate'; import {spring, Motion} from 'react-motion'; import PureRenderComponent from './pure-render-component'; const propTypes = { animatedProps: React.PropTypes.arrayOf(React.PropTypes.string).isRequired, onStart: React.PropTypes.func, onEnd: React.PropTypes.func, stiffness: React.PropTypes.number, damping: React.PropTypes.number, precision: React.PropTypes.number }; class Animation extends PureRenderComponent { constructor(props) { super(props); this._updateInterpolator(props); this._renderChildren = this._renderChildren.bind(this); this._motionEndHandler = this._motionEndHandler.bind(this); } componentWillUpdate(props) { this._updateInterpolator(this.props, props); if (props.onStart) { props.onStart(); } } /** * Update the interpolator function and assign it to this._interpolator. * @param {Object} oldProps Old props. * @param {Object} newProps New props. * @private */ _updateInterpolator(oldProps, newProps) { this._interpolator = interpolate( this._extractAnimatedPropValues(oldProps), newProps ? this._extractAnimatedPropValues(newProps) : null ); } /** * Extract the animated props from the entire props object. * @param {Object} props Props. * @returns {Object} Object of animated props. * @private */ _extractAnimatedPropValues(props) { const {animatedProps, ...otherProps} = props; return animatedProps.reduce((result, animatedPropName) => { if (otherProps.hasOwnProperty(animatedPropName)) { result[animatedPropName] = otherProps[animatedPropName]; } return result; }, {}); } /** * Render the child into the parent. * @param {Number} i Number generated by the spring. * @returns {React.Component} Rendered react element. * @private */ _renderChildren({i}) { const {children} = this.props; const interpolator = this._interpolator; const child = React.Children.only(children); const interpolatedProps = interpolator ? interpolator(i) : interpolator; return React.cloneElement( child, { ...child.props, ...interpolatedProps, // enforce re-rendering _animation: Math.random() } ); } _motionEndHandler() { if (this.props.onEnd) { this.props.onEnd(); } } render() { const defaultStyle = {i: 0}; const style = {i: spring(1)}; // In order to make Motion re-run animations each time, the random key is // always passed. // TODO: find a better solution for the spring. const key = Math.random(); return ( <Motion {...{defaultStyle, style, key}} onRest={this._motionEndHandler}> {this._renderChildren} </Motion> ); } } Animation.propTypes = propTypes; Animation.displayName = 'Animation'; export default Animation;
src/routes/indexMyCustom.js
daxiangaikafei/QBGoods
import React from 'react' import { Route, IndexRoute, Router } from 'dva/router' import CoreLayout from '../containers/layout' import Hotgoods from 'views/Hotgoods/page' import MyCustom from 'views/MyCustom/page' import SelfSupport from 'views/SelfSupport/page' import GatherGoods from 'views/GatherGoods/page' import GatherStore from 'views/GatherStore/page' import ShopActivity from 'views/ShopActivity/page' import Order from "views/Order/page" import BannerEntry from "views/Activity/bannerEntry" import Banner01 from "views/Activity/banner01" import ChannelEntry from "views/Activity/channelEntry" export default function (ref) { return ( <Router history={ref.history}> <Route path='/' component={CoreLayout} name="我有好物"> <IndexRoute component={MyCustom} name="我的定制"/> <Route path='/MyCustom' component={MyCustom} name="我的定制" /> </Route> </Router> ) }
frontend/src/Settings/AdvancedSettingsButton.js
geogolem/Radarr
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import Icon from 'Components/Icon'; import Link from 'Components/Link/Link'; import { icons } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; import styles from './AdvancedSettingsButton.css'; function AdvancedSettingsButton(props) { const { advancedSettings, onAdvancedSettingsPress } = props; return ( <Link className={styles.button} title={advancedSettings ? translate('ShownClickToHide') : translate('HiddenClickToShow')} onPress={onAdvancedSettingsPress} > <Icon name={icons.ADVANCED_SETTINGS} size={21} /> <span className={classNames( styles.indicatorContainer, 'fa-layers fa-fw' )} > <Icon className={styles.indicatorBackground} name={icons.CIRCLE} size={16} /> <Icon className={advancedSettings ? styles.enabled : styles.disabled} name={advancedSettings ? icons.CHECK : icons.CLOSE} size={10} /> </span> <div className={styles.labelContainer}> <div className={styles.label}> {advancedSettings ? translate('HideAdvanced') : translate('ShowAdvanced')} </div> </div> </Link> ); } AdvancedSettingsButton.propTypes = { advancedSettings: PropTypes.bool.isRequired, onAdvancedSettingsPress: PropTypes.func.isRequired }; export default AdvancedSettingsButton;
src/components/PersonView/PersonView.js
rlesniak/tind3r.com
// @flow import React, { Component } from 'react'; import { reaction, observable } from 'mobx'; import get from 'lodash/get'; import uniqueId from 'lodash/uniqueId'; import { observer, inject } from 'mobx-react'; import ReactTooltip from 'react-tooltip'; import Gallery from 'components/Gallery'; import ActionButtons from 'components/ActionButtons'; import Bio from 'components/Bio'; import Person from 'models/Person'; import recsStore from 'stores/RecsStore'; import withLikeCounter from 'hoc/withLikeCounter'; import { fbUserSearchUrlBySchool, fbUserSearchUrlByInterests } from 'utils'; import { getMatchByPerson, getActions } from 'utils/database.v2'; import type { ActionsType } from 'types/person'; import type { MatchType } from 'types/match'; import type { WithLikeCounterPropsType } from 'hoc/withLikeCounter'; import './PersonView.scss'; type PropsType = WithLikeCounterPropsType & { personId: ?string, onActionClick?: () => void, person: Person, withoutFetch: boolean, }; @inject('currentUser') @withLikeCounter @observer class PersonView extends Component { constructor(props: PropsType) { super(props); const json = this.props.person || { _id: this.props.personId }; this.match = getMatchByPerson(json._id); this.person = new Person({}, json); this.reactionDispose = reaction( () => this.person.is_loading, (state) => { if (this.props.person && state === false) { this.forceUpdate(); } }, ); } componentDidMount() { this.checkAction(); if (this.props.withoutFetch) return; this.person.fetch(); ReactTooltip.rebuild(); } componentDidUpdate() { ReactTooltip.rebuild(); } componentWillUnmount() { this.reactionDispose(); } props: PropsType; match: MatchType; person: Person; reactionDispose: () => void = n => n; @observable activeAction: ?ActionsType; handleActionClick = (type: ActionsType) => { const { onActionClick, handleSuperlike, handleError } = this.props; const pero = recsStore.persons.find(person => person._id === this.person._id); const person = pero || this.person; this.activeAction = type; if (person) { person.callAction(type, handleSuperlike, n => n, handleError); } if (onActionClick) { onActionClick(); } }; checkAction() { const { match } = this; if (match) { this.activeAction = match.is_super_like ? 'superlike' : (!match.is_super_like ? 'like' : null); // eslint-disable-line } if (!this.activeAction) { this.activeAction = get(getActions(this.person._id), '0.action_type', null); } } renderSchools() { if (this.person.schools && this.person.schools.length) { return ( <ul> {this.person.schools.map(school => ( <li key={school.id}> <a href={fbUserSearchUrlBySchool(school.id, this.person.name)} target="_blank" rel="noreferrer noopener" data-tip="Do Facebook search based on school and name. <br /> Tinder user has to have at least one Facebook photo <br /> so you can compare and find right person." data-for="main" data-offset="{'top': -10, 'left': -12}" className="person-view__fb-search" > <i className="fa fa-eye" /> </a> {school.name} </li> ))} </ul> ); } return null; } renderJobs() { if (this.person.jobs && this.person.jobs.length) { return ( <ul> {this.person.jobs.map(j => <li key={uniqueId()}>{get(j, 'company.name', null)}</li>)} </ul> ); } return null; } renderConnections() { if (this.person.common_connections && this.person.common_connections.length) { return ( <ul className="person-view__connections"> <li className="person-view__connections-header">Common connections:</li> {this.person.common_connections.map(c => <li key={c.id}>{c.name}</li>)} </ul> ); } return null; } renderInterests() { if (this.person.common_interests && this.person.common_interests.length) { return ( <ul className="person-view__connections"> <li className="person-view__connections-header">Common interests:</li> {this.person.common_interests.map(c => ( <li key={c.id}> <a href={fbUserSearchUrlByInterests(c.id, this.person.name)} target="_blank" rel="noreferrer noopener" data-tip="Do Facebook search based on interest and name. <br /> Tinder user has to have at least one Facebook photo <br /> so you can compare and find right person." data-for="main" > {c.name} </a> </li>))} <li key="ALL"> <a href={fbUserSearchUrlByInterests(this.person.common_interests.map(c => c.id), this.person.name)} target="_blank" rel="noreferrer noopener" data-tip="Do Facebook search based on all interests and name. <br /> Tinder user has to have at least one Facebook photo <br /> so you can compare and find right person." data-for="main" > ALL </a> </li> </ul> ); } return null; } render() { const { person } = this; const width = 500; const { currentUser, superlikeResetRemaining, likeResetRemaining } = this.props; const instagramPhotos = (person.instagram && person.instagram.photos) || []; const photos = person.photos.concat(instagramPhotos.map(photo => ({ id: photo.ts, url: photo.image }))); return ( <div className="person-view"> <div className="person-view__left"> <div className="person-view__info"> <div className="person-view__name">{person.name}, {person.age}</div> <div className="person-view__distance">{person.distanceKm}</div> <div className="person-view__lists"> {this.renderSchools()} {this.renderJobs()} </div> <div className="person-view__bio"> <Bio text={person.bio} /> </div> {person.instagramUsername && <div className="person-view__insta"> <a href={person.instagramProfileLink} target="_blank" rel="noopener noreferrer"> <i className="fa fa-instagram" /> <span>{person.instagramUsername}</span> </a> </div>} {this.renderConnections()} {this.renderInterests()} </div> <div className="person-view__buttons"> {person._id !== currentUser._id && <ActionButtons superLikeResetsAt={superlikeResetRemaining} superlikeRemaining={currentUser.superlike_remaining} superlikeDisabled={currentUser.superlike_remaining === 0} likeResetsAt={likeResetRemaining} likeDisabled={!!likeResetRemaining} onButtonClick={this.handleActionClick} hideTimer={false} size="large" activeAction={this.activeAction} />} </div> </div> <div className="person-view__gallery" style={{ width: `${width}px` }}> <Gallery delay={200} scrolling={false} images={photos} width={width} withArrowNav lazyLoad={false} /> </div> </div> ); } } export default PersonView;
ajax/libs/yui/3.0.0beta1m3/yui/yui.js
xymostech/cdnjs
/** * YUI core * @module yui */ (function() { var _instances = {}, _startTime = new Date().getTime(), p, i, add = function () { if (window.addEventListener) { return function(el, type, fn, capture) { el.addEventListener(type, fn, (!!capture)); }; } else if (window.attachEvent) { return function(el, type, fn) { el.attachEvent("on" + type, fn); }; } else { return function(){}; } }(), remove = function() { if (window.removeEventListener) { return function (el, type, fn, capture) { el.removeEventListener(type, fn, !!capture); }; } else if (window.detachEvent) { return function (el, type, fn) { el.detachEvent("on" + type, fn); }; } else { return function(){}; } }(), globalListener = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; remove(window, 'load', globalListener); }, // @TODO: this needs to be created at build time from module metadata _APPLY_TO_WHITE_LIST = { 'io.xdrReady': 1, 'io.start': 1, 'io.success': 1, 'io.failure': 1 }; // reduce to one or the other if (typeof YUI === 'undefined' || !YUI) { /** * The YUI global namespace object. If YUI is already defined, the * existing YUI object will not be overwritten so that defined * namespaces are preserved. * * @class YUI * @constructor * @global * @uses Event.Target * @param o Optional configuration object. Options: * <ul> * <li>------------------------------------------------------------------------</li> * <li>Global:</li> * <li>------------------------------------------------------------------------</li> * <li>debug: Turn debug statements on or off</li> * <li>useBrowserConsole: * Log to the browser console if debug is on and the console is available</li> * <li>logInclude: * A hash of log sources that should be logged. If specified, only log messages from these sources will be logged. * * </li> * <li>logExclude: * A hash of log sources that should be not be logged. If specified, all sources are logged if not on this list.</li> * <li>injected: set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event and onDOMReady.</li> * <li>throwFail: * If throwFail is set, Y.fail will generate or re-throw a JS error. Otherwise the failure is logged. * <li>win: * The target window/frame</li> * <li>core: * A list of modules that defines the YUI core (overrides the default)</li> * <li>dateFormat: default date format</li> * <li>locale: default locale</li> * <li>------------------------------------------------------------------------</li> * <li>For event and get:</li> * <li>------------------------------------------------------------------------</li> * <li>pollInterval: The default poll interval</li> * <li>windowResizeDelay: The time between browser events to wait before firing.</li> * <li>-------------------------------------------------------------------------</li> * <li>For loader:</li> * <li>-------------------------------------------------------------------------</li> * <li>base: The base dir</li> * <li>secureBase: The secure base dir (not implemented)</li> * <li>comboBase: The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li> * <li>root: The root path to prepend to module names for the combo service. Ex: 2.5.2/build/</li> * <li>filter: * * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * </li> * <li>filters: per-component filter specification. If specified for a given component, this overrides the filter config</li> * <li>combine: * Use the YUI combo service to reduce the number of http connections required to load your dependencies</li> * <li>ignore: * A list of modules that should never be dynamically loaded</li> * <li>force: * A list of modules that should always be loaded when required, even if already present on the page</li> * <li>insertBefore: * Node or id for a node that should be used as the insertion point for new nodes</li> * <li>charset: * charset for dynamic nodes</li> * <li>timeout: * number of milliseconds before a timeout occurs when dynamically loading nodes. in not set, there is no timeout</li> * <li>context: * execution context for all callbacks</li> * <li>onSuccess: * callback for the 'success' event</li> * <li>onFailure: * callback for the 'failure' event</li> * <li>onCSS: callback for the 'CSSComplete' event. When loading YUI components with CSS * the CSS is loaded first, then the script. This provides a moment you can tie into to improve * the presentation of the page while the script is loading.</li> * <li>onTimeout: * callback for the 'timeout' event</li> * <li>onProgress: * callback executed each time a script or css file is loaded</li> * <li>modules: * A list of module definitions. See Loader.addModule for the supported module metadata</li> * </ul> */ /*global YUI*/ // Make a function, disallow direct instantiation YUI = function(o) { var Y = this; // Allow instantiation without the new operator if (!(Y instanceof YUI)) { return new YUI(o); } else { // set up the core environment Y._init(o); // bind the specified additional modules for this instance Y._setup(); return Y; } }; } // The prototype contains the functions that are required to allow the external // modules to be registered and for the instance to be initialized. YUI.prototype = { /** * Initialize this YUI instance * @param o config options * @private */ _init: function(o) { o = o || {}; // find targeted window/frame // @TODO create facades var v = '@VERSION@', Y = this; o.win = o.win || window || {}; o.win = o.win.contentWindow || o.win; o.doc = o.win.document; o.debug = ('debug' in o) ? o.debug : true; o.useBrowserConsole = ('useBrowserConsole' in o) ? o.useBrowserConsole : true; o.throwFail = ('throwFail' in o) ? o.throwFail : true; // add a reference to o for anything that needs it // before _setup is called. Y.config = o; Y.Env = { // @todo expand the new module metadata mods: {}, _idx: 0, _pre: 'yuid', _used: {}, _attached: {}, _yidx: 0, _uidx: 0, _loaded: {} }; if (v.indexOf('@') > -1) { v = 'test'; } Y.version = v; Y.Env._loaded[v] = {}; if (YUI.Env) { Y.Env._yidx = ++YUI.Env._idx; Y.id = Y.stamp(Y); _instances[Y.id] = Y; } Y.constructor = YUI; // this.log(this.id + ') init '); }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { this.use("yui-base"); // @TODO eval the need to copy the config this.config = this.merge(this.config); }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {string} the YUI instance id * @param method {string} the name of the method to exectute. * Ex: 'Object.keys' * @param args {Array} the arguments to apply to the method * @return {object} the return value from the applied method or null */ applyTo: function(id, method, args) { if (!(method in _APPLY_TO_WHITE_LIST)) { this.error(method + ': applyTo not allowed'); return null; } var instance = _instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i=0; i<nest.length; i=i+1) { m = m[nest[i]]; if (!m) { this.error('applyTo not found: ' + method); } } return m.apply(instance, args); } return null; }, /** * Register a module * @method add * @param name {string} module name * @param fn {Function} entry point into the module that * is used to bind module to the YUI instance * @param version {string} version string * @param details optional config data: * requires - features that should be present before loading * optional - optional features that should be present if load optional defined * use - features that should be attached automatically * skinnable - * rollup * omit - features that should not be loaded if this module is present * @return {YUI} the YUI instance * */ add: function(name, fn, version, details) { // this.log('Adding a new component ' + name); // @todo expand this to include version mapping // @todo allow requires/supersedes // @todo may want to restore the build property // @todo fire moduleAvailable event var m = { name: name, fn: fn, version: version, details: details || {} }; YUI.Env.mods[name] = m; return this; // chain support }, _attach: function(r, fromLoader) { var mods = YUI.Env.mods, attached = this.Env._attached, i, l = r.length, name, m, d, req, use; for (i=0; i<l; i=i+1) { name = r[i]; m = mods[name]; if (!attached[name] && m) { attached[name] = true; d = m.details; req = d.requires; use = d.use; if (req) { this._attach(this.Array(req)); } // this.log('attaching ' + name, 'info', 'yui'); if (m.fn) { m.fn(this); } if (use) { this._attach(this.Array(use)); } } } }, /** * Bind a module to a YUI instance * @param modules* {string} 1-n modules to bind (uses arguments array) * @param *callback {function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * * @TODO * Implement versioning? loader can load different versions? * Should sub-modules/plugins be normal modules, or do * we add syntax for specifying these? * * YUI().use('dragdrop') * YUI().use('dragdrop:2.4.0'); // specific version * YUI().use('dragdrop:2.4.0-'); // at least this version * YUI().use('dragdrop:2.4.0-2.9999.9999'); // version range * YUI().use('*'); // use all available modules * YUI().use('lang+dump+substitute'); // use lang and some plugins * YUI().use('lang+*'); // use lang and all known plugins * * * @return {YUI} the YUI instance */ use: function() { if (this._loading) { this._useQueue.add(Array.prototype.slice.call(arguments)); return this; } var Y = this, a=Array.prototype.slice.call(arguments, 0), mods = YUI.Env.mods, used = Y.Env._used, loader, firstArg = a[0], dynamic = false, callback = a[a.length-1], k, i, l, missing = [], r = [], f = function(name) { // only attach a module once if (used[name]) { return; } var m = mods[name], j, req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has been loaded if (!YUI.Env._loaded[Y.version][name]) { missing.push(name); } else { // probably css used[name] = true; } } // make sure requirements are attached if (req) { if (Y.Lang.isString(req)) { f(req); } else { for (j = 0; j < req.length; j = j + 1) { f(req[j]); } } } // add this module to full list of things to attach r.push(name); }, onComplete = function(fromLoader) { fromLoader = fromLoader || { success: true, msg: 'not dynamic' }; if (Y.Env._callback) { var cb = Y.Env._callback; Y.Env._callback = null; cb(Y, fromLoader); } if (Y.fire) { Y.fire('yui:load', Y, fromLoader); } // process queued use requests as long until done // or dynamic load happens again. this._loading = false; while (this._useQueue && this._useQueue.size() && !this._loading) { Y.use.apply(Y, this._useQueue.next()); } }; // The last argument supplied to use can be a load complete callback if (typeof callback === 'function') { a.pop(); Y.Env._callback = callback; } else { callback = null; } // YUI().use('*'); // bind everything available if (firstArg === "*") { a = []; for (k in mods) { if (mods.hasOwnProperty(k)) { a.push(k); } } return Y.use.apply(Y, a); } // use loader to expand dependencies and sort the // requirements if it is available. if (Y.Loader) { dynamic = true; this._useQueue = this._useQueue || new Y.Queue(); loader = new Y.Loader(Y.config); loader.require(a); loader.ignoreRegistered = true; loader.allowRollup = false; loader.calculate(); a = loader.sorted; } l = a.length; // process each requirement and any additional requirements // the module metadata specifies for (i=0; i<l; i=i+1) { f(a[i]); } // dynamic load if (Y.Loader && missing.length) { this._loading = true; loader = new Y.Loader(Y.config); loader.onSuccess = onComplete; loader.onFailure = onComplete; loader.onTimeout = onComplete; loader.attaching = a; loader.require(missing); loader.insert(); } else { Y._attach(r); onComplete(); } return Y; // chain support var yui = YUI().use('dragdrop'); }, /** * Returns the namespace specified and creates it if it doesn't exist * <pre> * YUI.namespace("property.package"); * YUI.namespace("YAHOO.property.package"); * </pre> * Either of the above would create YUI.property, then * YUI.property.package (YAHOO is scrubbed out, this is * to remain compatible with YUI2) * * Be careful when naming packages. Reserved words may work in some browsers * and not others. For instance, the following will fail in Safari: * <pre> * YUI.namespace("really.long.nested.namespace"); * </pre> * This fails because "long" is a future reserved word in ECMAScript * * @method namespace * @param {string*} arguments 1-n namespaces to create * @return {object} A reference to the last namespace object created */ namespace: function() { var a=arguments, o=null, i, j, d; for (i=0; i<a.length; i=i+1) { d = ("" + a[i]).split("."); o = this; for (j=(d[0] == "YAHOO") ? 1 : 0; j<d.length; j=j+1) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } return o; }, // this is replaced if the log module is included log: function() { }, /** * Report an error. The reporting mechanism is controled by * the 'throwFail' configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown * @method error * @param msg {string} the error message * @param e {Error} Optional JS error that was caught. If supplied * and throwFail is specified, this error will be re-thrown. * @return {YUI} this YUI instance */ error: function(msg, e) { if (this.config.throwFail) { throw (e || new Error(msg)); } else { this.message(msg, "error"); // don't scrub this one } return this; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {string} optional guid prefix * @return {string} the guid */ guid: function(pre) { var e = this.Env, p = (pre) || e._pre, id = p + '-' + this.version + '-' + e._yidx + '-' + (e._uidx++) + '-' + _startTime; return id.replace(/\./g, '_'); }, /** * Returns a guid associated with an object. If the object * does not have one, a new one is created unless readOnly * is specified. * @method stamp * @param o The object to stamp * @param readOnly {boolean} if true, a valid guid will only * be returned if the object has one assigned to it. * @return {string} The object's guid or null */ stamp: function(o, readOnly) { if (!o) { return o; } var uid = (typeof o === 'string') ? o : o._yuid; if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch(e) { uid = null; } } } return uid; } }; // Give the YUI global the same properties as an instance. // This makes it so that the YUI global can be used like the YAHOO // global was used prior to 3.x. More importantly, the YUI global // provides global metadata, so env needs to be configured. // @TODO review p = YUI.prototype; // inheritance utilities are not available yet for (i in p) { if (true) { YUI[i] = p[i]; } } // set up the environment YUI._init(); // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', globalListener); YUI.Env.add = add; YUI.Env.remove = remove; })(); YUI.add('yui-base', function(Y) { /** * YUI stub * @module yui * @submodule yui-base */ (function() { var instance = Y, LOGEVENT = 'yui:log', _published; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt) * @param {String} src The source of the the message (opt) * @param {boolean} silent If true, the log event won't fire * @return {YUI} YUI instance */ instance.log = function(msg, cat, src, silent) { var Y = instance, c = Y.config, bail = false, exc, inc, m, f; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { exc = c.logExclude; inc = c.logInclude; // console.log('checking src filter: ' + src + ', inc: ' + inc + ', exc: ' + exc); if (inc && !(src in inc)) { // console.log('bail: inc list found, but src is not in list: ' + src); bail = true; } else if (exc && (src in exc)) { // console.log('bail: exc list found, and src is in it: ' + src); bail = true; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (typeof console != 'undefined') { f = (cat && console[cat]) ? cat : 'log'; console[f](m); } else if (typeof opera != 'undefined') { opera.postError(m); } } if (Y.fire && !bail && !silent) { if (!_published) { Y.publish(LOGEVENT, { broadcast: 2, emitFacade: true }); _published = true; } Y.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); // Y.fire('yui:log', msg, cat, src); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt) * @param {String} src The source of the the message (opt) * @param {boolean} silent If true, the log event won't fire * @return {YUI} YUI instance */ instance.message = function() { return instance.log.apply(instance, arguments); }; /* * @TODO I'm not convinced the current log statement scrubbing routine can * be made safe with all the variations that could be supplied for * the condition. * * logIf statements are stripped from the raw and min files. * @method logIf * @for YUI * @param {boolean} condition Logging only occurs if a truthy value is provided * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt) * @param {String} src The source of the the message (opt) * @param {boolean} silent If true, the log event won't fire * @return {YUI} YUI instance */ // instance.logIf = function(condition, msg, cat, src, silent) { // if (condition) { // } // }; })(); (function() { /** * Provides the language utilites and extensions used by the library * @class Lang * @static */ Y.Lang = Y.Lang || {}; var L = Y.Lang, ARRAY = 'array', BOOLEAN = 'boolean', DATE = 'date', ERROR = 'error', FUNCTION = 'function', NUMBER = 'number', NULL = 'null', OBJECT = 'object', REGEX = 'regexp', STRING = 'string', TOSTRING = Object.prototype.toString, UNDEFINED = 'undefined', TYPES = { 'undefined' : UNDEFINED, 'number' : NUMBER, 'boolean' : BOOLEAN, 'string' : STRING, '[object Function]' : FUNCTION, '[object RegExp]' : REGEX, '[object Array]' : ARRAY, '[object Date]' : DATE, '[object Error]' : ERROR }, TRIMREGEX = /^\s+|\s+$/g, EMPTYSTRING = ''; /** * Determines whether or not the provided item is an array. * Returns false for array-like collections such as the * function arguments collection or HTMLElement collection * will return false. You can use @see Array.test if you * want to * @method isArray * @static * @param o The object to test * @return {boolean} true if o is an array */ L.isArray = function(o) { return L.type(o) === ARRAY; }; /** * Determines whether or not the provided item is a boolean * @method isBoolean * @static * @param o The object to test * @return {boolean} true if o is a boolean */ L.isBoolean = function(o) { return typeof o === BOOLEAN; }; /** * Determines whether or not the provided item is a function * Note: Internet Explorer thinks certain functions are objects: * * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * * You will have to implement additional tests if these functions * matter to you. * * @method isFunction * @static * @param o The object to test * @return {boolean} true if o is a function */ L.isFunction = function(o) { return L.type(o) === FUNCTION; }; /** * Determines whether or not the supplied item is a date instance * @method isDate * @static * @param o The object to test * @return {boolean} true if o is a date */ L.isDate = function(o) { // return o instanceof Date; return L.type(o) === DATE; }; /** * Determines whether or not the provided item is null * @method isNull * @static * @param o The object to test * @return {boolean} true if o is null */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number * @method isNumber * @static * @param o The object to test * @return {boolean} true if o is a number */ L.isNumber = function(o) { return typeof o === NUMBER && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function * @method isObject * @static * @param o The object to test * @param failfn {boolean} fail if the input is a function * @return {boolean} true if o is an object */ L.isObject = function(o, failfn) { return (o && (typeof o === OBJECT || (!failfn && L.isFunction(o)))) || false; }; /** * Determines whether or not the provided item is a string * @method isString * @static * @param o The object to test * @return {boolean} true if o is a string */ L.isString = function(o) { return typeof o === STRING; }; /** * Determines whether or not the provided item is undefined * @method isUndefined * @static * @param o The object to test * @return {boolean} true if o is undefined */ L.isUndefined = function(o) { return typeof o === UNDEFINED; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim * @return {string} the trimmed string */ L.trim = function(s){ try { return s.replace(TRIMREGEX, EMPTYSTRING); } catch(e) { return s; } }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test * @return {boolean} true if it is not null/undefined/NaN || false */ L.isValue = function(o) { var t = L.type(o); switch (t) { case NUMBER: return isFinite(o); case NULL: case UNDEFINED: return false; default: return !!(t); } }; /** * Returns a string representing the type of the item passed in. * @method type * @param o the item to test * @return {string} the detected type */ L.type = function (o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? OBJECT : NULL); }; })(); (function() { /** * YUI core * @module yui */ var L = Y.Lang, Native = Array.prototype, /** * Adds the following array utilities to the YUI instance * @class YUI~array */ /** * Y.Array(o) returns an array: * - Arrays are return unmodified unless the start position is specified. * - "Array-like" collections (@see Array.test) are converted to arrays * - For everything else, a new array is created with the input as the sole item * - The start position is used if the input is or is like an array to return * a subset of the collection. * * @TODO this will not automatically convert elements that are also collections * such as forms and selects. Passing true as the third param will * force a conversion. * * @method Array * @static * @param o the item to arrayify * @param i {int} if an array or array-like, this is the start index * @param al {boolean} if true, it forces the array-like fork. This * can be used to avoid multiple array.test calls. * @return {Array} the resulting array */ A = function(o, startIdx, al) { var t = (al) ? 2 : Y.Array.test(o), i, l, a; // switch (t) { // case 1: // // return (startIdx) ? o.slice(startIdx) : o; // case 2: // return Native.slice.call(o, startIdx || 0); // default: // return [o]; // } if (t) { try { return Native.slice.call(o, startIdx || 0); // IE errors when trying to slice element collections } catch(e) { a=[]; for (i=0, l=o.length; i<l; i=i+1) { a.push(o[i]); } return a; } } else { return [o]; } }; Y.Array = A; /** * Evaluates the input to determine if it is an array, array-like, or * something else. This is used to handle the arguments collection * available within functions, and HTMLElement collections * * @method Array.test * @static * * @todo current implementation (intenionally) will not implicitly * handle html elements that are array-like (forms, selects, etc). * * @return {int} a number indicating the results: * 0: Not an array or an array-like collection * 1: A real array. * 2: array-like collection. */ A.test = function(o) { var r = 0; if (L.isObject(o)) { if (L.isArray(o)) { r = 1; } else { try { // indexed, but no tagName (element) or alert (window) if ("length" in o && !("tagName" in o) && !("alert" in o) && (!Y.Lang.isFunction(o.size) || o.size() > 1)) { r = 2; } } catch(e) {} } } return r; }; /** * Executes the supplied function on each item in the array. * @method Array.each * @param a {Array} the array to iterate * @param f {Function} the function to execute on each item * @param o Optional context object * @static * @return {YUI} the YUI instance */ A.each = (Native.forEach) ? function (a, f, o) { Native.forEach.call(a || [], f, o || Y); return Y; } : function (a, f, o) { var l = (a && a.length) || 0, i; for (i = 0; i < l; i=i+1) { f.call(o || Y, a[i], i, a); } return Y; }; /** * Returns an object using the first array as keys, and * the second as values. If the second array is not * provided the value is set to true for each. * @method Array.hash * @static * @param k {Array} keyset * @param v {Array} optional valueset * @return {object} the hash */ A.hash = function(k, v) { var o = {}, l = k.length, vl = v && v.length, i; for (i=0; i<l; i=i+1) { o[k[i]] = (vl && vl > i) ? v[i] : true; } return o; }; /** * Returns the index of the first item in the array * that contains the specified value, -1 if the * value isn't found. * @method Array.indexOf * @static * @param a {Array} the array to search * @param val the value to search for * @return {int} the index of the item that contains the value or -1 */ A.indexOf = (Native.indexOf) ? function(a, val) { return a.indexOf(val); } : function(a, val) { for (var i=0; i<a.length; i=i+1) { if (a[i] === val) { return i; } } return -1; }; /** * Numeric sort convenience function. * Y.ArrayAssert.itemsAreEqual([1, 2, 3], [3, 1, 2].sort(Y.Array.numericSort)); * @method numericSort */ A.numericSort = function(a, b) { return (a - b); }; /** * Executes the supplied function on each item in the array. * Returning true from the processing function will stop the * processing of the remaining * items. * @method Array.some * @param a {Array} the array to iterate * @param f {Function} the function to execute on each item * @param o Optional context object * @static * @return {boolean} true if the function returns true on * any of the items in the array */ A.some = (Native.some) ? function (a, f, o) { return Native.some.call(a, f, o); } : function (a, f, o) { var l = a.length, i; for (i=0; i<l; i=i+1) { if (f.call(o, a[i], i, a)) { return true; } } return false; }; })(); (function() { var L = Y.Lang, A = Y.Array, OP = Object.prototype, IEF = ["toString", "valueOf"], PROTO = 'prototype', DELIMITER = '`~', /** * IE will not enumerate native functions in a derived object even if the * function was overridden. This is a workaround for specific functions * we care about on the Object prototype. * @property _iefix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param w a whitelist object (the keys are the valid items to reference) * @private * @for YUI */ _iefix = (Y.UA && Y.UA.ie) ? function(r, s, w) { var i, a = IEF, n, f; for (i=0; i<a.length; i=i+1) { n = a[i]; f = s[n]; if (L.isFunction(f) && f != OP[n]) { if (!w || (n in w)) { r[n]=f; } } } } : function() {}; /** * Returns a new object containing all of the properties of * all the supplied objects. The properties from later objects * will overwrite those in earlier objects. Passing in a * single object will create a shallow copy of it. For a deep * copy, use clone. * @method merge * @param arguments {Object*} the objects to merge * @return {object} the new merged object */ Y.merge = function() { var a = arguments, o = {}, i, l = a.length; for (i=0; i<l; i=i+1) { Y.mix(o, a[i], true); } return o; }; /** * Applies the supplier's properties to the receiver. By default * all prototype and static propertes on the supplier are applied * to the corresponding spot on the receiver. By default all * properties are applied, and a property that is already on the * reciever will not be overwritten. The default behavior can * be modified by supplying the appropriate parameters. * * @TODO add constants for the modes * * @method mix * @param {Function} r the object to receive the augmentation * @param {Function} s the object that supplies the properties to augment * @param ov {boolean} if true, properties already on the receiver * will be overwritten if found on the supplier. * @param wl {string[]} a whitelist. If supplied, only properties in * this list will be applied to the receiver. * @param {int} mode what should be copies, and to where * default(0): object to object * 1: prototype to prototype (old augment) * 2: prototype to prototype and object props (new augment) * 3: prototype to object * 4: object to prototype * @param merge {boolean} merge objects instead of overwriting/ignoring * Used by Y.aggregate * @return {object} the augmented object * @TODO review for PR2 */ Y.mix = function(r, s, ov, wl, mode, merge) { if (!s||!r) { return Y; } var w = (wl && wl.length) ? A.hash(wl) : null, m = merge, f = function(fr, fs, proto, iwl) { var arr = m && L.isArray(fr), i; for (i in fs) { if (fs.hasOwnProperty(i)) { // We never want to overwrite the prototype // if (PROTO === i) { if (PROTO === i || '_yuid' === i) { continue; } // @TODO deal with the hasownprop issue // check white list if it was supplied if (!w || iwl || (i in w)) { // if the receiver has this property, it is an object, // and merge is specified, merge the two objects. if (m && L.isObject(fr[i], true)) { // console.log('aggregate RECURSE: ' + i); // @TODO recursive or no? // Y.mix(fr[i], fs[i]); // not recursive f(fr[i], fs[i], proto, true); // recursive // otherwise apply the property only if overwrite // is specified or the receiver doesn't have one. // @TODO make sure the 'arr' check isn't desructive } else if (!arr && (ov || !(i in fr))) { // console.log('hash: ' + i); fr[i] = fs[i]; // if merge is specified and the receiver is an array, // append the array item } else if (arr) { // console.log('array: ' + i); // @TODO probably will need to remove dups fr.push(fs[i]); } } } } _iefix(fr, fs, w); }, rp = r.prototype, sp = s.prototype; switch (mode) { case 1: // proto to proto f(rp, sp, true); break; case 2: // object to object and proto to proto f(r, s); f(rp, sp, true); break; case 3: // proto to static f(r, sp, true); break; case 4: // static to proto f(rp, s); break; default: // object to object f(r, s); } return r; }; /** * Returns a wrapper for a function which caches the * return value of that function, keyed off of the combined * argument values. * @function cached * @param source {function} the function to memoize * @param cache an optional cache seed * @return {Function} the wrapped function */ Y.cached = function(source, cache){ cache = cache || {}; return function(arg1, arg2) { var a = arguments, key = arg2 ? Y.Array(a, 0, true).join(DELIMITER) : arg1; if (!(key in cache)) { cache[key] = source.apply(source, a); } return cache[key]; }; }; })(); (function() { /** * Adds the following Object utilities to the YUI instance * @class YUI~object */ /** * Y.Object(o) returns a new object based upon the supplied object. * @TODO Use native Object.create() when available * @method Object * @static * @param o the supplier object * @return {object} the new object */ Y.Object = function(o) { var F = function() {}; F.prototype = o; return new F(); }; var O = Y.Object, UNDEFINED = undefined, /** * Extracts the keys, values, or size from an object * * @method _extract * @param o the object * @param what what to extract (0: keys, 1: values, 2: size) * @return {boolean|Array} the extracted info * @private */ _extract = function(o, what) { var count = (what === 2), out = (count) ? 0 : [], i; for (i in o) { if (count) { out++; } else { if (o.hasOwnProperty(i)) { out.push((what) ? o[i] : i); } } } return out; }; /** * Returns an array containing the object's keys * @TODO use native Object.keys() if available * @method Object.keys * @static * @param o an object * @return {string[]} the keys */ O.keys = function(o) { return _extract(o); }; /** * Returns an array containing the object's values * @TODO use native Object.values() if available * @method Object.values * @static * @param o an object * @return {Array} the values */ O.values = function(o) { return _extract(o, 1); }; /** * Returns the size of an object * @TODO use native Object.size() if available * @method Object.size * @static * @param o an object * @return {int} the size */ O.size = function(o) { return _extract(o, 2); }; /** * Returns true if the object contains a given key * @method Object.hasKey * @static * @param o an object * @param k the key to query * @return {boolean} true if the object contains the key */ O.hasKey = function(o, k) { // return (o.hasOwnProperty(k)); return (k in o); }; /** * Returns true if the object contains a given value * @method Object.hasValue * @static * @param o an object * @param v the value to query * @return {boolean} true if the object contains the value */ O.hasValue = function(o, v) { return (Y.Array.indexOf(O.values(o), v) > -1); }; /** * Determines whether or not the property was added * to the object instance. Returns false if the property is not present * in the object, or was inherited from the prototype. * * @deprecated Safari 1.x support has been removed, so this is simply a * wrapper for the native implementation. Use the native implementation * directly instead. * * @TODO Remove in B1 * * @method Object.owns * @static * @param o {any} The object being testing * @param p {string} the property to look for * @return {boolean} true if the object has the property on the instance */ O.owns = function(o, k) { return (o.hasOwnProperty(k)); }; /** * Executes a function on each item. The function * receives the value, the key, and the object * as paramters (in that order). * @method Object.each * @static * @param o the object to iterate * @param f {function} the function to execute * @param c the execution context * @param proto {boolean} include proto * @return {YUI} the YUI instance */ O.each = function (o, f, c, proto) { var s = c || Y, i; for (i in o) { if (proto || o.hasOwnProperty(i)) { f.call(s, o[i], i, o); } } return Y; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @param o The object from which to extract the property value * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found. * Returns the source object if an empty path is provided. */ O.getValue = function (o, path) { var p=Y.Array(path), l=p.length, i; for (i=0; o !== UNDEFINED && i < l; i=i+1) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var p=Y.Array(path), leafIdx=p.length-1, i, ref=o; if (leafIdx >= 0) { for (i=0; ref !== UNDEFINED && i < leafIdx; i=i+1) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; })(); /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. UA stores a version * number for the browser engine, 0 otherwise. This value may or may not map * to the version number of the browser using the engine. The value is * presented as a float so that it can easily be used for boolean evaluation * as well as for looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost (e.g., Gecko 1.8.0.9 * reports 1.8). * @class UA * @static */ Y.UA = function() { var o={ /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie:0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera:0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- Reports 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- Reports 1.8 * Firefox 3 alpha: 1.9a4 <-- Reports 1.9 * </pre> * @property gecko * @type float * @static */ gecko:0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native SVG * and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic update * from 2.x via the 10.4.11 OS patch * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_(web_browser)#Version_history * @property webkit * @type float * @static */ webkit:0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: 0, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @static */ os: null }, ua = navigator && navigator.userAgent, loc = Y.config.win.location, href = loc && loc.href, m; o.secure = href && (href.toLowerCase().indexOf("https") === 0); if (ua) { if ((/windows|win32/).test(ua)) { o.os = 'windows'; } else if ((/macintosh/).test(ua)) { o.os = 'macintosh'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit=1; } // Modern WebKit browsers are at least X-Grade m=ua.match(/AppleWebKit\/([^\s]*)/); if (m&&m[1]) { o.webkit=parseFloat(m[1]); // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = "Apple"; // iPhone or iPod Touch } else { m=ua.match(/NokiaN[^\/]*/); if (m) { o.mobile = m[0]; // Nokia N-series, ex: NokiaN95 } } m=ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m=ua.match(/Opera[\s\/]([^\s]*)/); if (m&&m[1]) { o.opera=parseFloat(m[1]); m=ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m=ua.match(/MSIE\s([^;]*)/); if (m&&m[1]) { o.ie=parseFloat(m[1]); } else { // not opera, webkit, or ie m=ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko=1; // Gecko detected, look for revision m=ua.match(/rv:([^\s\)]*)/); if (m&&m[1]) { o.gecko=parseFloat(m[1]); } } } } } m=ua.match(/Caja\/([^\s]*)/); if (m&&m[1]) { o.caja=parseFloat(m[1]); } } return o; }(); (function() { var L = Y.Lang, /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @method later * @for YUI * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This accepts * either a single item or an array. If an array is provided, the * function is executed with one parameter for each array item. If * you need to pass a single array parameter, it needs to be wrapped in * an array [myarray]. * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this object to * stop the timer. */ later = function(when, o, fn, data, periodic) { when = when || 0; o = o || {}; var m=fn, d=data, f, r; if (L.isString(fn)) { m = o[fn]; } if (!m) { Y.error("method undefined"); } if (!L.isArray(d)) { d = [data]; } f = function() { m.apply(o, d); }; r = (periodic) ? setInterval(f, when) : setTimeout(f, when); return { id: r, interval: periodic, cancel: function() { if (this.interval) { clearInterval(r); } else { clearTimeout(r); } } }; }; Y.later = later; L.later = later; })(); (function() { // var min = ['yui-base', 'log', 'lang', 'array', 'core'], core, C = Y.config; var min = ['yui-base'], core, C = Y.config; // apply the minimal required functionality Y.use.apply(Y, min); if (C.core) { core = C.core; } else { core = ['queue-base', 'get', 'loader']; } Y.use.apply(Y, core); })(); }, '@VERSION@' ); YUI.add('queue-base', function(Y) { /** * A simple FIFO queue of function references. * * @module queue * @submodule queue-base * @class Queue * @param callback* {Function} 0..n callback functions to seed the queue */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init : function () { /** * The collection of enqueued functions * * @property _q * @type {Array} * @protected */ this._q = []; }, /** * Get the next callback in the queue. * * @method next * @return {Function} the next callback in the queue */ next : function () { return this._q.shift(); }, /** * Add 0..n callbacks to the end of the queue * * @method add * @param callback* {Function} 0..n callback functions */ add : function () { Y.Array.each(Y.Array(arguments,0,true),function (fn) { this._q.push(fn); },this); return this; }, /** * Returns the current number of queued callbacks * * @method size * @return {Number} */ size : function () { return this._q.length; } }; Y.Queue = Queue; }, '@VERSION@' ); YUI.add('get', function(Y) { (function() { /** * Provides a mechanism to fetch remote resources and * insert them into a document. * @module yui * @submodule get */ var ua = Y.UA, L = Y.Lang, PREFIX = Y.guid('yui_'), TYPE_JS = "text/javascript", TYPE_CSS = "text/css", STYLESHEET = "stylesheet"; /** * Fetches and inserts one or more script or link nodes into the document * @class Get * @static */ Y.Get = function() { /** * hash of queues to manage multiple requests * @property queues * @private */ var queues={}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx=0, /** * node index used to generate unique node ids * @property nidx * @type int * @private */ nidx=0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ purging=false, /** * Generates an HTML element, this is not appended to a document * @method _node * @param type {string} the type of element * @param attr {string} the attributes * @param win {Window} optional window to create the element in * @return {HTMLElement} the generated node * @private */ _node = function(type, attr, win) { var w = win || Y.config.win, d=w.document, n=d.createElement(type), i; for (i in attr) { if (attr[i] && attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param url {string} the url for the css file * @param win {Window} optional window to create the node in * @param attributes optional attributes collection to apply to the new node * @return {HTMLElement} the generated node * @private */ _linkNode = function(url, win, attributes) { var o = { id: PREFIX + (nidx++), type: TYPE_CSS, rel: STYLESHEET, href: url }; if (attributes) { Y.mix(o, attributes); } return _node("link", o, win); }, /** * Generates a script node * @method _scriptNode * @param url {string} the url for the script file * @param win {Window} optional window to create the node in * @param attributes optional attributes collection to apply to the new node * @return {HTMLElement} the generated node * @private */ _scriptNode = function(url, win, attributes) { var o = { id: PREFIX + (nidx++), type: TYPE_JS, src: url }; if (attributes) { Y.mix(o, attributes); } return _node("script", o, win); }, /** * Removes the nodes for the specified queue * @method _purge * @private */ _purge = function(tId) { var q=queues[tId], n, l, d, h, s, i; if (q) { n = q.nodes; l = n.length; d = q.win.document; h = d.getElementsByTagName("head")[0]; if (q.insertBefore) { s = _get(q.insertBefore, tId); if (s) { h = s.parentNode; } } for (i=0; i<l; i=i+1) { h.removeChild(n[i]); } } q.nodes = []; }, /** * Returns the data payload for callback functions * @method _returnData * @private */ _returnData = function(q, msg, result) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, statusText: result, purge: function() { _purge(this.tId); } }; }, /** * The transaction is finished * @method _end * @param id {string} the id of the request * @private */ _end = function(id, msg, result) { var q = queues[id], sc; if (q && q.onEnd) { sc = q.context || q; q.onEnd.call(sc, _returnData(q, msg, result)); } }, /* * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param id {string} the id of the request * @private */ _fail = function(id, msg) { var q = queues[id], sc; if (q.timer) { q.timer.cancel(); } // execute failure callback if (q.onFailure) { sc = q.context || q; q.onFailure.call(sc, _returnData(q, msg)); } _end(id, msg, 'failure'); }, _get = function(nId, tId) { var q = queues[tId], n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, "target node not found: " + nId); } return n; }, /** * The request is complete, so executing the requester's callback * @method _finish * @param id {string} the id of the request * @private */ _finish = function(id) { var q = queues[id], msg, sc; if (q.timer) { q.timer.cancel(); } q.finished = true; if (q.aborted) { msg = "transaction " + id + " was aborted"; _fail(id, msg); return; } // execute success callback if (q.onSuccess) { sc = q.context || q; q.onSuccess.call(sc, _returnData(q)); } _end(id, msg, 'OK'); }, /** * Timeout detected * @method _timeout * @param id {string} the id of the request * @private */ _timeout = function(id) { var q = queues[id], sc; if (q.onTimeout) { sc = q.context || q; q.onTimeout.call(sc, _returnData(q)); } _end(id, 'timeout', 'timeout'); }, /** * Loads the next item for a given request * @method _next * @param id {string} the id of the request * @param loaded {string} the url that was just loaded, if any * @private */ _next = function(id, loaded) { var q = queues[id], msg, w, d, h, n, url, s; if (q.timer) { q.timer.cancel(); } if (q.aborted) { msg = "transaction " + id + " was aborted"; _fail(id, msg); return; } if (loaded) { q.url.shift(); if (q.varName) { q.varName.shift(); } } else { // This is the first pass: make sure the url is an array q.url = (L.isString(q.url)) ? [q.url] : q.url; if (q.varName) { q.varName = (L.isString(q.varName)) ? [q.varName] : q.varName; } } w = q.win; d = w.document; h = d.getElementsByTagName("head")[0]; if (q.url.length === 0) { _finish(id); return; } url = q.url[0]; // if the url is undefined, this is probably a trailing comma problem in IE if (!url) { q.url.shift(); return _next(id); } if (q.timeout) { q.timer = L.later(q.timeout, q, _timeout, id); } if (q.type === "script") { n = _scriptNode(url, w, q.attributes); } else { n = _linkNode(url, w, q.attributes); } // track this node's load progress _track(q.type, n, id, url, w, q.url.length); // add the node to the queue so we can return it to the user supplied callback q.nodes.push(n); // add it to the head or insert it before 'insertBefore' if (q.insertBefore) { s = _get(q.insertBefore, id); if (s) { s.parentNode.insertBefore(n, s); } } else { h.appendChild(n); } // FireFox does not support the onload event for link nodes, so there is // no way to make the css requests synchronous. This means that the css // rules in multiple files could be applied out of order in this browser // if a later request returns before an earlier one. Safari too. if ((ua.webkit || ua.gecko) && q.type === "css") { _next(id, url); } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (purging) { return; } purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param type {string} the type of node to insert * @param url {string} the url to load * @param opts the hash of options for this request * @private */ _queue = function(type, url, opts) { opts = opts || {}; var id = "q" + (qidx++), q, thresh = opts.purgethreshold || Y.Get.PURGE_THRESH; if (qidx % thresh === 0) { _autoPurge(); } queues[id] = Y.merge(opts, { tId: id, type: type, url: url, finished: false, nodes: [] }); q = queues[id]; q.win = q.win || Y.config.win; q.context = q.context || q; q.autopurge = ("autopurge" in q) ? q.autopurge : (type === "script") ? true : false; if (opts.charset) { q.attributes = q.attributes || {}; q.attributes.charset = opts.charset; } L.later(0, q, _next, id); return { tId: id }; }, /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _track * @param type {string} the type of node to track * @param n {HTMLElement} the node to track * @param id {string} the id of the request * @param url {string} the url that is being loaded * @param win {Window} the targeted window * @param qlength the number of remaining items in the queue, * including this one * @param trackfn {Function} function to execute when finished * the default is _next * @private */ _track = function(type, n, id, url, win, qlength, trackfn) { var f = trackfn || _next; // IE supports the readystatechange event for script and css nodes // Opera only for script nodes. Opera support onload for script // nodes, but this doesn't fire when there is a load failure. // The onreadystatechange appears to be a better way to respond // to both success and failure. if (ua.ie) { n.onreadystatechange = function() { var rs = this.readyState; if ("loaded" === rs || "complete" === rs) { n.onreadystatechange = null; f(id, url); } }; // webkit prior to 3.x is no longer supported } else if (ua.webkit) { if (type === "script") { // Safari 3.x supports the load event for script nodes (DOM2) n.addEventListener("load", function() { f(id, url); }); } // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link // nodes. } else { n.onload = function() { f(id, url); }; n.onerror = function(e) { _fail(id, e + ": " + url); }; } }; return { /** * The number of request required before an automatic purge. * property PURGE_THRESH * @static * @type int * @default 20 */ PURGE_THRESH: 20, /** * Called by the the helper for detecting script load in Safari * @method _finalize * @static * @param id {string} the transaction id * @private */ _finalize: function(id) { L.later(0, null, _finish, id); }, /** * Abort a transaction * @method abort * @static * @param o {string|object} Either the tId or the object returned from * script() or css() */ abort: function(o) { var id = (L.isString(o)) ? o : o.tId, q = queues[id]; if (q) { q.aborted = true; } }, /** * Fetches and inserts one or more script nodes into the head * of the current document or the document in a specified window. * * @method script * @static * @param url {string|string[]} the url or urls to the script(s) * @param opts {object} Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onTimeout</dt> * <dd> * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onEnd</dt> * <dd>a function that executes when the transaction finishes, regardless of the exit path</dd> * <dt>onFailure</dt> * <dd> * callback to execute when the script load operation fails * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted successfully</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove any nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>autopurge</dt> * <dd> * setting to true will let the utilities cleanup routine purge * the script once loaded * </dd> * <dt>purgethreshold</dt> * <dd> * The number of transaction before autopurge should be initiated * </dd> * <dt>data</dt> * <dd> * data that is supplied to the callback when the script(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling</dd> * </dl> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to the link tags</dd> * <dt>timeout</dt> * <dd>Number of milliseconds to wait before aborting and firing the timeout event</dd> * <pre> * &nbsp;&nbsp;Y.Get.script( * &nbsp;&nbsp;["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp;&nbsp;&nbsp;"http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], &#123; * &nbsp;&nbsp;&nbsp;&nbsp;onSuccess: function(o) &#123; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.log("won't cause error because Y is the context"); * &nbsp;&nbsp;&nbsp;&nbsp;&#125;, * &nbsp;&nbsp;&nbsp;&nbsp;onFailure: function(o) &#123; * &nbsp;&nbsp;&nbsp;&nbsp;&#125;, * &nbsp;&nbsp;&nbsp;&nbsp;onTimeout: function(o) &#123; * &nbsp;&nbsp;&nbsp;&nbsp;&#125;, * &nbsp;&nbsp;&nbsp;&nbsp;data: "foo", * &nbsp;&nbsp;&nbsp;&nbsp;timeout: 10000, // 10 second timeout * &nbsp;&nbsp;&nbsp;&nbsp;context: Y, // make the YUI instance * &nbsp;&nbsp;&nbsp;&nbsp;// win: otherframe // target another window/frame * &nbsp;&nbsp;&nbsp;&nbsp;autopurge: true // allow the utility to choose when to remove the nodes * &nbsp;&nbsp;&nbsp;&nbsp;purgetheshold: 1 // purge previous transaction before next transaction * &nbsp;&nbsp;&#125;); * </pre> * @return {tId: string} an object containing info about the transaction */ script: function(url, opts) { return _queue("script", url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param url {string} the url or urls to the css file(s) * @param opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: * <dl>win</dl> * <dd>the window the link nodes(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>data</dt> * <dd> * data that is supplied to the callbacks when the nodes(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling</dd> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to the link tags</dd> * </dl> * <pre> * Y.Get.css("http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css"); * </pre> * <pre> * &nbsp;&nbsp;Y.Get.css( * &nbsp;&nbsp;["http://yui.yahooapis.com/2.3.1/build/menu/assets/skins/sam/menu.css", * &nbsp;&nbsp;&nbsp;&nbsp;insertBefore: 'custom-styles' // nodes will be inserted before the specified node * &nbsp;&nbsp;&#125;); * </pre> * @return {tId: string} an object containing info about the transaction */ css: function(url, opts) { return _queue("css", url, opts); } }; }(); })(); }, '@VERSION@' ); YUI.add('loader', function(Y) { (function() { /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * @module yui * @submodule loader */ /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * @class Loader * @constructor * @param o an optional set of configuration options. Valid options: * <ul> * <li>base: * The base dir</li> * <li>secureBase: * The secure base dir (not implemented)</li> * <li>comboBase: * The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li> * <li>root: * The root path to prepend to module names for the combo service. Ex: 2.5.2/build/</li> * <li>filter: * * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * </li> * <li>filters: per-component filter specification. If specified for a given component, this overrides the filter config</li> * <li>combine: * Use the YUI combo service to reduce the number of http connections required to load your dependencies</li> * <li>ignore: * A list of modules that should never be dynamically loaded</li> * <li>force: * A list of modules that should always be loaded when required, even if already present on the page</li> * <li>insertBefore: * Node or id for a node that should be used as the insertion point for new nodes</li> * <li>charset: * charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes)</li> * <li>jsAttributes: object literal containing attributes to add to script nodes</li> * <li>cssAttributes: object literal containing attributes to add to link nodes</li> * <li>timeout: * number of milliseconds before a timeout occurs when dynamically loading nodes. in not set, there is no timeout</li> * <li>context: * execution context for all callbacks</li> * <li>onSuccess: * callback for the 'success' event</li> * <li>onFailure: callback for the 'failure' event</li> * <li>onCSS: callback for the 'CSSComplete' event. When loading YUI components with CSS * the CSS is loaded first, then the script. This provides a moment you can tie into to improve * the presentation of the page while the script is loading.</li> * <li>onTimeout: * callback for the 'timeout' event</li> * <li>onProgress: * callback executed each time a script or css file is loaded</li> * <li>modules: * A list of module definitions. See Loader.addModule for the supported module metadata</li> * </ul> */ // @TODO backed out the custom event changes so that the event system // isn't required in the seed build. If needed, we may want to // add them back if the event system is detected. /* * Executed when the loader successfully completes an insert operation * This can be subscribed to normally, or a listener can be passed * as an onSuccess config option. * @event success */ /* * Executed when the loader fails to complete an insert operation. * This can be subscribed to normally, or a listener can be passed * as an onFailure config option. * * @event failure */ /* * Executed when a Get operation times out. * This can be subscribed to normally, or a listener can be passed * as an onTimeout config option. * * @event timeout */ // http://yui.yahooapis.com/combo?2.5.2/build/yahoo/yahoo-min.js&2.5.2/build/dom/dom-min.js&2.5.2/build/event/event-min.js&2.5.2/build/autocomplete/autocomplete-min.js" /** * Global loader queue * @property _loaderQueue * @type Queue * @private * @for YUI.Env */ YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Y.Queue(); var GLOBAL_ENV = YUI.Env, GLOBAL_LOADED, BASE = 'base', CSS = 'css', JS = 'js', CSSRESET = 'cssreset', CSSFONTS = 'cssfonts', CSSGRIDS = 'cssgrids', CSSBASE = 'cssbase', CSS_AFTER = [CSSRESET, CSSFONTS, CSSGRIDS, 'cssreset-context', 'cssfonts-context', 'cssgrids-context'], YUI_CSS = ['reset', 'fonts', 'grids', BASE], VERSION = Y.version, ROOT = VERSION + '/build/', CONTEXT = '-context', ANIMBASE = 'anim-base', DDDRAG = 'dd-drag', DOM = 'dom', DATASCHEMABASE = 'dataschema-base', DATASOURCELOCAL = 'datasource-local', DOMBASE = 'dom-base', DOMSTYLE = 'dom-style', DUMP = 'dump', GET = 'get', EVENT = 'event', EVENTCUSTOM = 'event-custom', IOBASE = 'io-base', NODE = 'node', NODEBASE = 'node-base', OOP = 'oop', SELECTOR = 'selector', SUBSTITUTE = 'substitute', WIDGET = 'widget', WIDGETPOSITION = 'widget-position', YUIBASE = 'yui-base', PLUGIN = 'plugin', META = { version: VERSION, root: ROOT, base: 'http://yui.yahooapis.com/' + ROOT, comboBase: 'http://yui.yahooapis.com/combo?', skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: CSS_AFTER //rollup: 3 }, modules: { dom: { requires: [OOP], submodules: { 'dom-base': { requires: [OOP] }, 'dom-style': { requires: [DOMBASE] }, 'dom-screen': { requires: [DOMBASE, DOMSTYLE] }, selector: { requires: [DOMBASE] }, 'selector-native': { requires: [DOMBASE] } }, plugins: { 'selector-css3': { requires: [SELECTOR] } } }, node: { requires: [DOM, BASE], expound: EVENT, submodules: { 'node-base': { requires: [DOMBASE, BASE, SELECTOR] }, 'node-style': { requires: [DOMSTYLE, NODEBASE] }, 'node-screen': { requires: ['dom-screen', NODEBASE] } }, plugins: { 'node-event-simulate': { requires: [NODEBASE, 'event-simulate'] } } }, anim: { requires: [BASE, NODE], submodules: { 'anim-base': { requires: [BASE, 'node-style'] }, 'anim-color': { requires: [ANIMBASE] }, 'anim-curve': { requires: ['anim-xy'] }, 'anim-easing': { requires: [ANIMBASE] }, 'anim-scroll': { requires: [ANIMBASE] }, 'anim-xy': { requires: [ANIMBASE, 'node-screen'] }, 'anim-node-plugin': { requires: [NODE, ANIMBASE] } } }, attribute: { requires: [EVENTCUSTOM] }, base: { submodules: { 'base-base': { requires: ['attribute'] }, 'base-build': { requires: ['base-base'] } } }, cache: { requires: [PLUGIN] }, compat: { requires: [NODE, DUMP, SUBSTITUTE] }, classnamemanager: { requires: [YUIBASE] }, collection: { requires: [OOP] }, console: { requires: [WIDGET, SUBSTITUTE], skinnable: true }, cookie: { requires: [YUIBASE] }, dataschema:{ submodules: { 'dataschema-base': { requires: [BASE] }, 'dataschema-array': { requires: [DATASCHEMABASE] }, 'dataschema-json': { requires: [DATASCHEMABASE] }, 'dataschema-text': { requires: [DATASCHEMABASE] }, 'dataschema-xml': { requires: [DATASCHEMABASE] } } }, datasource:{ submodules: { 'datasource-local': { requires: [BASE] }, 'datasource-arrayschema': { requires: [DATASOURCELOCAL, PLUGIN, 'dataschema-array'] }, 'datasource-cache': { requires: [DATASOURCELOCAL, 'cache'] }, 'datasource-function': { requires: [DATASOURCELOCAL] }, 'datasource-jsonschema': { requires: [DATASOURCELOCAL, PLUGIN, 'dataschema-json'] }, 'datasource-polling': { requires: [DATASOURCELOCAL] }, 'datasource-scriptnode': { requires: [DATASOURCELOCAL, GET] }, 'datasource-textschema': { requires: [DATASOURCELOCAL, PLUGIN, 'dataschema-text'] }, 'datasource-xhr': { requires: [DATASOURCELOCAL, IOBASE] }, 'datasource-xmlschema': { requires: [DATASOURCELOCAL, PLUGIN, 'dataschema-xml'] } } }, datatype:{ submodules: { 'datatype-date': { requires: [YUIBASE] }, 'datatype-number': { requires: [YUIBASE] }, 'datatype-xml': { requires: [YUIBASE] } } }, dd:{ submodules: { 'dd-ddm-base': { requires: [NODE, BASE] }, 'dd-ddm':{ requires: ['dd-ddm-base'] }, 'dd-ddm-drop':{ requires: ['dd-ddm'] }, 'dd-drag':{ requires: ['dd-ddm-base'] }, 'dd-drop':{ requires: ['dd-ddm-drop'] }, 'dd-proxy':{ requires: [DDDRAG] }, 'dd-constrain':{ requires: [DDDRAG] }, 'dd-scroll':{ requires: [DDDRAG] }, 'dd-plugin':{ requires: [DDDRAG], optional: ['dd-constrain', 'dd-proxy'] }, 'dd-drop-plugin':{ requires: ['dd-drop'] } } }, dump: { requires: [YUIBASE] }, event: { requires: [EVENTCUSTOM, NODE] }, 'event-custom': { requires: [OOP] }, 'event-simulate': { requires: [EVENT] }, 'node-focusmanager': { requires: [NODE, PLUGIN] }, get: { requires: [YUIBASE] }, history: { requires: [NODE] }, imageloader: { requires: [NODE] }, io:{ submodules: { 'io-base': { requires: [EVENTCUSTOM] }, 'io-xdr': { requires: [IOBASE] }, 'io-form': { requires: [IOBASE, NODE] }, 'io-upload-iframe': { requires: [IOBASE, NODE] }, 'io-queue': { requires: [IOBASE, 'queue-promote'] } } }, json: { submodules: { 'json-parse': { requires: [YUIBASE] }, 'json-stringify': { requires: [YUIBASE] } } }, loader: { requires: [GET] }, 'node-menunav': { requires: [NODE, 'classnamemanager', PLUGIN, 'node-focusmanager'], skinnable: true }, oop: { requires: [YUIBASE] }, overlay: { requires: [WIDGET, WIDGETPOSITION, 'widget-position-ext', 'widget-stack', 'widget-stdmod'], skinnable: true }, plugin: { requires: [BASE] }, profiler: { requires: [YUIBASE] }, queue: { submodules: { 'queue-base': { requires: [YUIBASE] }, 'queue-run': { requires: ['queue-base', EVENTCUSTOM] } }, plugins: { 'queue-promote': { } } }, slider: { requires: [WIDGET, 'dd-constrain'], skinnable: true }, stylesheet: { requires: [YUIBASE] }, substitute: { optional: [DUMP] }, widget: { requires: [BASE, NODE, 'classnamemanager'], plugins: { 'widget-position': { }, 'widget-position-ext': { requires: [WIDGETPOSITION] }, 'widget-stack': { skinnable: true }, 'widget-stdmod': { } }, skinnable: true }, yui: { supersedes: [YUIBASE, GET, 'loader', 'queue-base'] }, 'yui-base': { }, test: { requires: [SUBSTITUTE, NODE, 'json', 'event-simulate'] } } }, _path = function(dir, file, type) { return dir + '/' + file + '-min.' + (type || CSS); }, _queue = YUI.Env._loaderQueue, mods = META.modules, i, bname, mname, contextname, L = Y.Lang, PROV = "_provides", SUPER = "_supersedes"; // Create the metadata for both the regular and context-aware // versions of the YUI CSS foundation. for (i=0; i<YUI_CSS.length; i=i+1) { bname = YUI_CSS[i]; mname = CSS + bname; mods[mname] = { type: CSS, path: _path(mname, bname) }; // define -context module contextname = mname + CONTEXT; bname = bname + CONTEXT; mods[contextname] = { type: CSS, path: _path(mname, bname) }; if (mname == CSSGRIDS) { mods[mname].requires = [CSSFONTS]; mods[mname].optional = [CSSRESET]; mods[contextname].requires = [CSSFONTS + CONTEXT]; mods[contextname].optional = [CSSRESET + CONTEXT]; } else if (mname == CSSBASE) { mods[mname].after = CSS_AFTER; mods[contextname].after = CSS_AFTER; } } Y.Env.meta = META; GLOBAL_LOADED = GLOBAL_ENV._loaded; Y.Loader = function(o) { /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ this._internalCallback = null; /** * Use the YUI environment listener to detect script load. This * is only switched on for Safari 2.x and below. * @property _useYahooListener * @private */ this._useYahooListener = false; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ this.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ this.onFailure = null; /** * Callback for the 'CSSComplete' event. When loading YUI components with CSS * the CSS is loaded first, then the script. This provides a moment you can tie into to improve * the presentation of the page while the script is loading. * @method onCSS * @type function */ this.onCSS = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ this.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ this.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ this.context = Y; /** * Data that is passed to all callbacks * @property data */ this.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ this.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated, use cssAttributes or jsAttributes */ this.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ this.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ this.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ this.base = Y.Env.meta.base; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ this.comboBase = Y.Env.meta.comboBase; /** * If configured, YUI JS resources will use the combo * handler * @property combine * @type boolean * @default true if a base dir isn't in the config */ this.combine = (!(BASE in o)); /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ this.ignoreRegistered = false; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ this.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, this value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ this.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ this.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ this.force = null; /** * Should we allow rollups * @property allowRollup * @type boolean * @default true */ this.allowRollup = true; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * @property filter * @type string|{searchExp: string, replaceStr: string} */ this.filter = null; /** * per-component filter specification. If specified for a given component, this * overrides the filter config. * @property filters * @type object */ this.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ this.required = {}; /** * The library metadata * @property moduleInfo */ // this.moduleInfo = Y.merge(Y.Env.meta.moduleInfo); this.moduleInfo = {}; /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * <code> * skin: { * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // The name of the rollup css file for the skin * path: 'skin.css', * * // The number of skinnable components requested that are * // required before using the rollup file rather than the * // individual component css files * rollup: 3, * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * </code> * @property skin */ this.skin = Y.merge(Y.Env.meta.skin); var defaults = Y.Env.meta.modules, i; for (i in defaults) { if (defaults.hasOwnProperty(i)) { this._internal = true; this.addModule(defaults[i], i); this._internal = false; } } /** * List of rollup files found in the library metadata * @property rollups */ this.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ this.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ this.sorted = []; /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @propery loaded * @type {string: boolean} */ this.loaded = GLOBAL_LOADED[VERSION]; /** * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ this.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ this.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ this.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ this.skipped = {}; // Y.on('yui:load', this.loadNext, this); this._config(o); }; Y.Loader.prototype = { FILTER_DEFS: { RAW: { 'searchExp': "-min\\.js", 'replaceStr': ".js" }, DEBUG: { 'searchExp': "-min\\.js", 'replaceStr': "-debug.js" } }, SKIN_PREFIX: "skin-", _config: function(o) { var i, j, val, f; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; if (i == 'require') { this.require(val); } else if (i == 'modules') { // add a hash of module definitions for (j in val) { if (val.hasOwnProperty(j)) { this.addModule(val[j], j); } } } else { this[i] = val; } } } } // fix filter f = this.filter; if (L.isString(f)) { f = f.toUpperCase(); this.filterName = f; this.filter = this.FILTER_DEFS[f]; } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param skin {string} the name of the skin * @param mod {string} optional: the name of a module to skin * @return {string} the full skin module name */ formatSkin: function(skin, mod) { var s = this.SKIN_PREFIX + skin; if (mod) { s = s + "-" + mod; } return s; }, /** * Reverses <code>formatSkin</code>, providing the skin name and * module name if the string matches the pattern for skins. * @method parseSkin * @param mod {string} the module name to parse * @return {skin: string, module: string} the parsed skin name * and module name, or null if the supplied string does not match * the skin pattern */ parseSkin: function(mod) { if (mod.indexOf(this.SKIN_PREFIX) === 0) { var a = mod.split("-"); return {skin: a[1], module: a[2]}; } return null; }, /** * Adds the skin def to the module info * @method _addSkin * @param skin {string} the name of the skin * @param mod {string} the name of the module * @param parent {string} parent module if this is a skin of a * submodule or plugin * @return {string} the module name for the skin * @private */ _addSkin: function(skin, mod, parent) { var name = this.formatSkin(skin), info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext, mdef, pkg; /* // Add a module definition for the skin rollup css if (!info[name]) { this.addModule({ 'name': name, 'type': 'css', 'path': sinf.base + skin + '/' + sinf.path, //'supersedes': '*', 'after': sinf.after, 'rollup': sinf.rollup, 'ext': ext }); } */ // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { mdef = info[mod]; pkg = mdef.pkg || mod; this.addModule({ 'name': name, 'type': 'css', 'after': sinf.after, 'path': (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', 'ext': ext }); } } return name; }, /** Add a new module to the component metadata. * <dl> * <dt>name:</dt> <dd>required, the component name</dd> * <dt>type:</dt> <dd>required, the component type (js or css)</dd> * <dt>path:</dt> <dd>required, the path to the script from "base"</dd> * <dt>requires:</dt> <dd>array of modules required by this component</dd> * <dt>optional:</dt> <dd>array of optional modules for this component</dd> * <dt>supersedes:</dt> <dd>array of the modules this component replaces</dd> * <dt>after:</dt> <dd>array of modules the components which, if present, should be sorted above this one</dd> * <dt>rollup:</dt> <dd>the number of superseded modules required for automatic rollup</dd> * <dt>fullpath:</dt> <dd>If fullpath is specified, this is used instead of the configured base + path</dd> * <dt>skinnable:</dt> <dd>flag to determine if skin assets should automatically be pulled in</dd> * <dt>submodules:</dt> <dd>a has of submodules</dd> * </dl> * @method addModule * @param o An object containing the module data * @param name the module name (optional), required if not in the module data * @return {boolean} true if the module was added, false if * the object passed in did not provide all required attributes */ addModule: function(o, name) { name = name || o.name; o.name = name; if (!o || !o.name) { return false; } if (!o.type) { o.type = JS; } if (!o.path && !o.fullpath) { // o.path = name + "/" + name + "-min." + o.type; o.path = _path(name, name, o.type); } o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; o.requires = o.requires || []; this.moduleInfo[name] = o; // Handle submodule logic var subs = o.submodules, i, l, sup, s, smod, plugins, plug; if (subs) { sup = []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = _path(name, i, o.type); this.addModule(s, i); sup.push(i); if (o.skinnable) { smod = this._addSkin(this.skin.defaultSkin, i, name); sup.push(smod.name); } l++; } } o.supersedes = sup; o.rollup = Math.min(l-1, 4); } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.path = _path(name, i, o.type); plug.requires = plug.requires || []; plug.requires.push(name); this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } this.dirty = true; return o; }, /** * Add a requirement for one or more module * @method require * @param what {string[] | string*} the modules to load */ require: function(what) { var a = (typeof what === "string") ? arguments : what; this.dirty = true; Y.mix(this.required, Y.Array.hash(a)); }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param mod The module definition from moduleInfo */ getRequires: function(mod) { if (!mod) { return []; } if (!this.dirty && mod.expanded) { return mod.expanded; } var i, d=[], r=mod.requires, o=mod.optional, info=this.moduleInfo, m, j, add; for (i=0; i<r.length; i=i+1) { d.push(r[i]); m = this.getModule(r[i]); add = this.getRequires(m); for (j=0;j<add.length;j=j+1) { d.push(add[j]); } } // get the requirements from superseded modules, if any r=mod.supersedes; if (r) { for (i=0; i<r.length; i=i+1) { d.push(r[i]); m = this.getModule(r[i]); add = this.getRequires(m); for (j=0;j<add.length;j=j+1) { d.push(add[j]); } } } if (o && this.loadOptional) { for (i=0; i<o.length; i=i+1) { d.push(o[i]); add = this.getRequires(info[o[i]]); for (j=0;j<add.length;j=j+1) { d.push(add[j]); } } } mod.expanded = Y.Object.keys(Y.Array.hash(d)); return mod.expanded; }, /** * Returns an object literal of the modules the supplied module satisfies * @method getProvides * @param name{string} The name of the module * @param notMe {string} don't add this module name, only include superseded modules * @return what this module provides */ getProvides: function(name, notMe) { var addMe = !(notMe), ckey = (addMe) ? PROV : SUPER, m = this.getModule(name), o = {}, s, done, me, i, // use worker to break cycles add = function(mm) { if (!done[mm]) { done[mm] = true; // we always want the return value normal behavior // (provides) for superseded modules. Y.mix(o, me.getProvides(mm)); } // else { // } }; if (!m) { return o; } if (m[ckey]) { return m[ckey]; } s = m.supersedes; done = {}; me = this; // calculate superseded modules if (s) { for (i=0; i<s.length; i=i+1) { add(s[i]); } } // supersedes cache m[SUPER] = o; // provides cache m[PROV] = Y.merge(o); m[PROV][name] = true; return m[ckey]; }, /** * Calculates the dependency tree, the result is stored in the sorted * property * @method calculate * @param o optional options object */ calculate: function(o) { if (o || this.dirty) { this._config(o); this._setup(); this._explode(); if (this.allowRollup && !this.combine) { this._rollup(); } this._reduce(); this._sort(); this.dirty = false; } }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, o, l, smod; // Create skin modules for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m && m.skinnable) { o = this.skin.overrides; if (o && o[name]) { for (i=0; i<o[name].length; i=i+1) { smod = this._addSkin(o[name][i], name); } } else { smod = this._addSkin(this.skin.defaultSkin, name); } m.requires.push(smod); } } } l = Y.merge(this.inserted); // shallow clone // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { // OU.appendArray(l, this.ignore); Y.mix(l, Y.Array.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i=0; i<this.force.length; i=i+1) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); // this.loaded = l; }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { var r=this.required, i, mod, req, me = this, f = function(name) { mod = me.getModule(name); var expound = mod && mod.expound; if (mod) { if (expound) { r[expound] = me.getModule(expound); req = me.getRequires(r[expound]); Y.mix(r, Y.Array.hash(req)); } req = me.getRequires(mod); Y.mix(r, Y.Array.hash(req)); } }; for (i in r) { if (r.hasOwnProperty(i)) { f(i); } } }, getModule: function(name) { var m = this.moduleInfo[name]; // create the default module // if (!m) { // m = this.addModule({ext: false}, name); // } return m; }, /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate() * @method _rollup * @private */ _rollup: function() { var i, j, m, s, rollups={}, r=this.required, roll, info = this.moduleInfo, rolled, c; // find and cache rollup modules if (this.dirty || !this.rollups) { for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { rollups[i] = m; } } } this.rollups = rollups; } // make as many passes as needed to pick up rollup rollups for (;;) { rolled = false; // go through the rollup candidates for (i in rollups) { if (rollups.hasOwnProperty(i)) { // there can be only one if (!r[i] && !this.loaded[i]) { m = this.getModule(i); s = m.supersedes || []; roll = false; // @TODO remove continue if (!m.rollup) { continue; } c = 0; // check the threshold for (j=0;j<s.length;j=j+1) { // if the superseded module is loaded, we can't load the rollup // if (this.loaded[s[j]] && (!_Y.dupsAllowed[s[j]])) { if (this.loaded[s[j]]) { roll = false; break; // increment the counter if this module is required. if we are // beyond the rollup threshold, we will use the rollup module } else if (r[s[j]]) { c++; roll = (c >= m.rollup); if (roll) { break; } } } if (roll) { // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @private */ _reduce: function() { var i, j, s, m, r=this.required; for (i in r) { if (r.hasOwnProperty(i)) { // remove if already loaded if (i in this.loaded && !this.ignoreRegistered) { delete r[i]; // remove anything this module supersedes } else { m = this.getModule(i); s = m && m.supersedes; if (s) { for (j=0; j<s.length; j=j+1) { if (s[j] in r) { delete r[s[j]]; } } } } } } }, _attach: function() { // this is the full list of items the YUI needs attached, // which is needed if some dependencies are already on // the page without their dependencies. if (this.attaching) { Y._attach(this.attaching); } else { Y._attach(this.sorted); } // this._pushEvents(); }, _finish: function() { _queue.running = false; this._continue(); }, _onSuccess: function() { this._attach(); var skipped = this.skipped, i, f; for (i in skipped) { if (skipped.hasOwnProperty(i)) { delete this.inserted[i]; } } this.skipped = {}; f = this.onSuccess; if (f) { f.call(this.context, { msg: 'success', data: this.data, success: true }); } this._finish(); }, _onFailure: function(o) { this._attach(); var f = this.onFailure; if (f) { f.call(this.context, { msg: 'failure: ' + o.msg, data: this.data, success: false }); } this._finish(); }, _onTimeout: function() { this._attach(); var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false }); } this._finish(); }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { // create an indexed list var s=Y.Object.keys(this.required), info=this.moduleInfo, loaded=this.loaded, p, l, a, b, j, k, moved, // returns true if b is not loaded, and is required // directly or by means of modules it supersedes. requires = function(aa, bb) { var mm = info[aa], ii, rr, after, other, ss; if (loaded[bb] || !mm) { return false; } rr = mm.expanded; after = mm.after; other = info[bb]; // check if this module requires the other directly if (rr && Y.Array.indexOf(rr, bb) > -1) { return true; } // check if this module should be sorted after the other if (after && Y.Array.indexOf(after, bb) > -1) { return true; } // check if this module requires one the other supersedes ss = info[bb] && info[bb].supersedes; if (ss) { for (ii=0; ii<ss.length; ii=ii+1) { if (requires(aa, ss[ii])) { return true; } } } // external css files should be sorted below yui css if (mm.ext && mm.type == CSS && !other.ext && other.type == CSS) { return true; } return false; }; // pointer to the first unsorted item p = 0; // keep going until we make a pass without moving anything for (;;) { l = s.length; moved = false; // start the loop after items that are already sorted for (j=p; j<l; j=j+1) { // check the next module on the list to see if its // dependencies have been met a = s[j]; // check everything below current item and move if we // find a requirement for the current item for (k=j+1; k<l; k=k+1) { if (requires(a, s[k])) { // extract the dependency so we can move it up b = s.splice(k, 1); // insert the dependency above the item that // requires it s.splice(j, 0, b[0]); moved = true; break; } } // jump out of loop if we moved something if (moved) { break; // this item is sorted, move our pointer and keep going } else { p = p + 1; } } // when we make it here and moved is false, we are // finished sorting if (!moved) { break; } } this.sorted = s; }, _insert: function(source, o, type) { // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list this.calculate(o); if (!type) { var self = this; this._internalCallback = function() { var f = self.onCSS; if (f) { f.call(self.context, Y); } self._internalCallback = null; self._insert(null, null, JS); }; // _queue.running = false; this._insert(null, null, CSS); return; } // set a flag to indicate the load has started this._loading = true; // flag to indicate we are done with the combo service // and any additional files will need to be loaded // individually this._combineComplete = {}; // keep the loadType (js, css or undefined) cached this.loadType = type; // start the load this.loadNext(); }, _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * <code>type</code> can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param o optional options object * @param type {string} the type of dependency to insert */ insert: function(o, type) { var self = this, copy; copy = Y.merge(this, true); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @param mname {string} optional the name of the module that has * been loaded (which is usually why it is time to load the next * one) */ loadNext: function(mname) { // It is possible that this function is executed due to something // else one the page loading a YUI module. Only react when we // are actively loading something if (!this._loading) { return; } var s, len, i, m, url, self=this, type=this.loadType, fn, msg, attr, callback=function(o) { this._combineComplete[type] = true; var c=this._combining, len=c.length, i; for (i=0; i<len; i=i+1) { this.inserted[c[i]] = true; } this.loadNext(o.data); }, onsuccess=function(o) { self.loadNext(o.data); }; // @TODO this will need to handle the two phase insert when // CSS support is added if (this.combine && (!this._combineComplete[type])) { this._combining = []; s=this.sorted; len=s.length; url=this.comboBase; for (i=0; i<len; i=i+1) { m = this.getModule(s[i]); // @TODO we can't combine CSS yet until we deliver files with absolute paths to the assets // Do not try to combine non-yui JS if (m && m.type === this.loadType && !m.ext) { url += this.root + m.path; if (i < len-1) { url += '&'; } this._combining.push(s[i]); } } if (this._combining.length) { if (m.type === CSS) { fn = Y.Get.css; attr = this.cssAttributes; } else { fn = Y.Get.script; attr = this.jsAttributes; } // @TODO get rid of the redundant Get code fn(this._filter(url), { data: this._loading, onSuccess: callback, onFailure: this._onFailure, onTimeout: this._onTimeout, insertBefore: this.insertBefore, charset: this.charset, attributes: attr, timeout: this.timeout, context: self }); return; } else { this._combineComplete[type] = true; } } if (mname) { // if the module that was just loaded isn't what we were expecting, // continue to wait if (mname !== this._loading) { return; } // The global handler that is called when each module is loaded // will pass that module name to this function. Storing this // data to avoid loading the same module multiple times this.inserted[mname] = true; this.loaded[mname] = true; if (this.onProgress) { this.onProgress.call(this.context, { name: mname, data: this.data }); } } s=this.sorted; len=s.length; for (i=0; i<len; i=i+1) { // this.inserted keeps track of what the loader has loaded. // move on if this item is done. if (s[i] in this.inserted) { continue; } // Because rollups will cause multiple load notifications // from Y, loadNext may be called multiple times for // the same module when loading a rollup. We can safely // skip the subsequent requests if (s[i] === this._loading) { return; } // log("inserting " + s[i]); m = this.getModule(s[i]); if (!m) { msg = "Undefined module " + s[i] + " skipped"; this.inserted[s[i]] = true; this.skipped[s[i]] = true; continue; } // The load type is stored to offer the possibility to load // the css separately from the script. if (!type || type === m.type) { this._loading = s[i]; if (m.type === CSS) { fn = Y.Get.css; attr = this.cssAttributes; } else { fn = Y.Get.script; attr = this.jsAttributes; } url = (m.fullpath) ? this._filter(m.fullpath, s[i]) : this._url(m.path, s[i]); fn(url, { data: s[i], onSuccess: onsuccess, insertBefore: this.insertBefore, charset: this.charset, attributes: attr, onFailure: this._onFailure, onTimeout: this._onTimeout, timeout: this.timeout, context: self }); return; } } // we are finished this._loading = null; fn = this._internalCallback; // internal callback for loading css first if (fn) { this._internalCallback = null; fn.call(this); // } else if (this.onSuccess) { } else { // call Y.use passing this instance. Y will use the sorted // dependency list. this._onSuccess(); } }, /** * Apply filter defined for this instance to a url/path * method _filter * @param u {string} the string to filter * @param name {string} the name of the module, if we are processing * a single module as opposed to a combined url * @return {string} the filtered string * @private */ _filter: function(u, name) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name]; if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * method _url * @param path {string} the path fragment * @return {string} the full url * @private */ _url: function(path, name) { return this._filter((this.base || "") + path, name); } }; })(); }, '@VERSION@' ,{requires:['queue-base']}); YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','queue-base','get','loader']});
tests/layouts/CoreLayout.spec.js
kubism/kubism.github.io
import React from 'react' import TestUtils from 'react-addons-test-utils' import CoreLayout from 'layouts/CoreLayout' function shallowRender (component) { const renderer = TestUtils.createRenderer() renderer.render(component) return renderer.getRenderOutput() } function shallowRenderWithProps (props = {}) { return shallowRender(<CoreLayout {...props} />) } describe('(Layout) Core', function () { let _component let _props let _child beforeEach(function () { _child = <h1 className='child'>Child</h1> _props = { children: _child, } _component = shallowRenderWithProps(_props) }) it('Should render as a <div>.', function () { expect(_component.type).to.equal('div') }) })
src/svg-icons/editor/pie-chart.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorPieChart = (props) => ( <SvgIcon {...props}> <path d="M11 2v20c-5.07-.5-9-4.79-9-10s3.93-9.5 9-10zm2.03 0v8.99H22c-.47-4.74-4.24-8.52-8.97-8.99zm0 11.01V22c4.74-.47 8.5-4.25 8.97-8.99h-8.97z"/> </SvgIcon> ); EditorPieChart = pure(EditorPieChart); EditorPieChart.displayName = 'EditorPieChart'; EditorPieChart.muiName = 'SvgIcon'; export default EditorPieChart;
src/notebook/components/transforms/text.js
0u812/nteract
/* @flow */ import React from 'react'; import Ansi from 'ansi-to-react'; type Props = { data: string, } export default class TextDisplay extends React.Component { props: Props; shouldComponentUpdate(): boolean { return true; } render(): ?React.Element<any> { return <Ansi>{this.props.data}</Ansi>; } }
ajax/libs/react-bootstrap-table/0.5.4/react-bootstrap-table.min.js
sashberd/cdnjs
!function e(t,o,n){function r(s,l){if(!o[s]){if(!t[s]){var i="function"==typeof require&&require;if(!l&&i)return i(s,!0);if(a)return a(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=o[s]={exports:{}};t[s][0].call(u.exports,function(e){var o=t[s][1][e];return r(o?o:e)},u,u.exports,e,t,o,n)}return o[s].exports}for(var a="function"==typeof require&&require,s=0;s<n.length;s++)r(n[s]);return r}({"./src/index.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=n(e("./BootstrapTable")),a=n(e("./TableHeaderColumn"));t.exports={BootstrapTable:r,TableHeaderColumn:a}},{"./BootstrapTable":"/home/allen/workspace/react-bootstrap-table/src/BootstrapTable.js","./TableHeaderColumn":"/home/allen/workspace/react-bootstrap-table/src/TableHeaderColumn.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js":[function(e,t,o){function n(){if(!l){l=!0;for(var e,t=s.length;t;){e=s,s=[];for(var o=-1;++o<t;)e[o]();t=s.length}l=!1}}function r(){}var a=t.exports={},s=[],l=!1;a.nextTick=function(e){s.push(e),l||setTimeout(n,0)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=r,a.addListener=r,a.once=r,a.off=r,a.removeListener=r,a.removeAllListeners=r,a.emit=r,a.binding=function(e){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(e){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/classnames/index.js":[function(e,t,o){function n(){for(var e,t="",o=0;o<arguments.length;o++)if(e=arguments[o])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+n.apply(null,e);else if("object"==typeof e)for(var r in e)e.hasOwnProperty(r)&&e[r]&&(t+=" "+r);return t.substr(1)}"undefined"!=typeof t&&t.exports&&(t.exports=n)},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/AutoFocusMixin.js":[function(e,t,o){"use strict";var n=e("./focusNode"),r={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};t.exports=r},{"./focusNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/focusNode.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/BeforeInputEventPlugin.js":[function(e,t,o){"use strict";function n(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function a(e){switch(e){case j.topCompositionStart:return D.compositionStart;case j.topCompositionEnd:return D.compositionEnd;case j.topCompositionUpdate:return D.compositionUpdate}}function s(e,t){return e===j.topKeyDown&&t.keyCode===g}function l(e,t){switch(e){case j.topKeyUp:return-1!==y.indexOf(t.keyCode);case j.topKeyDown:return t.keyCode!==g;case j.topKeyPress:case j.topMouseDown:case j.topBlur:return!0;default:return!1}}function i(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function c(e,t,o,n){var r,c;if(w?r=a(e):P?l(e,n)&&(r=D.compositionEnd):s(e,n)&&(r=D.compositionStart),!r)return null;k&&(P||r!==D.compositionStart?r===D.compositionEnd&&P&&(c=P.getData()):P=f.getPooled(t));var u=v.getPooled(r,o,n);if(c)u.data=c;else{var p=i(n);null!==p&&(u.data=p)}return b.accumulateTwoPhaseDispatches(u),u}function u(e,t){switch(e){case j.topCompositionEnd:return i(t);case j.topKeyPress:var o=t.which;return o!==N?null:(M=!0,O);case j.topTextInput:var n=t.data;return n===O&&M?null:n;default:return null}}function p(e,t){if(P){if(e===j.topCompositionEnd||l(e,t)){var o=P.getData();return f.release(P),P=null,o}return null}switch(e){case j.topPaste:return null;case j.topKeyPress:return t.which&&!r(t)?String.fromCharCode(t.which):null;case j.topCompositionEnd:return k?null:t.data;default:return null}}function d(e,t,o,n){var r;if(r=R?u(e,n):p(e,n),!r)return null;var a=E.getPooled(D.beforeInput,o,n);return a.data=r,b.accumulateTwoPhaseDispatches(a),a}var m=e("./EventConstants"),b=e("./EventPropagators"),h=e("./ExecutionEnvironment"),f=e("./FallbackCompositionState"),v=e("./SyntheticCompositionEvent"),E=e("./SyntheticInputEvent"),_=e("./keyOf"),y=[9,13,27,32],g=229,w=h.canUseDOM&&"CompositionEvent"in window,C=null;h.canUseDOM&&"documentMode"in document&&(C=document.documentMode);var R=h.canUseDOM&&"TextEvent"in window&&!C&&!n(),k=h.canUseDOM&&(!w||C&&C>8&&11>=C),N=32,O=String.fromCharCode(N),j=m.topLevelTypes,D={beforeInput:{phasedRegistrationNames:{bubbled:_({onBeforeInput:null}),captured:_({onBeforeInputCapture:null})},dependencies:[j.topCompositionEnd,j.topKeyPress,j.topTextInput,j.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:_({onCompositionEnd:null}),captured:_({onCompositionEndCapture:null})},dependencies:[j.topBlur,j.topCompositionEnd,j.topKeyDown,j.topKeyPress,j.topKeyUp,j.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:_({onCompositionStart:null}),captured:_({onCompositionStartCapture:null})},dependencies:[j.topBlur,j.topCompositionStart,j.topKeyDown,j.topKeyPress,j.topKeyUp,j.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:_({onCompositionUpdate:null}),captured:_({onCompositionUpdateCapture:null})},dependencies:[j.topBlur,j.topCompositionUpdate,j.topKeyDown,j.topKeyPress,j.topKeyUp,j.topMouseDown]}},M=!1,P=null,x={eventTypes:D,extractEvents:function(e,t,o,n){return[c(e,t,o,n),d(e,t,o,n)]}};t.exports=x},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./EventPropagators":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPropagators.js","./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./FallbackCompositionState":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/FallbackCompositionState.js","./SyntheticCompositionEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticCompositionEvent.js","./SyntheticInputEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticInputEvent.js","./keyOf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CSSProperty.js":[function(e,t,o){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},a=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){a.forEach(function(t){r[n(t,e)]=r[e]})});var s={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},l={isUnitlessNumber:r,shorthandPropertyExpansions:s};t.exports=l},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CSSPropertyOperations.js":[function(e,t,o){(function(o){"use strict";var n=e("./CSSProperty"),r=e("./ExecutionEnvironment"),a=e("./camelizeStyleName"),s=e("./dangerousStyleValue"),l=e("./hyphenateStyleName"),i=e("./memoizeStringOnly"),c=e("./warning"),u=i(function(e){return l(e)}),p="cssFloat";if(r.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(p="styleFloat"),"production"!==o.env.NODE_ENV)var d=/^(?:webkit|moz|o)[A-Z]/,m=/;\s*$/,b={},h={},f=function(e){b.hasOwnProperty(e)&&b[e]||(b[e]=!0,"production"!==o.env.NODE_ENV?c(!1,"Unsupported style property %s. Did you mean %s?",e,a(e)):null)},v=function(e){b.hasOwnProperty(e)&&b[e]||(b[e]=!0,"production"!==o.env.NODE_ENV?c(!1,"Unsupported vendor-prefixed style property %s. Did you mean %s?",e,e.charAt(0).toUpperCase()+e.slice(1)):null)},E=function(e,t){h.hasOwnProperty(t)&&h[t]||(h[t]=!0,"production"!==o.env.NODE_ENV?c(!1,'Style property values shouldn\'t contain a semicolon. Try "%s: %s" instead.',e,t.replace(m,"")):null)},_=function(e,t){e.indexOf("-")>-1?f(e):d.test(e)?v(e):m.test(t)&&E(e,t)};var y={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];"production"!==o.env.NODE_ENV&&_(n,r),null!=r&&(t+=u(n)+":",t+=s(n,r)+";")}return t||null},setValueForStyles:function(e,t){var r=e.style;for(var a in t)if(t.hasOwnProperty(a)){"production"!==o.env.NODE_ENV&&_(a,t[a]);var l=s(a,t[a]);if("float"===a&&(a=p),l)r[a]=l;else{var i=n.shorthandPropertyExpansions[a];if(i)for(var c in i)r[c]="";else r[a]=""}}}};t.exports=y}).call(this,e("_process"))},{"./CSSProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CSSProperty.js","./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./camelizeStyleName":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/camelizeStyleName.js","./dangerousStyleValue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/dangerousStyleValue.js","./hyphenateStyleName":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/hyphenateStyleName.js","./memoizeStringOnly":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/memoizeStringOnly.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CallbackQueue.js":[function(e,t,o){(function(o){"use strict";function n(){this._callbacks=null,this._contexts=null}var r=e("./PooledClass"),a=e("./Object.assign"),s=e("./invariant");a(n.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){"production"!==o.env.NODE_ENV?s(e.length===t.length,"Mismatched list of contexts in callback queue"):s(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0,r=e.length;r>n;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n}).call(this,e("_process"))},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ChangeEventPlugin.js":[function(e,t,o){"use strict";function n(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function r(e){var t=C.getPooled(j.change,M,e);y.accumulateTwoPhaseDispatches(t),w.batchedUpdates(a,t)}function a(e){_.enqueueEvents(e),_.processEventQueue()}function s(e,t){D=e,M=t,D.attachEvent("onchange",r)}function l(){D&&(D.detachEvent("onchange",r),D=null,M=null)}function i(e,t,o){return e===O.topChange?o:void 0}function c(e,t,o){e===O.topFocus?(l(),s(t,o)):e===O.topBlur&&l()}function u(e,t){D=e,M=t,P=e.value,x=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(D,"value",I),D.attachEvent("onpropertychange",d)}function p(){D&&(delete D.value,D.detachEvent("onpropertychange",d),D=null,M=null,P=null,x=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==P&&(P=t,r(e))}}function m(e,t,o){return e===O.topInput?o:void 0}function b(e,t,o){e===O.topFocus?(p(),u(t,o)):e===O.topBlur&&p()}function h(e,t,o){return e!==O.topSelectionChange&&e!==O.topKeyUp&&e!==O.topKeyDown||!D||D.value===P?void 0:(P=D.value,M)}function f(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function v(e,t,o){return e===O.topClick?o:void 0}var E=e("./EventConstants"),_=e("./EventPluginHub"),y=e("./EventPropagators"),g=e("./ExecutionEnvironment"),w=e("./ReactUpdates"),C=e("./SyntheticEvent"),R=e("./isEventSupported"),k=e("./isTextInputElement"),N=e("./keyOf"),O=E.topLevelTypes,j={change:{phasedRegistrationNames:{bubbled:N({onChange:null}),captured:N({onChangeCapture:null})},dependencies:[O.topBlur,O.topChange,O.topClick,O.topFocus,O.topInput,O.topKeyDown,O.topKeyUp,O.topSelectionChange]}},D=null,M=null,P=null,x=null,T=!1;g.canUseDOM&&(T=R("change")&&(!("documentMode"in document)||document.documentMode>8));var S=!1;g.canUseDOM&&(S=R("input")&&(!("documentMode"in document)||document.documentMode>9));var I={get:function(){return x.get.call(this)},set:function(e){P=""+e,x.set.call(this,e)}},A={eventTypes:j,extractEvents:function(e,t,o,r){var a,s;if(n(t)?T?a=i:s=c:k(t)?S?a=m:(a=h,s=b):f(t)&&(a=v),a){var l=a(e,t,o);if(l){var u=C.getPooled(j.change,l,r);return y.accumulateTwoPhaseDispatches(u),u}}s&&s(e,t,o)}};t.exports=A},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./EventPluginHub":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginHub.js","./EventPropagators":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPropagators.js","./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js","./SyntheticEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticEvent.js","./isEventSupported":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isEventSupported.js","./isTextInputElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isTextInputElement.js","./keyOf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ClientReactRootIndex.js":[function(e,t,o){"use strict";var n=0,r={createReactRootIndex:function(){return n++}};t.exports=r},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMChildrenOperations.js":[function(e,t,o){(function(o){"use strict";function n(e,t,o){e.insertBefore(t,e.childNodes[o]||null)}var r=e("./Danger"),a=e("./ReactMultiChildUpdateTypes"),s=e("./setTextContent"),l=e("./invariant"),i={dangerouslyReplaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup,updateTextContent:s,processUpdates:function(e,t){for(var i,c=null,u=null,p=0;p<e.length;p++)if(i=e[p],i.type===a.MOVE_EXISTING||i.type===a.REMOVE_NODE){var d=i.fromIndex,m=i.parentNode.childNodes[d],b=i.parentID;"production"!==o.env.NODE_ENV?l(m,"processUpdates(): Unable to find child %s of element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `%s`.",d,b):l(m),c=c||{},c[b]=c[b]||[],c[b][d]=m,u=u||[],u.push(m)}var h=r.dangerouslyRenderMarkup(t);if(u)for(var f=0;f<u.length;f++)u[f].parentNode.removeChild(u[f]);for(var v=0;v<e.length;v++)switch(i=e[v],i.type){case a.INSERT_MARKUP:n(i.parentNode,h[i.markupIndex],i.toIndex);break;case a.MOVE_EXISTING:n(i.parentNode,c[i.parentID][i.fromIndex],i.toIndex);break;case a.TEXT_CONTENT:s(i.parentNode,i.textContent);break;case a.REMOVE_NODE:}}};t.exports=i}).call(this,e("_process"))},{"./Danger":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Danger.js","./ReactMultiChildUpdateTypes":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMultiChildUpdateTypes.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./setTextContent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/setTextContent.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMProperty.js":[function(e,t,o){(function(o){"use strict";function n(e,t){return(e&t)===t}var r=e("./invariant"),a={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:48,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(e){var t=e.Properties||{},s=e.DOMAttributeNames||{},i=e.DOMPropertyNames||{},c=e.DOMMutationMethods||{};e.isCustomAttribute&&l._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var u in t){"production"!==o.env.NODE_ENV?r(!l.isStandardName.hasOwnProperty(u),"injectDOMPropertyConfig(...): You're trying to inject DOM property '%s' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.",u):r(!l.isStandardName.hasOwnProperty(u)),l.isStandardName[u]=!0;var p=u.toLowerCase();if(l.getPossibleStandardName[p]=u,s.hasOwnProperty(u)){var d=s[u];l.getPossibleStandardName[d]=u,l.getAttributeName[u]=d}else l.getAttributeName[u]=p;l.getPropertyName[u]=i.hasOwnProperty(u)?i[u]:u,c.hasOwnProperty(u)?l.getMutationMethod[u]=c[u]:l.getMutationMethod[u]=null;var m=t[u];l.mustUseAttribute[u]=n(m,a.MUST_USE_ATTRIBUTE),l.mustUseProperty[u]=n(m,a.MUST_USE_PROPERTY),l.hasSideEffects[u]=n(m,a.HAS_SIDE_EFFECTS),l.hasBooleanValue[u]=n(m,a.HAS_BOOLEAN_VALUE),l.hasNumericValue[u]=n(m,a.HAS_NUMERIC_VALUE),l.hasPositiveNumericValue[u]=n(m,a.HAS_POSITIVE_NUMERIC_VALUE),l.hasOverloadedBooleanValue[u]=n(m,a.HAS_OVERLOADED_BOOLEAN_VALUE),"production"!==o.env.NODE_ENV?r(!l.mustUseAttribute[u]||!l.mustUseProperty[u],"DOMProperty: Cannot require using both attribute and property: %s",u):r(!l.mustUseAttribute[u]||!l.mustUseProperty[u]),"production"!==o.env.NODE_ENV?r(l.mustUseProperty[u]||!l.hasSideEffects[u],"DOMProperty: Properties that have side effects must use property: %s",u):r(l.mustUseProperty[u]||!l.hasSideEffects[u]),"production"!==o.env.NODE_ENV?r(!!l.hasBooleanValue[u]+!!l.hasNumericValue[u]+!!l.hasOverloadedBooleanValue[u]<=1,"DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s",u):r(!!l.hasBooleanValue[u]+!!l.hasNumericValue[u]+!!l.hasOverloadedBooleanValue[u]<=1)}}},s={},l={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<l._isCustomAttributeFunctions.length;t++){var o=l._isCustomAttributeFunctions[t];if(o(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var o,n=s[e];return n||(s[e]=n={}),t in n||(o=document.createElement(e),n[t]=o[t]),n[t]},injection:a};t.exports=l}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMPropertyOperations.js":[function(e,t,o){(function(o){"use strict";function n(e,t){return null==t||r.hasBooleanValue[e]&&!t||r.hasNumericValue[e]&&isNaN(t)||r.hasPositiveNumericValue[e]&&1>t||r.hasOverloadedBooleanValue[e]&&t===!1}var r=e("./DOMProperty"),a=e("./quoteAttributeValueForBrowser"),s=e("./warning");if("production"!==o.env.NODE_ENV)var l={children:!0,dangerouslySetInnerHTML:!0,key:!0,ref:!0},i={},c=function(e){if(!(l.hasOwnProperty(e)&&l[e]||i.hasOwnProperty(e)&&i[e])){i[e]=!0;var t=e.toLowerCase(),n=r.isCustomAttribute(t)?t:r.getPossibleStandardName.hasOwnProperty(t)?r.getPossibleStandardName[t]:null;"production"!==o.env.NODE_ENV?s(null==n,"Unknown DOM property %s. Did you mean %s?",e,n):null}};var u={createMarkupForID:function(e){return r.ID_ATTRIBUTE_NAME+"="+a(e)},createMarkupForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(e)&&r.isStandardName[e]){if(n(e,t))return"";var s=r.getAttributeName[e];return r.hasBooleanValue[e]||r.hasOverloadedBooleanValue[e]&&t===!0?s:s+"="+a(t)}return r.isCustomAttribute(e)?null==t?"":e+"="+a(t):("production"!==o.env.NODE_ENV&&c(e),null)},setValueForProperty:function(e,t,a){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var s=r.getMutationMethod[t];if(s)s(e,a);else if(n(t,a))this.deleteValueForProperty(e,t);else if(r.mustUseAttribute[t])e.setAttribute(r.getAttributeName[t],""+a);else{var l=r.getPropertyName[t];r.hasSideEffects[t]&&""+e[l]==""+a||(e[l]=a)}}else r.isCustomAttribute(t)?null==a?e.removeAttribute(t):e.setAttribute(t,""+a):"production"!==o.env.NODE_ENV&&c(t)},deleteValueForProperty:function(e,t){if(r.isStandardName.hasOwnProperty(t)&&r.isStandardName[t]){var n=r.getMutationMethod[t];if(n)n(e,void 0);else if(r.mustUseAttribute[t])e.removeAttribute(r.getAttributeName[t]);else{var a=r.getPropertyName[t],s=r.getDefaultValueForProperty(e.nodeName,a);r.hasSideEffects[t]&&""+e[a]===s||(e[a]=s)}}else r.isCustomAttribute(t)?e.removeAttribute(t):"production"!==o.env.NODE_ENV&&c(t)}};t.exports=u}).call(this,e("_process"))},{"./DOMProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMProperty.js","./quoteAttributeValueForBrowser":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/quoteAttributeValueForBrowser.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Danger.js":[function(e,t,o){(function(o){"use strict";function n(e){return e.substring(1,e.indexOf(" "))}var r=e("./ExecutionEnvironment"),a=e("./createNodesFromMarkup"),s=e("./emptyFunction"),l=e("./getMarkupWrap"),i=e("./invariant"),c=/^(<[^ \/>]+)/,u="data-danger-index",p={dangerouslyRenderMarkup:function(e){"production"!==o.env.NODE_ENV?i(r.canUseDOM,"dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use React.renderToString for server rendering."):i(r.canUseDOM);for(var t,p={},d=0;d<e.length;d++)"production"!==o.env.NODE_ENV?i(e[d],"dangerouslyRenderMarkup(...): Missing markup."):i(e[d]),t=n(e[d]),t=l(t)?t:"*",p[t]=p[t]||[],p[t][d]=e[d];var m=[],b=0;for(t in p)if(p.hasOwnProperty(t)){var h,f=p[t];for(h in f)if(f.hasOwnProperty(h)){var v=f[h];f[h]=v.replace(c,"$1 "+u+'="'+h+'" ')}for(var E=a(f.join(""),s),_=0;_<E.length;++_){var y=E[_];y.hasAttribute&&y.hasAttribute(u)?(h=+y.getAttribute(u),y.removeAttribute(u),"production"!==o.env.NODE_ENV?i(!m.hasOwnProperty(h),"Danger: Assigning to an already-occupied result index."):i(!m.hasOwnProperty(h)),m[h]=y,b+=1):"production"!==o.env.NODE_ENV&&console.error("Danger: Discarding unexpected node:",y)}}return"production"!==o.env.NODE_ENV?i(b===m.length,"Danger: Did not assign to every index of resultList."):i(b===m.length),"production"!==o.env.NODE_ENV?i(m.length===e.length,"Danger: Expected markup to render %s nodes, but rendered %s.",e.length,m.length):i(m.length===e.length),m},dangerouslyReplaceNodeWithMarkup:function(e,t){"production"!==o.env.NODE_ENV?i(r.canUseDOM,"dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use React.renderToString for server rendering."):i(r.canUseDOM),"production"!==o.env.NODE_ENV?i(t,"dangerouslyReplaceNodeWithMarkup(...): Missing markup."):i(t),"production"!==o.env.NODE_ENV?i("html"!==e.tagName.toLowerCase(),"dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See React.renderToString()."):i("html"!==e.tagName.toLowerCase());var n=a(t,s)[0];e.parentNode.replaceChild(n,e)}};t.exports=p}).call(this,e("_process"))},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./createNodesFromMarkup":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/createNodesFromMarkup.js","./emptyFunction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js","./getMarkupWrap":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getMarkupWrap.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DefaultEventPluginOrder.js":[function(e,t,o){"use strict";var n=e("./keyOf"),r=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({SelectEventPlugin:null}),n({BeforeInputEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];t.exports=r},{"./keyOf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EnterLeaveEventPlugin.js":[function(e,t,o){"use strict";var n=e("./EventConstants"),r=e("./EventPropagators"),a=e("./SyntheticMouseEvent"),s=e("./ReactMount"),l=e("./keyOf"),i=n.topLevelTypes,c=s.getFirstReactDOM,u={mouseEnter:{registrationName:l({onMouseEnter:null}),dependencies:[i.topMouseOut,i.topMouseOver]},mouseLeave:{registrationName:l({onMouseLeave:null}),dependencies:[i.topMouseOut,i.topMouseOver]}},p=[null,null],d={eventTypes:u,extractEvents:function(e,t,o,n){if(e===i.topMouseOver&&(n.relatedTarget||n.fromElement))return null;if(e!==i.topMouseOut&&e!==i.topMouseOver)return null;var l;if(t.window===t)l=t;else{var d=t.ownerDocument;l=d?d.defaultView||d.parentWindow:window}var m,b;if(e===i.topMouseOut?(m=t,b=c(n.relatedTarget||n.toElement)||l):(m=l,b=t),m===b)return null;var h=m?s.getID(m):"",f=b?s.getID(b):"",v=a.getPooled(u.mouseLeave,h,n);v.type="mouseleave",v.target=m,v.relatedTarget=b;var E=a.getPooled(u.mouseEnter,f,n);return E.type="mouseenter",E.target=b,E.relatedTarget=m,r.accumulateEnterLeaveDispatches(v,E,h,f),p[0]=v,p[1]=E,p}};t.exports=d},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./EventPropagators":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPropagators.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./SyntheticMouseEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticMouseEvent.js","./keyOf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js":[function(e,t,o){"use strict";var n=e("./keyMirror"),r=n({bubbled:null,captured:null}),a=n({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),s={topLevelTypes:a,PropagationPhases:r};t.exports=s},{"./keyMirror":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyMirror.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventListener.js":[function(e,t,o){(function(o){var n=e("./emptyFunction"),r={listen:function(e,t,o){return e.addEventListener?(e.addEventListener(t,o,!1),{remove:function(){e.removeEventListener(t,o,!1)}}):e.attachEvent?(e.attachEvent("on"+t,o),{remove:function(){e.detachEvent("on"+t,o)}}):void 0},capture:function(e,t,r){return e.addEventListener?(e.addEventListener(t,r,!0),{remove:function(){e.removeEventListener(t,r,!0)}}):("production"!==o.env.NODE_ENV&&console.error("Attempted to listen to events during the capture phase on a browser that does not support the capture phase. Your application will not receive some events."),{remove:n})},registerDefault:function(){}};t.exports=r}).call(this,e("_process"))},{"./emptyFunction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginHub.js":[function(e,t,o){(function(o){"use strict";function n(){var e=d&&d.traverseTwoPhase&&d.traverseEnterLeave;"production"!==o.env.NODE_ENV?i(e,"InstanceHandle not injected before use!"):i(e)}var r=e("./EventPluginRegistry"),a=e("./EventPluginUtils"),s=e("./accumulateInto"),l=e("./forEachAccumulated"),i=e("./invariant"),c={},u=null,p=function(e){if(e){var t=a.executeDispatch,o=r.getPluginModuleForEvent(e);o&&o.executeDispatch&&(t=o.executeDispatch),a.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},d=null,m={injection:{injectMount:a.injection.injectMount,injectInstanceHandle:function(e){d=e,"production"!==o.env.NODE_ENV&&n()},getInstanceHandle:function(){return"production"!==o.env.NODE_ENV&&n(),d},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){"production"!==o.env.NODE_ENV?i(!n||"function"==typeof n,"Expected %s listener to be a function, instead got type %s",t,typeof n):i(!n||"function"==typeof n);var r=c[t]||(c[t]={});r[e]=n},getListener:function(e,t){var o=c[t];return o&&o[e]},deleteListener:function(e,t){var o=c[t];o&&delete o[e]},deleteAllListeners:function(e){for(var t in c)delete c[t][e]},extractEvents:function(e,t,o,n){for(var a,l=r.plugins,i=0,c=l.length;c>i;i++){var u=l[i];if(u){var p=u.extractEvents(e,t,o,n);p&&(a=s(a,p))}}return a},enqueueEvents:function(e){e&&(u=s(u,e))},processEventQueue:function(){var e=u;u=null,l(e,p),"production"!==o.env.NODE_ENV?i(!u,"processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented."):i(!u)},__purge:function(){c={}},__getListenerBank:function(){return c}};t.exports=m}).call(this,e("_process"))},{"./EventPluginRegistry":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginRegistry.js","./EventPluginUtils":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginUtils.js", "./accumulateInto":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/accumulateInto.js","./forEachAccumulated":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/forEachAccumulated.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginRegistry.js":[function(e,t,o){(function(o){"use strict";function n(){if(l)for(var e in i){var t=i[e],n=l.indexOf(e);if("production"!==o.env.NODE_ENV?s(n>-1,"EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.",e):s(n>-1),!c.plugins[n]){"production"!==o.env.NODE_ENV?s(t.extractEvents,"EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.",e):s(t.extractEvents),c.plugins[n]=t;var a=t.eventTypes;for(var u in a)"production"!==o.env.NODE_ENV?s(r(a[u],t,u),"EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.",u,e):s(r(a[u],t,u))}}}function r(e,t,n){"production"!==o.env.NODE_ENV?s(!c.eventNameDispatchConfigs.hasOwnProperty(n),"EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.",n):s(!c.eventNameDispatchConfigs.hasOwnProperty(n)),c.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var l in r)if(r.hasOwnProperty(l)){var i=r[l];a(i,t,n)}return!0}return e.registrationName?(a(e.registrationName,t,n),!0):!1}function a(e,t,n){"production"!==o.env.NODE_ENV?s(!c.registrationNameModules[e],"EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.",e):s(!c.registrationNameModules[e]),c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var s=e("./invariant"),l=null,i={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){"production"!==o.env.NODE_ENV?s(!l,"EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React."):s(!l),l=Array.prototype.slice.call(e),n()},injectEventPluginsByName:function(e){var t=!1;for(var r in e)if(e.hasOwnProperty(r)){var a=e[r];i.hasOwnProperty(r)&&i[r]===a||("production"!==o.env.NODE_ENV?s(!i[r],"EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.",r):s(!i[r]),i[r]=a,t=!0)}t&&n()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return c.registrationNameModules[t.registrationName]||null;for(var o in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(o)){var n=c.registrationNameModules[t.phasedRegistrationNames[o]];if(n)return n}return null},_resetEventPlugins:function(){l=null;for(var e in i)i.hasOwnProperty(e)&&delete i[e];c.plugins.length=0;var t=c.eventNameDispatchConfigs;for(var o in t)t.hasOwnProperty(o)&&delete t[o];var n=c.registrationNameModules;for(var r in n)n.hasOwnProperty(r)&&delete n[r]}};t.exports=c}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginUtils.js":[function(e,t,o){(function(o){"use strict";function n(e){return e===v.topMouseUp||e===v.topTouchEnd||e===v.topTouchCancel}function r(e){return e===v.topMouseMove||e===v.topTouchMove}function a(e){return e===v.topMouseDown||e===v.topTouchStart}function s(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if("production"!==o.env.NODE_ENV&&m(e),Array.isArray(n))for(var a=0;a<n.length&&!e.isPropagationStopped();a++)t(e,n[a],r[a]);else n&&t(e,n,r)}function l(e,t,o){e.currentTarget=f.Mount.getNode(o);var n=t(e,o);return e.currentTarget=null,n}function i(e,t){s(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function c(e){var t=e._dispatchListeners,n=e._dispatchIDs;if("production"!==o.env.NODE_ENV&&m(e),Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function u(e){var t=c(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function p(e){"production"!==o.env.NODE_ENV&&m(e);var t=e._dispatchListeners,n=e._dispatchIDs;"production"!==o.env.NODE_ENV?h(!Array.isArray(t),"executeDirectDispatch(...): Invalid `event`."):h(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function d(e){return!!e._dispatchListeners}var m,b=e("./EventConstants"),h=e("./invariant"),f={Mount:null,injectMount:function(e){f.Mount=e,"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?h(e&&e.getNode,"EventPluginUtils.injection.injectMount(...): Injected Mount module is missing getNode."):h(e&&e.getNode))}},v=b.topLevelTypes;"production"!==o.env.NODE_ENV&&(m=function(e){var t=e._dispatchListeners,n=e._dispatchIDs,r=Array.isArray(t),a=Array.isArray(n),s=a?n.length:n?1:0,l=r?t.length:t?1:0;"production"!==o.env.NODE_ENV?h(a===r&&s===l,"EventPluginUtils: Invalid `event`."):h(a===r&&s===l)});var E={isEndish:n,isMoveish:r,isStartish:a,executeDirectDispatch:p,executeDispatch:l,executeDispatchesInOrder:i,executeDispatchesInOrderStopAtTrue:u,hasDispatches:d,injection:f,useTouchEvents:!1};t.exports=E}).call(this,e("_process"))},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPropagators.js":[function(e,t,o){(function(o){"use strict";function n(e,t,o){var n=t.dispatchConfig.phasedRegistrationNames[o];return f(e,n)}function r(e,t,r){if("production"!==o.env.NODE_ENV&&!e)throw new Error("Dispatching id must not be null");var a=t?h.bubbled:h.captured,s=n(e,r,a);s&&(r._dispatchListeners=m(r._dispatchListeners,s),r._dispatchIDs=m(r._dispatchIDs,e))}function a(e){e&&e.dispatchConfig.phasedRegistrationNames&&d.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,r,e)}function s(e,t,o){if(o&&o.dispatchConfig.registrationName){var n=o.dispatchConfig.registrationName,r=f(e,n);r&&(o._dispatchListeners=m(o._dispatchListeners,r),o._dispatchIDs=m(o._dispatchIDs,e))}}function l(e){e&&e.dispatchConfig.registrationName&&s(e.dispatchMarker,null,e)}function i(e){b(e,a)}function c(e,t,o,n){d.injection.getInstanceHandle().traverseEnterLeave(o,n,s,e,t)}function u(e){b(e,l)}var p=e("./EventConstants"),d=e("./EventPluginHub"),m=e("./accumulateInto"),b=e("./forEachAccumulated"),h=p.PropagationPhases,f=d.getListener,v={accumulateTwoPhaseDispatches:i,accumulateDirectDispatches:u,accumulateEnterLeaveDispatches:c};t.exports=v}).call(this,e("_process"))},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./EventPluginHub":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginHub.js","./accumulateInto":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/accumulateInto.js","./forEachAccumulated":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/forEachAccumulated.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js":[function(e,t,o){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};t.exports=r},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/FallbackCompositionState.js":[function(e,t,o){"use strict";function n(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var r=e("./PooledClass"),a=e("./Object.assign"),s=e("./getTextContentAccessor");a(n.prototype,{getText:function(){return"value"in this._root?this._root.value:this._root[s()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,o=this._startText,n=o.length,r=this.getText(),a=r.length;for(e=0;n>e&&o[e]===r[e];e++);var s=n-e;for(t=1;s>=t&&o[n-t]===r[a-t];t++);var l=t>1?1-t:void 0;return this._fallbackText=r.slice(e,l),this._fallbackText}}),r.addPoolingTo(n),t.exports=n},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./getTextContentAccessor":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getTextContentAccessor.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/HTMLDOMPropertyConfig.js":[function(e,t,o){"use strict";var n,r=e("./DOMProperty"),a=e("./ExecutionEnvironment"),s=r.injection.MUST_USE_ATTRIBUTE,l=r.injection.MUST_USE_PROPERTY,i=r.injection.HAS_BOOLEAN_VALUE,c=r.injection.HAS_SIDE_EFFECTS,u=r.injection.HAS_NUMERIC_VALUE,p=r.injection.HAS_POSITIVE_NUMERIC_VALUE,d=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(a.canUseDOM){var m=document.implementation;n=m&&m.hasFeature&&m.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var b={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:s|i,allowTransparency:s,alt:null,async:i,autoComplete:null,autoPlay:i,cellPadding:null,cellSpacing:null,charSet:s,checked:l|i,classID:s,className:n?s:l,cols:s|p,colSpan:null,content:null,contentEditable:null,contextMenu:s,controls:l|i,coords:null,crossOrigin:null,data:null,dateTime:s,defer:i,dir:null,disabled:s|i,download:d,draggable:null,encType:null,form:s,formAction:s,formEncType:s,formMethod:s,formNoValidate:i,formTarget:s,frameBorder:s,headers:null,height:s,hidden:s|i,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:l,label:null,lang:null,list:s,loop:l|i,low:null,manifest:s,marginHeight:null,marginWidth:null,max:null,maxLength:s,media:s,mediaGroup:null,method:null,min:null,multiple:l|i,muted:l|i,name:null,noValidate:i,open:i,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:l|i,rel:null,required:i,role:s,rows:s|p,rowSpan:null,sandbox:null,scope:null,scoped:i,scrolling:null,seamless:s|i,selected:l|i,shape:null,size:s|p,sizes:s,span:p,spellCheck:null,src:null,srcDoc:l,srcSet:s,start:u,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:l|c,width:s,wmode:s,autoCapitalize:null,autoCorrect:null,itemProp:s,itemScope:s|i,itemType:s,itemID:s,itemRef:s,property:null,unselectable:s},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=b},{"./DOMProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMProperty.js","./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/LinkedValueUtils.js":[function(e,t,o){(function(o){"use strict";function n(e){"production"!==o.env.NODE_ENV?c(null==e.props.checkedLink||null==e.props.valueLink,"Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don't want to use valueLink and vice versa."):c(null==e.props.checkedLink||null==e.props.valueLink)}function r(e){n(e),"production"!==o.env.NODE_ENV?c(null==e.props.value&&null==e.props.onChange,"Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don't want to use valueLink."):c(null==e.props.value&&null==e.props.onChange)}function a(e){n(e),"production"!==o.env.NODE_ENV?c(null==e.props.checked&&null==e.props.onChange,"Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don't want to use checkedLink"):c(null==e.props.checked&&null==e.props.onChange)}function s(e){this.props.valueLink.requestChange(e.target.value)}function l(e){this.props.checkedLink.requestChange(e.target.checked)}var i=e("./ReactPropTypes"),c=e("./invariant"),u={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},p={Mixin:{propTypes:{value:function(e,t,o){return!e[t]||u[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,o){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:i.func}},getValue:function(e){return e.props.valueLink?(r(e),e.props.valueLink.value):e.props.value},getChecked:function(e){return e.props.checkedLink?(a(e),e.props.checkedLink.value):e.props.checked},getOnChange:function(e){return e.props.valueLink?(r(e),s):e.props.checkedLink?(a(e),l):e.props.onChange}};t.exports=p}).call(this,e("_process"))},{"./ReactPropTypes":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypes.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/LocalEventTrapMixin.js":[function(e,t,o){(function(o){"use strict";function n(e){e.remove()}var r=e("./ReactBrowserEventEmitter"),a=e("./accumulateInto"),s=e("./forEachAccumulated"),l=e("./invariant"),i={trapBubbledEvent:function(e,t){"production"!==o.env.NODE_ENV?l(this.isMounted(),"Must be mounted to trap events"):l(this.isMounted());var n=this.getDOMNode();"production"!==o.env.NODE_ENV?l(n,"LocalEventTrapMixin.trapBubbledEvent(...): Requires node to be rendered."):l(n);var s=r.trapBubbledEvent(e,t,n);this._localEventListeners=a(this._localEventListeners,s)},componentWillUnmount:function(){this._localEventListeners&&s(this._localEventListeners,n)}};t.exports=i}).call(this,e("_process"))},{"./ReactBrowserEventEmitter":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserEventEmitter.js","./accumulateInto":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/accumulateInto.js","./forEachAccumulated":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/forEachAccumulated.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/MobileSafariClickEventPlugin.js":[function(e,t,o){"use strict";var n=e("./EventConstants"),r=e("./emptyFunction"),a=n.topLevelTypes,s={eventTypes:null,extractEvents:function(e,t,o,n){if(e===a.topTouchStart){var s=n.target;s&&!s.onclick&&(s.onclick=r)}}};t.exports=s},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./emptyFunction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js":[function(e,t,o){"use strict";function n(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var o=Object(e),n=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var a=arguments[r];if(null!=a){var s=Object(a);for(var l in s)n.call(s,l)&&(o[l]=s[l])}}return o}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js":[function(e,t,o){(function(o){"use strict";var n=e("./invariant"),r=function(e){var t=this;if(t.instancePool.length){var o=t.instancePool.pop();return t.call(o,e),o}return new t(e)},a=function(e,t){var o=this;if(o.instancePool.length){var n=o.instancePool.pop();return o.call(n,e,t),n}return new o(e,t)},s=function(e,t,o){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t,o),r}return new n(e,t,o)},l=function(e,t,o,n,r){var a=this;if(a.instancePool.length){var s=a.instancePool.pop();return a.call(s,e,t,o,n,r),s}return new a(e,t,o,n,r)},i=function(e){var t=this;"production"!==o.env.NODE_ENV?n(e instanceof t,"Trying to release an instance into a pool of a different type."):n(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=10,u=r,p=function(e,t){var o=e;return o.instancePool=[],o.getPooled=t||u,o.poolSize||(o.poolSize=c),o.release=i,o},d={addPoolingTo:p,oneArgumentPooler:r,twoArgumentPooler:a,threeArgumentPooler:s,fiveArgumentPooler:l};t.exports=d}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/React.js":[function(e,t,o){(function(o){"use strict";var n=e("./EventPluginUtils"),r=e("./ReactChildren"),a=e("./ReactComponent"),s=e("./ReactClass"),l=e("./ReactContext"),i=e("./ReactCurrentOwner"),c=e("./ReactElement"),u=e("./ReactElementValidator"),p=e("./ReactDOM"),d=e("./ReactDOMTextComponent"),m=e("./ReactDefaultInjection"),b=e("./ReactInstanceHandles"),h=e("./ReactMount"),f=e("./ReactPerf"),v=e("./ReactPropTypes"),E=e("./ReactReconciler"),_=e("./ReactServerRendering"),y=e("./Object.assign"),g=e("./findDOMNode"),w=e("./onlyChild");m.inject();var C=c.createElement,R=c.createFactory,k=c.cloneElement;"production"!==o.env.NODE_ENV&&(C=u.createElement,R=u.createFactory,k=u.cloneElement);var N=f.measure("React","render",h.render),O={Children:{map:r.map,forEach:r.forEach,count:r.count,only:w},Component:a,DOM:p,PropTypes:v,initializeTouchEvents:function(e){n.useTouchEvents=e},createClass:s.createClass,createElement:C,cloneElement:k,createFactory:R,createMixin:function(e){return e},constructAndRenderComponent:h.constructAndRenderComponent,constructAndRenderComponentByID:h.constructAndRenderComponentByID,findDOMNode:g,render:N,renderToString:_.renderToString,renderToStaticMarkup:_.renderToStaticMarkup,unmountComponentAtNode:h.unmountComponentAtNode,isValidElement:c.isValidElement,withContext:l.withContext,__spread:y};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:i,InstanceHandles:b,Mount:h,Reconciler:E,TextComponent:d}),"production"!==o.env.NODE_ENV){var j=e("./ExecutionEnvironment");if(j.canUseDOM&&window.top===window.self){navigator.userAgent.indexOf("Chrome")>-1&&"undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&console.debug("Download the React DevTools for a better development experience: http://fb.me/react-devtools");for(var D=[Array.isArray,Array.prototype.every,Array.prototype.forEach,Array.prototype.indexOf,Array.prototype.map,Date.now,Function.prototype.bind,Object.keys,String.prototype.split,String.prototype.trim,Object.create,Object.freeze],M=0;M<D.length;M++)if(!D[M]){console.error("One or more ES5 shim/shams expected by React are not available: http://fb.me/react-warning-polyfills");break}}}O.version="0.13.2",t.exports=O}).call(this,e("_process"))},{"./EventPluginUtils":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginUtils.js","./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactChildren":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactChildren.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponent.js","./ReactContext":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactContext.js","./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./ReactDOM":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOM.js","./ReactDOMTextComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMTextComponent.js","./ReactDefaultInjection":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDefaultInjection.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactElementValidator":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElementValidator.js","./ReactInstanceHandles":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceHandles.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./ReactPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js","./ReactPropTypes":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypes.js","./ReactReconciler":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconciler.js","./ReactServerRendering":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactServerRendering.js","./findDOMNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/findDOMNode.js","./onlyChild":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/onlyChild.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js":[function(e,t,o){"use strict";var n=e("./findDOMNode"),r={getDOMNode:function(){return n(this)}};t.exports=r},{"./findDOMNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/findDOMNode.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserEventEmitter.js":[function(e,t,o){"use strict";function n(e){return Object.prototype.hasOwnProperty.call(e,h)||(e[h]=m++,p[e[h]]={}),p[e[h]]}var r=e("./EventConstants"),a=e("./EventPluginHub"),s=e("./EventPluginRegistry"),l=e("./ReactEventEmitterMixin"),i=e("./ViewportMetrics"),c=e("./Object.assign"),u=e("./isEventSupported"),p={},d=!1,m=0,b={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},h="_reactListenersID"+String(Math.random()).slice(2),f=c({},l,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(f.handleTopLevel),f.ReactEventListener=e}},setEnabled:function(e){f.ReactEventListener&&f.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!f.ReactEventListener||!f.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var o=t,a=n(o),l=s.registrationNameDependencies[e],i=r.topLevelTypes,c=0,p=l.length;p>c;c++){var d=l[c];a.hasOwnProperty(d)&&a[d]||(d===i.topWheel?u("wheel")?f.ReactEventListener.trapBubbledEvent(i.topWheel,"wheel",o):u("mousewheel")?f.ReactEventListener.trapBubbledEvent(i.topWheel,"mousewheel",o):f.ReactEventListener.trapBubbledEvent(i.topWheel,"DOMMouseScroll",o):d===i.topScroll?u("scroll",!0)?f.ReactEventListener.trapCapturedEvent(i.topScroll,"scroll",o):f.ReactEventListener.trapBubbledEvent(i.topScroll,"scroll",f.ReactEventListener.WINDOW_HANDLE):d===i.topFocus||d===i.topBlur?(u("focus",!0)?(f.ReactEventListener.trapCapturedEvent(i.topFocus,"focus",o),f.ReactEventListener.trapCapturedEvent(i.topBlur,"blur",o)):u("focusin")&&(f.ReactEventListener.trapBubbledEvent(i.topFocus,"focusin",o),f.ReactEventListener.trapBubbledEvent(i.topBlur,"focusout",o)),a[i.topBlur]=!0,a[i.topFocus]=!0):b.hasOwnProperty(d)&&f.ReactEventListener.trapBubbledEvent(d,b[d],o),a[d]=!0)}},trapBubbledEvent:function(e,t,o){return f.ReactEventListener.trapBubbledEvent(e,t,o)},trapCapturedEvent:function(e,t,o){return f.ReactEventListener.trapCapturedEvent(e,t,o)},ensureScrollValueMonitoring:function(){if(!d){var e=i.refreshScrollValues;f.ReactEventListener.monitorScrollValue(e),d=!0}},eventNameDispatchConfigs:a.eventNameDispatchConfigs,registrationNameModules:a.registrationNameModules,putListener:a.putListener,getListener:a.getListener,deleteListener:a.deleteListener,deleteAllListeners:a.deleteAllListeners});t.exports=f},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./EventPluginHub":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginHub.js","./EventPluginRegistry":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginRegistry.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactEventEmitterMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactEventEmitterMixin.js","./ViewportMetrics":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ViewportMetrics.js","./isEventSupported":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isEventSupported.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactChildReconciler.js":[function(e,t,o){"use strict";var n=e("./ReactReconciler"),r=e("./flattenChildren"),a=e("./instantiateReactComponent"),s=e("./shouldUpdateReactComponent"),l={instantiateChildren:function(e,t,o){var n=r(e);for(var s in n)if(n.hasOwnProperty(s)){var l=n[s],i=a(l,null);n[s]=i}return n},updateChildren:function(e,t,o,l){var i=r(t);if(!i&&!e)return null;var c;for(c in i)if(i.hasOwnProperty(c)){var u=e&&e[c],p=u&&u._currentElement,d=i[c];if(s(p,d))n.receiveComponent(u,d,o,l),i[c]=u;else{u&&n.unmountComponent(u,c);var m=a(d,null);i[c]=m}}for(c in e)!e.hasOwnProperty(c)||i&&i.hasOwnProperty(c)||n.unmountComponent(e[c]);return i},unmountChildren:function(e){for(var t in e){var o=e[t];n.unmountComponent(o)}}};t.exports=l},{"./ReactReconciler":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconciler.js","./flattenChildren":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/flattenChildren.js","./instantiateReactComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/instantiateReactComponent.js","./shouldUpdateReactComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/shouldUpdateReactComponent.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactChildren.js":[function(e,t,o){(function(o){"use strict";function n(e,t){this.forEachFunction=e,this.forEachContext=t}function r(e,t,o,n){var r=e;r.forEachFunction.call(r.forEachContext,t,n)}function a(e,t,o){if(null==e)return e;var a=n.getPooled(t,o);m(e,r,a),n.release(a)}function s(e,t,o){this.mapResult=e,this.mapFunction=t,this.mapContext=o}function l(e,t,n,r){var a=e,s=a.mapResult,l=!s.hasOwnProperty(n);if("production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?b(l,"ReactChildren.map(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.",n):null),l){var i=a.mapFunction.call(a.mapContext,t,r);s[n]=i}}function i(e,t,o){if(null==e)return e;var n={},r=s.getPooled(n,t,o);return m(e,l,r),s.release(r),d.create(n)}function c(e,t,o,n){return null}function u(e,t){return m(e,c,null)}var p=e("./PooledClass"),d=e("./ReactFragment"),m=e("./traverseAllChildren"),b=e("./warning"),h=p.twoArgumentPooler,f=p.threeArgumentPooler;p.addPoolingTo(n,h),p.addPoolingTo(s,f);var v={forEach:a,map:i,count:u};t.exports=v}).call(this,e("_process"))},{"./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./ReactFragment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactFragment.js","./traverseAllChildren":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/traverseAllChildren.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js":[function(e,t,o){(function(o){"use strict";function n(e,t,n){for(var r in t)t.hasOwnProperty(r)&&("production"!==o.env.NODE_ENV?k("function"==typeof t[r],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e.displayName||"ReactClass",_[n],r):null)}function r(e,t){var n=D.hasOwnProperty(t)?D[t]:null;x.hasOwnProperty(t)&&("production"!==o.env.NODE_ENV?w(n===O.OVERRIDE_BASE,"ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.",t):w(n===O.OVERRIDE_BASE)),e.hasOwnProperty(t)&&("production"!==o.env.NODE_ENV?w(n===O.DEFINE_MANY||n===O.DEFINE_MANY_MERGED,"ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",t):w(n===O.DEFINE_MANY||n===O.DEFINE_MANY_MERGED))}function a(e,t){if(t){"production"!==o.env.NODE_ENV?w("function"!=typeof t,"ReactClass: You're attempting to use a component class as a mixin. Instead, just use a regular object."):w("function"!=typeof t),"production"!==o.env.NODE_ENV?w(!b.isValidElement(t),"ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object."):w(!b.isValidElement(t));var n=e.prototype;t.hasOwnProperty(N)&&M.mixins(e,t.mixins);for(var a in t)if(t.hasOwnProperty(a)&&a!==N){var s=t[a];if(r(n,a),M.hasOwnProperty(a))M[a](e,s);else{var l=D.hasOwnProperty(a),u=n.hasOwnProperty(a),p=s&&s.__reactDontBind,d="function"==typeof s,m=d&&!l&&!u&&!p;if(m)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[a]=s,n[a]=s;else if(u){var h=D[a];"production"!==o.env.NODE_ENV?w(l&&(h===O.DEFINE_MANY_MERGED||h===O.DEFINE_MANY),"ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.",h,a):w(l&&(h===O.DEFINE_MANY_MERGED||h===O.DEFINE_MANY)),h===O.DEFINE_MANY_MERGED?n[a]=i(n[a],s):h===O.DEFINE_MANY&&(n[a]=c(n[a],s)); }else n[a]=s,"production"!==o.env.NODE_ENV&&"function"==typeof s&&t.displayName&&(n[a].displayName=t.displayName+"_"+a)}}}}function s(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var a=n in M;"production"!==o.env.NODE_ENV?w(!a,'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.',n):w(!a);var s=n in e;"production"!==o.env.NODE_ENV?w(!s,"ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",n):w(!s),e[n]=r}}}function l(e,t){"production"!==o.env.NODE_ENV?w(e&&t&&"object"==typeof e&&"object"==typeof t,"mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects."):w(e&&t&&"object"==typeof e&&"object"==typeof t);for(var n in t)t.hasOwnProperty(n)&&("production"!==o.env.NODE_ENV?w(void 0===e[n],"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.",n):w(void 0===e[n]),e[n]=t[n]);return e}function i(e,t){return function(){var o=e.apply(this,arguments),n=t.apply(this,arguments);if(null==o)return n;if(null==n)return o;var r={};return l(r,o),l(r,n),r}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function u(e,t){var n=t.bind(e);if("production"!==o.env.NODE_ENV){n.__reactBoundContext=e,n.__reactBoundMethod=t,n.__reactBoundArguments=null;var r=e.constructor.displayName,a=n.bind;n.bind=function(s){for(var l=[],i=1,c=arguments.length;c>i;i++)l.push(arguments[i]);if(s!==e&&null!==s)"production"!==o.env.NODE_ENV?k(!1,"bind(): React component methods may only be bound to the component instance. See %s",r):null;else if(!l.length)return"production"!==o.env.NODE_ENV?k(!1,"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",r):null,n;var u=a.apply(n,arguments);return u.__reactBoundContext=e,u.__reactBoundMethod=t,u.__reactBoundArguments=l,u}}return n}function p(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var o=e.__reactAutoBindMap[t];e[t]=u(e,h.guard(o,e.constructor.displayName+"."+t))}}var d=e("./ReactComponent"),m=e("./ReactCurrentOwner"),b=e("./ReactElement"),h=e("./ReactErrorUtils"),f=e("./ReactInstanceMap"),v=e("./ReactLifeCycle"),E=e("./ReactPropTypeLocations"),_=e("./ReactPropTypeLocationNames"),y=e("./ReactUpdateQueue"),g=e("./Object.assign"),w=e("./invariant"),C=e("./keyMirror"),R=e("./keyOf"),k=e("./warning"),N=R({mixins:null}),O=C({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),j=[],D={mixins:O.DEFINE_MANY,statics:O.DEFINE_MANY,propTypes:O.DEFINE_MANY,contextTypes:O.DEFINE_MANY,childContextTypes:O.DEFINE_MANY,getDefaultProps:O.DEFINE_MANY_MERGED,getInitialState:O.DEFINE_MANY_MERGED,getChildContext:O.DEFINE_MANY_MERGED,render:O.DEFINE_ONCE,componentWillMount:O.DEFINE_MANY,componentDidMount:O.DEFINE_MANY,componentWillReceiveProps:O.DEFINE_MANY,shouldComponentUpdate:O.DEFINE_ONCE,componentWillUpdate:O.DEFINE_MANY,componentDidUpdate:O.DEFINE_MANY,componentWillUnmount:O.DEFINE_MANY,updateComponent:O.OVERRIDE_BASE},M={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var o=0;o<t.length;o++)a(e,t[o])},childContextTypes:function(e,t){"production"!==o.env.NODE_ENV&&n(e,t,E.childContext),e.childContextTypes=g({},e.childContextTypes,t)},contextTypes:function(e,t){"production"!==o.env.NODE_ENV&&n(e,t,E.context),e.contextTypes=g({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=i(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){"production"!==o.env.NODE_ENV&&n(e,t,E.prop),e.propTypes=g({},e.propTypes,t)},statics:function(e,t){s(e,t)}},P={enumerable:!1,get:function(){var e=this.displayName||this.name||"Component";return"production"!==o.env.NODE_ENV?k(!1,"%s.type is deprecated. Use %s directly to access the class.",e,e):null,Object.defineProperty(this,"type",{value:this}),this}},x={replaceState:function(e,t){y.enqueueReplaceState(this,e),t&&y.enqueueCallback(this,t)},isMounted:function(){if("production"!==o.env.NODE_ENV){var e=m.current;null!==e&&("production"!==o.env.NODE_ENV?k(e._warnedAboutRefsInRender,"%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",e.getName()||"A component"):null,e._warnedAboutRefsInRender=!0)}var t=f.get(this);return t&&t!==v.currentlyMountingInstance},setProps:function(e,t){y.enqueueSetProps(this,e),t&&y.enqueueCallback(this,t)},replaceProps:function(e,t){y.enqueueReplaceProps(this,e),t&&y.enqueueCallback(this,t)}},T=function(){};g(T.prototype,d.prototype,x);var S={createClass:function(e){var t=function(e,n){"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?k(this instanceof t,"Something is calling a React component directly. Use a factory or JSX instead. See: http://fb.me/react-legacyfactory"):null),this.__reactAutoBindMap&&p(this),this.props=e,this.context=n,this.state=null;var r=this.getInitialState?this.getInitialState():null;"production"!==o.env.NODE_ENV&&"undefined"==typeof r&&this.getInitialState._isMockFunction&&(r=null),"production"!==o.env.NODE_ENV?w("object"==typeof r&&!Array.isArray(r),"%s.getInitialState(): must return an object or null",t.displayName||"ReactCompositeComponent"):w("object"==typeof r&&!Array.isArray(r)),this.state=r};t.prototype=new T,t.prototype.constructor=t,j.forEach(a.bind(null,t)),a(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),"production"!==o.env.NODE_ENV&&(t.getDefaultProps&&(t.getDefaultProps.isReactClassApproved={}),t.prototype.getInitialState&&(t.prototype.getInitialState.isReactClassApproved={})),"production"!==o.env.NODE_ENV?w(t.prototype.render,"createClass(...): Class specification must implement a `render` method."):w(t.prototype.render),"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?k(!t.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.",e.displayName||"A component"):null);for(var n in D)t.prototype[n]||(t.prototype[n]=null);if(t.type=t,"production"!==o.env.NODE_ENV)try{Object.defineProperty(t,"type",P)}catch(r){}return t},injection:{injectMixin:function(e){j.push(e)}}};t.exports=S}).call(this,e("_process"))},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponent.js","./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactErrorUtils":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactErrorUtils.js","./ReactInstanceMap":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceMap.js","./ReactLifeCycle":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactLifeCycle.js","./ReactPropTypeLocationNames":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocationNames.js","./ReactPropTypeLocations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocations.js","./ReactUpdateQueue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdateQueue.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./keyMirror":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyMirror.js","./keyOf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponent.js":[function(e,t,o){(function(o){"use strict";function n(e,t){this.props=e,this.context=t}var r=e("./ReactUpdateQueue"),a=e("./invariant"),s=e("./warning");if(n.prototype.setState=function(e,t){"production"!==o.env.NODE_ENV?a("object"==typeof e||"function"==typeof e||null==e,"setState(...): takes an object of state variables to update or a function which returns an object of state variables."):a("object"==typeof e||"function"==typeof e||null==e),"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?s(null!=e,"setState(...): You passed an undefined or null state object; instead, use forceUpdate()."):null),r.enqueueSetState(this,e),t&&r.enqueueCallback(this,t)},n.prototype.forceUpdate=function(e){r.enqueueForceUpdate(this),e&&r.enqueueCallback(this,e)},"production"!==o.env.NODE_ENV){var l={getDOMNode:"getDOMNode",isMounted:"isMounted",replaceProps:"replaceProps",replaceState:"replaceState",setProps:"setProps"},i=function(e,t){try{Object.defineProperty(n.prototype,e,{get:function(){"production"!==o.env.NODE_ENV?s(!1,"%s(...) is deprecated in plain JavaScript React classes.",t):null}})}catch(r){}};for(var c in l)l.hasOwnProperty(c)&&i(c,l[c])}t.exports=n}).call(this,e("_process"))},{"./ReactUpdateQueue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdateQueue.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponentBrowserEnvironment.js":[function(e,t,o){"use strict";var n=e("./ReactDOMIDOperations"),r=e("./ReactMount"),a={processChildrenUpdates:n.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:n.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){r.purgeID(e)}};t.exports=a},{"./ReactDOMIDOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMIDOperations.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponentEnvironment.js":[function(e,t,o){(function(o){"use strict";var n=e("./invariant"),r=!1,a={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){"production"!==o.env.NODE_ENV?n(!r,"ReactCompositeComponent: injectEnvironment() can only be called once."):n(!r),a.unmountIDFromEnvironment=e.unmountIDFromEnvironment,a.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,a.processChildrenUpdates=e.processChildrenUpdates,r=!0}}};t.exports=a}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCompositeComponent.js":[function(e,t,o){(function(o){"use strict";function n(e){var t=e._currentElement._owner||null;if(t){var o=t.getName();if(o)return" Check the render method of `"+o+"`."}return""}var r=e("./ReactComponentEnvironment"),a=e("./ReactContext"),s=e("./ReactCurrentOwner"),l=e("./ReactElement"),i=e("./ReactElementValidator"),c=e("./ReactInstanceMap"),u=e("./ReactLifeCycle"),p=e("./ReactNativeComponent"),d=e("./ReactPerf"),m=e("./ReactPropTypeLocations"),b=e("./ReactPropTypeLocationNames"),h=e("./ReactReconciler"),f=e("./ReactUpdates"),v=e("./Object.assign"),E=e("./emptyObject"),_=e("./invariant"),y=e("./shouldUpdateReactComponent"),g=e("./warning"),w=1,C={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._isTopLevel=!1,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=w++,this._rootNodeID=e;var r=this._processProps(this._currentElement.props),a=this._processContext(this._currentElement._context),s=p.getComponentClassForElement(this._currentElement),l=new s(r,a);"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?g(null!=l.render,"%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render` in your component or you may have accidentally tried to render an element whose type is a function that isn't a React component.",s.displayName||s.name||"Component"):null),l.props=r,l.context=a,l.refs=E,this._instance=l,c.set(l,this),"production"!==o.env.NODE_ENV&&this._warnIfContextsDiffer(this._currentElement._context,n),"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?g(!l.getInitialState||l.getInitialState.isReactClassApproved,"getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",this.getName()||"a component"):null,"production"!==o.env.NODE_ENV?g(!l.getDefaultProps||l.getDefaultProps.isReactClassApproved,"getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",this.getName()||"a component"):null,"production"!==o.env.NODE_ENV?g(!l.propTypes,"propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.",this.getName()||"a component"):null,"production"!==o.env.NODE_ENV?g(!l.contextTypes,"contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.",this.getName()||"a component"):null,"production"!==o.env.NODE_ENV?g("function"!=typeof l.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.",this.getName()||"A component"):null);var i=l.state;void 0===i&&(l.state=i=null),"production"!==o.env.NODE_ENV?_("object"==typeof i&&!Array.isArray(i),"%s.state: must be set to an object or null",this.getName()||"ReactCompositeComponent"):_("object"==typeof i&&!Array.isArray(i)),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var d,m=u.currentlyMountingInstance;u.currentlyMountingInstance=this;try{l.componentWillMount&&(l.componentWillMount(),this._pendingStateQueue&&(l.state=this._processPendingState(l.props,l.context))),d=this._renderValidatedComponent()}finally{u.currentlyMountingInstance=m}this._renderedComponent=this._instantiateReactComponent(d,this._currentElement.type);var b=h.mountComponent(this._renderedComponent,e,t,this._processChildContext(n));return l.componentDidMount&&t.getReactMountReady().enqueue(l.componentDidMount,l),b},unmountComponent:function(){var e=this._instance;if(e.componentWillUnmount){var t=u.currentlyUnmountingInstance;u.currentlyUnmountingInstance=this;try{e.componentWillUnmount()}finally{u.currentlyUnmountingInstance=t}}h.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,c.remove(e)},_setPropsInternal:function(e,t){var o=this._pendingElement||this._currentElement;this._pendingElement=l.cloneAndReplaceProps(o,v({},o.props,e)),f.enqueueUpdate(this,t)},_maskContext:function(e){var t=null;if("string"==typeof this._currentElement.type)return E;var o=this._currentElement.type.contextTypes;if(!o)return E;t={};for(var n in o)t[n]=e[n];return t},_processContext:function(e){var t=this._maskContext(e);if("production"!==o.env.NODE_ENV){var n=p.getComponentClassForElement(this._currentElement);n.contextTypes&&this._checkPropTypes(n.contextTypes,t,m.context)}return t},_processChildContext:function(e){var t=this._instance,n=t.getChildContext&&t.getChildContext();if(n){"production"!==o.env.NODE_ENV?_("object"==typeof t.constructor.childContextTypes,"%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",this.getName()||"ReactCompositeComponent"):_("object"==typeof t.constructor.childContextTypes),"production"!==o.env.NODE_ENV&&this._checkPropTypes(t.constructor.childContextTypes,n,m.childContext);for(var r in n)"production"!==o.env.NODE_ENV?_(r in t.constructor.childContextTypes,'%s.getChildContext(): key "%s" is not defined in childContextTypes.',this.getName()||"ReactCompositeComponent",r):_(r in t.constructor.childContextTypes);return v({},e,n)}return e},_processProps:function(e){if("production"!==o.env.NODE_ENV){var t=p.getComponentClassForElement(this._currentElement);t.propTypes&&this._checkPropTypes(t.propTypes,e,m.prop)}return e},_checkPropTypes:function(e,t,r){var a=this.getName();for(var s in e)if(e.hasOwnProperty(s)){var l;try{"production"!==o.env.NODE_ENV?_("function"==typeof e[s],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",a||"React class",b[r],s):_("function"==typeof e[s]),l=e[s](t,s,a,r)}catch(i){l=i}if(l instanceof Error){var c=n(this);r===m.prop?"production"!==o.env.NODE_ENV?g(!1,"Failed Composite propType: %s%s",l.message,c):null:"production"!==o.env.NODE_ENV?g(!1,"Failed Context Types: %s%s",l.message,c):null}}},receiveComponent:function(e,t,o){var n=this._currentElement,r=this._context;this._pendingElement=null,this.updateComponent(t,n,e,r,o)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&h.receiveComponent(this,this._pendingElement||this._currentElement,e,this._context),(null!==this._pendingStateQueue||this._pendingForceUpdate)&&("production"!==o.env.NODE_ENV&&i.checkAndWarnForMutatedProps(this._currentElement),this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context))},_warnIfContextsDiffer:function(e,t){e=this._maskContext(e),t=this._maskContext(t);for(var n=Object.keys(t).sort(),r=this.getName()||"ReactCompositeComponent",a=0;a<n.length;a++){var s=n[a];"production"!==o.env.NODE_ENV?g(e[s]===t[s],"owner-based and parent-based contexts differ (values: `%s` vs `%s`) for key (%s) while mounting %s (see: http://fb.me/react-context-by-parent)",e[s],t[s],s,r):null}},updateComponent:function(e,t,n,r,a){var s=this._instance,l=s.context,i=s.props;t!==n&&(l=this._processContext(n._context),i=this._processProps(n.props),"production"!==o.env.NODE_ENV&&null!=a&&this._warnIfContextsDiffer(n._context,a),s.componentWillReceiveProps&&s.componentWillReceiveProps(i,l));var c=this._processPendingState(i,l),u=this._pendingForceUpdate||!s.shouldComponentUpdate||s.shouldComponentUpdate(i,c,l);"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?g("undefined"!=typeof u,"%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",this.getName()||"ReactCompositeComponent"):null),u?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,i,c,l,e,a)):(this._currentElement=n,this._context=a,s.props=i,s.state=c,s.context=l)},_processPendingState:function(e,t){var o=this._instance,n=this._pendingStateQueue,r=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!n)return o.state;for(var a=v({},r?n[0]:o.state),s=r?1:0;s<n.length;s++){var l=n[s];v(a,"function"==typeof l?l.call(o,a,e,t):l)}return a},_performComponentUpdate:function(e,t,o,n,r,a){var s=this._instance,l=s.props,i=s.state,c=s.context;s.componentWillUpdate&&s.componentWillUpdate(t,o,n),this._currentElement=e,this._context=a,s.props=t,s.state=o,s.context=n,this._updateRenderedComponent(r,a),s.componentDidUpdate&&r.getReactMountReady().enqueue(s.componentDidUpdate.bind(s,l,i,c),s)},_updateRenderedComponent:function(e,t){var o=this._renderedComponent,n=o._currentElement,r=this._renderValidatedComponent();if(y(n,r))h.receiveComponent(o,r,e,this._processChildContext(t));else{var a=this._rootNodeID,s=o._rootNodeID;h.unmountComponent(o),this._renderedComponent=this._instantiateReactComponent(r,this._currentElement.type);var l=h.mountComponent(this._renderedComponent,a,e,this._processChildContext(t));this._replaceNodeWithMarkupByID(s,l)}},_replaceNodeWithMarkupByID:function(e,t){r.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return"production"!==o.env.NODE_ENV&&"undefined"==typeof t&&e.render._isMockFunction&&(t=null),t},_renderValidatedComponent:function(){var e,t=a.current;a.current=this._processChildContext(this._currentElement._context),s.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{a.current=t,s.current=null}return"production"!==o.env.NODE_ENV?_(null===e||e===!1||l.isValidElement(e),"%s.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.",this.getName()||"ReactCompositeComponent"):_(null===e||e===!1||l.isValidElement(e)),e},attachRef:function(e,t){var o=this.getPublicInstance(),n=o.refs===E?o.refs={}:o.refs;n[e]=t.getPublicInstance()},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){return this._instance},_instantiateReactComponent:null};d.measureMethods(C,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var R={Mixin:C};t.exports=R}).call(this,e("_process"))},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactComponentEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponentEnvironment.js","./ReactContext":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactContext.js","./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactElementValidator":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElementValidator.js","./ReactInstanceMap":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceMap.js","./ReactLifeCycle":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactLifeCycle.js","./ReactNativeComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactNativeComponent.js","./ReactPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js","./ReactPropTypeLocationNames":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocationNames.js","./ReactPropTypeLocations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocations.js","./ReactReconciler":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconciler.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js","./emptyObject":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyObject.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./shouldUpdateReactComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/shouldUpdateReactComponent.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactContext.js":[function(e,t,o){(function(o){"use strict";var n=e("./Object.assign"),r=e("./emptyObject"),a=e("./warning"),s=!1,l={current:r,withContext:function(e,t){"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?a(s,"withContext is deprecated and will be removed in a future version. Use a wrapper component with getChildContext instead."):null,s=!0);var r,i=l.current;l.current=n({},i,e);try{r=t()}finally{l.current=i}return r}};t.exports=l}).call(this,e("_process"))},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./emptyObject":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyObject.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js":[function(e,t,o){"use strict";var n={current:null};t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOM.js":[function(e,t,o){(function(o){"use strict";function n(e){return"production"!==o.env.NODE_ENV?a.createFactory(e):r.createFactory(e)}var r=e("./ReactElement"),a=e("./ReactElementValidator"),s=e("./mapObject"),l=s({a:"a",abbr:"abbr",address:"address",area:"area",article:"article",aside:"aside",audio:"audio",b:"b",base:"base",bdi:"bdi",bdo:"bdo",big:"big",blockquote:"blockquote",body:"body",br:"br",button:"button",canvas:"canvas",caption:"caption",cite:"cite",code:"code",col:"col",colgroup:"colgroup",data:"data",datalist:"datalist",dd:"dd",del:"del",details:"details",dfn:"dfn",dialog:"dialog",div:"div",dl:"dl",dt:"dt",em:"em",embed:"embed",fieldset:"fieldset",figcaption:"figcaption",figure:"figure",footer:"footer",form:"form",h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",head:"head",header:"header",hr:"hr",html:"html",i:"i",iframe:"iframe",img:"img",input:"input",ins:"ins",kbd:"kbd",keygen:"keygen",label:"label",legend:"legend",li:"li",link:"link",main:"main",map:"map",mark:"mark",menu:"menu",menuitem:"menuitem",meta:"meta",meter:"meter",nav:"nav",noscript:"noscript",object:"object",ol:"ol",optgroup:"optgroup",option:"option",output:"output",p:"p",param:"param",picture:"picture",pre:"pre",progress:"progress",q:"q",rp:"rp",rt:"rt",ruby:"ruby",s:"s",samp:"samp",script:"script",section:"section",select:"select",small:"small",source:"source",span:"span",strong:"strong",style:"style",sub:"sub",summary:"summary",sup:"sup",table:"table",tbody:"tbody",td:"td",textarea:"textarea",tfoot:"tfoot",th:"th",thead:"thead",time:"time",title:"title",tr:"tr",track:"track",u:"u",ul:"ul","var":"var",video:"video",wbr:"wbr",circle:"circle",defs:"defs",ellipse:"ellipse",g:"g",line:"line",linearGradient:"linearGradient",mask:"mask",path:"path",pattern:"pattern",polygon:"polygon",polyline:"polyline",radialGradient:"radialGradient",rect:"rect",stop:"stop",svg:"svg",text:"text",tspan:"tspan"},n);t.exports=l}).call(this,e("_process"))},{"./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactElementValidator":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElementValidator.js","./mapObject":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/mapObject.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMButton.js":[function(e,t,o){"use strict";var n=e("./AutoFocusMixin"),r=e("./ReactBrowserComponentMixin"),a=e("./ReactClass"),s=e("./ReactElement"),l=e("./keyMirror"),i=s.createFactory("button"),c=l({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),u=a.createClass({displayName:"ReactDOMButton",tagName:"BUTTON",mixins:[n,r],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&c[t]||(e[t]=this.props[t]);return i(e,this.props.children)}});t.exports=u},{"./AutoFocusMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/AutoFocusMixin.js","./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./keyMirror":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyMirror.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMComponent.js":[function(e,t,o){(function(o){"use strict";function n(e){e&&(null!=e.dangerouslySetInnerHTML&&("production"!==o.env.NODE_ENV?v(null==e.children,"Can only set one of `children` or `props.dangerouslySetInnerHTML`."):v(null==e.children),"production"!==o.env.NODE_ENV?v(null!=e.dangerouslySetInnerHTML.__html,"`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit http://fb.me/react-invariant-dangerously-set-inner-html for more information."):v(null!=e.dangerouslySetInnerHTML.__html)),"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?y(null==e.innerHTML,"Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."):null,"production"!==o.env.NODE_ENV?y(!e.contentEditable||null==e.children,"A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."):null),"production"!==o.env.NODE_ENV?v(null==e.style||"object"==typeof e.style,"The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."):v(null==e.style||"object"==typeof e.style))}function r(e,t,n,r){"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?y("onScroll"!==t||E("scroll",!0),"This browser doesn't support the `onScroll` event"):null);var a=d.findReactContainerForID(e);if(a){var s=a.nodeType===N?a.ownerDocument:a;w(t,s)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function a(e){P.call(M,e)||("production"!==o.env.NODE_ENV?v(D.test(e),"Invalid tag: %s",e):v(D.test(e)),M[e]=!0)}function s(e){a(e),this._tag=e,this._renderedChildren=null,this._previousStyleCopy=null,this._rootNodeID=null}var l=e("./CSSPropertyOperations"),i=e("./DOMProperty"),c=e("./DOMPropertyOperations"),u=e("./ReactBrowserEventEmitter"),p=e("./ReactComponentBrowserEnvironment"),d=e("./ReactMount"),m=e("./ReactMultiChild"),b=e("./ReactPerf"),h=e("./Object.assign"),f=e("./escapeTextContentForBrowser"),v=e("./invariant"),E=e("./isEventSupported"),_=e("./keyOf"),y=e("./warning"),g=u.deleteListener,w=u.listenTo,C=u.registrationNameModules,R={string:!0,number:!0},k=_({style:null}),N=1,O=null,j={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},D=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,M={},P={}.hasOwnProperty;s.displayName="ReactDOMComponent",s.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,o){this._rootNodeID=e, n(this._currentElement.props);var r=j[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t,o)+r},_createOpenTagMarkupAndPutListeners:function(e){var t=this._currentElement.props,o="<"+this._tag;for(var n in t)if(t.hasOwnProperty(n)){var a=t[n];if(null!=a)if(C.hasOwnProperty(n))r(this._rootNodeID,n,a,e);else{n===k&&(a&&(a=this._previousStyleCopy=h({},t.style)),a=l.createMarkupForStyles(a));var s=c.createMarkupForProperty(n,a);s&&(o+=" "+s)}}if(e.renderToStaticMarkup)return o+">";var i=c.createMarkupForID(this._rootNodeID);return o+" "+i+">"},_createContentMarkup:function(e,t){var o="";"listing"!==this._tag&&"pre"!==this._tag&&"textarea"!==this._tag||(o="\n");var n=this._currentElement.props,r=n.dangerouslySetInnerHTML;if(null!=r){if(null!=r.__html)return o+r.__html}else{var a=R[typeof n.children]?n.children:null,s=null!=a?null:n.children;if(null!=a)return o+f(a);if(null!=s){var l=this.mountChildren(s,e,t);return o+l.join("")}}return o},receiveComponent:function(e,t,o){var n=this._currentElement;this._currentElement=e,this.updateComponent(t,n,e,o)},updateComponent:function(e,t,o,r){n(this._currentElement.props),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e,r)},_updateDOMProperties:function(e,t){var o,n,a,s=this._currentElement.props;for(o in e)if(!s.hasOwnProperty(o)&&e.hasOwnProperty(o))if(o===k){var l=this._previousStyleCopy;for(n in l)l.hasOwnProperty(n)&&(a=a||{},a[n]="");this._previousStyleCopy=null}else C.hasOwnProperty(o)?g(this._rootNodeID,o):(i.isStandardName[o]||i.isCustomAttribute(o))&&O.deletePropertyByID(this._rootNodeID,o);for(o in s){var c=s[o],u=o===k?this._previousStyleCopy:e[o];if(s.hasOwnProperty(o)&&c!==u)if(o===k)if(c?c=this._previousStyleCopy=h({},c):this._previousStyleCopy=null,u){for(n in u)!u.hasOwnProperty(n)||c&&c.hasOwnProperty(n)||(a=a||{},a[n]="");for(n in c)c.hasOwnProperty(n)&&u[n]!==c[n]&&(a=a||{},a[n]=c[n])}else a=c;else C.hasOwnProperty(o)?r(this._rootNodeID,o,c,t):(i.isStandardName[o]||i.isCustomAttribute(o))&&O.updatePropertyByID(this._rootNodeID,o,c)}a&&O.updateStylesByID(this._rootNodeID,a)},_updateDOMChildren:function(e,t,o){var n=this._currentElement.props,r=R[typeof e.children]?e.children:null,a=R[typeof n.children]?n.children:null,s=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,l=n.dangerouslySetInnerHTML&&n.dangerouslySetInnerHTML.__html,i=null!=r?null:e.children,c=null!=a?null:n.children,u=null!=r||null!=s,p=null!=a||null!=l;null!=i&&null==c?this.updateChildren(null,t,o):u&&!p&&this.updateTextContent(""),null!=a?r!==a&&this.updateTextContent(""+a):null!=l?s!==l&&O.updateInnerHTMLByID(this._rootNodeID,l):null!=c&&this.updateChildren(c,t,o)},unmountComponent:function(){this.unmountChildren(),u.deleteAllListeners(this._rootNodeID),p.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null}},b.measureMethods(s,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),h(s.prototype,s.Mixin,m.Mixin),s.injection={injectIDOperations:function(e){s.BackendIDOperations=O=e}},t.exports=s}).call(this,e("_process"))},{"./CSSPropertyOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CSSPropertyOperations.js","./DOMProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMProperty.js","./DOMPropertyOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMPropertyOperations.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactBrowserEventEmitter":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserEventEmitter.js","./ReactComponentBrowserEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponentBrowserEnvironment.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./ReactMultiChild":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMultiChild.js","./ReactPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js","./escapeTextContentForBrowser":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/escapeTextContentForBrowser.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./isEventSupported":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isEventSupported.js","./keyOf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMForm.js":[function(e,t,o){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactClass"),l=e("./ReactElement"),i=l.createFactory("form"),c=s.createClass({displayName:"ReactDOMForm",tagName:"FORM",mixins:[a,r],render:function(){return i(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(n.topLevelTypes.topSubmit,"submit")}});t.exports=c},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./LocalEventTrapMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/LocalEventTrapMixin.js","./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMIDOperations.js":[function(e,t,o){(function(o){"use strict";var n=e("./CSSPropertyOperations"),r=e("./DOMChildrenOperations"),a=e("./DOMPropertyOperations"),s=e("./ReactMount"),l=e("./ReactPerf"),i=e("./invariant"),c=e("./setInnerHTML"),u={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},p={updatePropertyByID:function(e,t,n){var r=s.getNode(e);"production"!==o.env.NODE_ENV?i(!u.hasOwnProperty(t),"updatePropertyByID(...): %s",u[t]):i(!u.hasOwnProperty(t)),null!=n?a.setValueForProperty(r,t,n):a.deleteValueForProperty(r,t)},deletePropertyByID:function(e,t,n){var r=s.getNode(e);"production"!==o.env.NODE_ENV?i(!u.hasOwnProperty(t),"updatePropertyByID(...): %s",u[t]):i(!u.hasOwnProperty(t)),a.deleteValueForProperty(r,t,n)},updateStylesByID:function(e,t){var o=s.getNode(e);n.setValueForStyles(o,t)},updateInnerHTMLByID:function(e,t){var o=s.getNode(e);c(o,t)},updateTextContentByID:function(e,t){var o=s.getNode(e);r.updateTextContent(o,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var o=s.getNode(e);r.dangerouslyReplaceNodeWithMarkup(o,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var o=0;o<e.length;o++)e[o].parentNode=s.getNode(e[o].parentID);r.processUpdates(e,t)}};l.measureMethods(p,"ReactDOMIDOperations",{updatePropertyByID:"updatePropertyByID",deletePropertyByID:"deletePropertyByID",updateStylesByID:"updateStylesByID",updateInnerHTMLByID:"updateInnerHTMLByID",updateTextContentByID:"updateTextContentByID",dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),t.exports=p}).call(this,e("_process"))},{"./CSSPropertyOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CSSPropertyOperations.js","./DOMChildrenOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMChildrenOperations.js","./DOMPropertyOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMPropertyOperations.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./ReactPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./setInnerHTML":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/setInnerHTML.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMIframe.js":[function(e,t,o){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactClass"),l=e("./ReactElement"),i=l.createFactory("iframe"),c=s.createClass({displayName:"ReactDOMIframe",tagName:"IFRAME",mixins:[a,r],render:function(){return i(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load")}});t.exports=c},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./LocalEventTrapMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/LocalEventTrapMixin.js","./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMImg.js":[function(e,t,o){"use strict";var n=e("./EventConstants"),r=e("./LocalEventTrapMixin"),a=e("./ReactBrowserComponentMixin"),s=e("./ReactClass"),l=e("./ReactElement"),i=l.createFactory("img"),c=s.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[a,r],render:function(){return i(this.props)},componentDidMount:function(){this.trapBubbledEvent(n.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(n.topLevelTypes.topError,"error")}});t.exports=c},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./LocalEventTrapMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/LocalEventTrapMixin.js","./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMInput.js":[function(e,t,o){(function(o){"use strict";function n(){this.isMounted()&&this.forceUpdate()}var r=e("./AutoFocusMixin"),a=e("./DOMPropertyOperations"),s=e("./LinkedValueUtils"),l=e("./ReactBrowserComponentMixin"),i=e("./ReactClass"),c=e("./ReactElement"),u=e("./ReactMount"),p=e("./ReactUpdates"),d=e("./Object.assign"),m=e("./invariant"),b=c.createFactory("input"),h={},f=i.createClass({displayName:"ReactDOMInput",tagName:"INPUT",mixins:[r,s.Mixin,l],getInitialState:function(){var e=this.props.defaultValue;return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=d({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=s.getValue(this);e.value=null!=t?t:this.state.initialValue;var o=s.getChecked(this);return e.checked=null!=o?o:this.state.initialChecked,e.onChange=this._handleChange,b(e,this.props.children)},componentDidMount:function(){var e=u.getID(this.getDOMNode());h[e]=this},componentWillUnmount:function(){var e=this.getDOMNode(),t=u.getID(e);delete h[t]},componentDidUpdate:function(e,t,o){var n=this.getDOMNode();null!=this.props.checked&&a.setValueForProperty(n,"checked",this.props.checked||!1);var r=s.getValue(this);null!=r&&a.setValueForProperty(n,"value",""+r)},_handleChange:function(e){var t,r=s.getOnChange(this);r&&(t=r.call(this,e)),p.asap(n,this);var a=this.props.name;if("radio"===this.props.type&&null!=a){for(var l=this.getDOMNode(),i=l;i.parentNode;)i=i.parentNode;for(var c=i.querySelectorAll("input[name="+JSON.stringify(""+a)+'][type="radio"]'),d=0,b=c.length;b>d;d++){var f=c[d];if(f!==l&&f.form===l.form){var v=u.getID(f);"production"!==o.env.NODE_ENV?m(v,"ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."):m(v);var E=h[v];"production"!==o.env.NODE_ENV?m(E,"ReactDOMInput: Unknown radio button ID %s.",v):m(E),p.asap(n,E)}}}return t}});t.exports=f}).call(this,e("_process"))},{"./AutoFocusMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/AutoFocusMixin.js","./DOMPropertyOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMPropertyOperations.js","./LinkedValueUtils":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/LinkedValueUtils.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMOption.js":[function(e,t,o){(function(o){"use strict";var n=e("./ReactBrowserComponentMixin"),r=e("./ReactClass"),a=e("./ReactElement"),s=e("./warning"),l=a.createFactory("option"),i=r.createClass({displayName:"ReactDOMOption",tagName:"OPTION",mixins:[n],componentWillMount:function(){"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?s(null==this.props.selected,"Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."):null)},render:function(){return l(this.props,this.props.children)}});t.exports=i}).call(this,e("_process"))},{"./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMSelect.js":[function(e,t,o){"use strict";function n(){if(this._pendingUpdate){this._pendingUpdate=!1;var e=l.getValue(this);null!=e&&this.isMounted()&&a(this,e)}}function r(e,t,o){if(null==e[t])return null;if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function a(e,t){var o,n,r,a=e.getDOMNode().options;if(e.props.multiple){for(o={},n=0,r=t.length;r>n;n++)o[""+t[n]]=!0;for(n=0,r=a.length;r>n;n++){var s=o.hasOwnProperty(a[n].value);a[n].selected!==s&&(a[n].selected=s)}}else{for(o=""+t,n=0,r=a.length;r>n;n++)if(a[n].value===o)return void(a[n].selected=!0);a.length&&(a[0].selected=!0)}}var s=e("./AutoFocusMixin"),l=e("./LinkedValueUtils"),i=e("./ReactBrowserComponentMixin"),c=e("./ReactClass"),u=e("./ReactElement"),p=e("./ReactUpdates"),d=e("./Object.assign"),m=u.createFactory("select"),b=c.createClass({displayName:"ReactDOMSelect",tagName:"SELECT",mixins:[s,l.Mixin,i],propTypes:{defaultValue:r,value:r},render:function(){var e=d({},this.props);return e.onChange=this._handleChange,e.value=null,m(e,this.props.children)},componentWillMount:function(){this._pendingUpdate=!1},componentDidMount:function(){var e=l.getValue(this);null!=e?a(this,e):null!=this.props.defaultValue&&a(this,this.props.defaultValue)},componentDidUpdate:function(e){var t=l.getValue(this);null!=t?(this._pendingUpdate=!1,a(this,t)):!e.multiple!=!this.props.multiple&&(null!=this.props.defaultValue?a(this,this.props.defaultValue):a(this,this.props.multiple?[]:""))},_handleChange:function(e){var t,o=l.getOnChange(this);return o&&(t=o.call(this,e)),this._pendingUpdate=!0,p.asap(n,this),t}});t.exports=b},{"./AutoFocusMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/AutoFocusMixin.js","./LinkedValueUtils":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/LinkedValueUtils.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMSelection.js":[function(e,t,o){"use strict";function n(e,t,o,n){return e===o&&t===n}function r(e){var t=document.selection,o=t.createRange(),n=o.text.length,r=o.duplicate();r.moveToElementText(e),r.setEndPoint("EndToStart",o);var a=r.text.length,s=a+n;return{start:a,end:s}}function a(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var o=t.anchorNode,r=t.anchorOffset,a=t.focusNode,s=t.focusOffset,l=t.getRangeAt(0),i=n(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=i?0:l.toString().length,u=l.cloneRange();u.selectNodeContents(e),u.setEnd(l.startContainer,l.startOffset);var p=n(u.startContainer,u.startOffset,u.endContainer,u.endOffset),d=p?0:u.toString().length,m=d+c,b=document.createRange();b.setStart(o,r),b.setEnd(a,s);var h=b.collapsed;return{start:h?m:d,end:h?d:m}}function s(e,t){var o,n,r=document.selection.createRange().duplicate();"undefined"==typeof t.end?(o=t.start,n=o):t.start>t.end?(o=t.end,n=t.start):(o=t.start,n=t.end),r.moveToElementText(e),r.moveStart("character",o),r.setEndPoint("EndToStart",r),r.moveEnd("character",n-o),r.select()}function l(e,t){if(window.getSelection){var o=window.getSelection(),n=e[u()].length,r=Math.min(t.start,n),a="undefined"==typeof t.end?r:Math.min(t.end,n);if(!o.extend&&r>a){var s=a;a=r,r=s}var l=c(e,r),i=c(e,a);if(l&&i){var p=document.createRange();p.setStart(l.node,l.offset),o.removeAllRanges(),r>a?(o.addRange(p),o.extend(i.node,i.offset)):(p.setEnd(i.node,i.offset),o.addRange(p))}}}var i=e("./ExecutionEnvironment"),c=e("./getNodeForCharacterOffset"),u=e("./getTextContentAccessor"),p=i.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?r:a,setOffsets:p?s:l};t.exports=d},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./getNodeForCharacterOffset":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getNodeForCharacterOffset.js","./getTextContentAccessor":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getTextContentAccessor.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMTextComponent.js":[function(e,t,o){"use strict";var n=e("./DOMPropertyOperations"),r=e("./ReactComponentBrowserEnvironment"),a=e("./ReactDOMComponent"),s=e("./Object.assign"),l=e("./escapeTextContentForBrowser"),i=function(e){};s(i.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,o){this._rootNodeID=e;var r=l(this._stringText);return t.renderToStaticMarkup?r:"<span "+n.createMarkupForID(e)+">"+r+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var o=""+e;o!==this._stringText&&(this._stringText=o,a.BackendIDOperations.updateTextContentByID(this._rootNodeID,o))}},unmountComponent:function(){r.unmountIDFromEnvironment(this._rootNodeID)}}),t.exports=i},{"./DOMPropertyOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMPropertyOperations.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactComponentBrowserEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponentBrowserEnvironment.js","./ReactDOMComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMComponent.js","./escapeTextContentForBrowser":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/escapeTextContentForBrowser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMTextarea.js":[function(e,t,o){(function(o){"use strict";function n(){this.isMounted()&&this.forceUpdate()}var r=e("./AutoFocusMixin"),a=e("./DOMPropertyOperations"),s=e("./LinkedValueUtils"),l=e("./ReactBrowserComponentMixin"),i=e("./ReactClass"),c=e("./ReactElement"),u=e("./ReactUpdates"),p=e("./Object.assign"),d=e("./invariant"),m=e("./warning"),b=c.createFactory("textarea"),h=i.createClass({displayName:"ReactDOMTextarea",tagName:"TEXTAREA",mixins:[r,s.Mixin,l],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&("production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?m(!1,"Use the `defaultValue` or `value` props instead of setting children on <textarea>."):null),"production"!==o.env.NODE_ENV?d(null==e,"If you supply `defaultValue` on a <textarea>, do not pass children."):d(null==e),Array.isArray(t)&&("production"!==o.env.NODE_ENV?d(t.length<=1,"<textarea> can only have at most one child."):d(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=s.getValue(this);return{initialValue:""+(null!=n?n:e)}},render:function(){var e=p({},this.props);return"production"!==o.env.NODE_ENV?d(null==e.dangerouslySetInnerHTML,"`dangerouslySetInnerHTML` does not make sense on <textarea>."):d(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,b(e,this.state.initialValue)},componentDidUpdate:function(e,t,o){var n=s.getValue(this);if(null!=n){var r=this.getDOMNode();a.setValueForProperty(r,"value",""+n)}},_handleChange:function(e){var t,o=s.getOnChange(this);return o&&(t=o.call(this,e)),u.asap(n,this),t}});t.exports=h}).call(this,e("_process"))},{"./AutoFocusMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/AutoFocusMixin.js","./DOMPropertyOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMPropertyOperations.js","./LinkedValueUtils":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/LinkedValueUtils.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDefaultBatchingStrategy.js":[function(e,t,o){"use strict";function n(){this.reinitializeTransaction()}var r=e("./ReactUpdates"),a=e("./Transaction"),s=e("./Object.assign"),l=e("./emptyFunction"),i={initialize:l,close:function(){d.isBatchingUpdates=!1}},c={initialize:l,close:r.flushBatchedUpdates.bind(r)},u=[c,i];s(n.prototype,a.Mixin,{getTransactionWrappers:function(){return u}});var p=new n,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,o,n,r){var a=d.isBatchingUpdates;d.isBatchingUpdates=!0,a?e(t,o,n,r):p.perform(e,null,t,o,n,r)}};t.exports=d},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js","./Transaction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Transaction.js","./emptyFunction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDefaultInjection.js":[function(e,t,o){(function(o){"use strict";function n(e){return b.createClass({tagName:e.toUpperCase(),render:function(){return new j(e,null,null,null,null,this.props)}})}function r(){if(M.EventEmitter.injectReactEventListener(D),M.EventPluginHub.injectEventPluginOrder(i),M.EventPluginHub.injectInstanceHandle(P),M.EventPluginHub.injectMount(x),M.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:A,EnterLeaveEventPlugin:c,ChangeEventPlugin:s,MobileSafariClickEventPlugin:d,SelectEventPlugin:S,BeforeInputEventPlugin:a}),M.NativeComponent.injectGenericComponentClass(v),M.NativeComponent.injectTextComponentClass(O),M.NativeComponent.injectAutoWrapper(n),M.Class.injectMixin(m),M.NativeComponent.injectComponentClasses({button:E,form:_,iframe:w,img:y,input:C,option:R,select:k,textarea:N,html:L("html"),head:L("head"),body:L("body")}),M.DOMProperty.injectDOMPropertyConfig(p),M.DOMProperty.injectDOMPropertyConfig(V),M.EmptyComponent.injectEmptyComponent("noscript"),M.Updates.injectReconcileTransaction(T),M.Updates.injectBatchingStrategy(f),M.RootIndex.injectCreateReactRootIndex(u.canUseDOM?l.createReactRootIndex:I.createReactRootIndex),M.Component.injectEnvironment(h),M.DOMComponent.injectIDOperations(g),"production"!==o.env.NODE_ENV){var t=u.canUseDOM&&window.location.href||"";if(/[?&]react_perf\b/.test(t)){var r=e("./ReactDefaultPerf");r.start()}}}var a=e("./BeforeInputEventPlugin"),s=e("./ChangeEventPlugin"),l=e("./ClientReactRootIndex"),i=e("./DefaultEventPluginOrder"),c=e("./EnterLeaveEventPlugin"),u=e("./ExecutionEnvironment"),p=e("./HTMLDOMPropertyConfig"),d=e("./MobileSafariClickEventPlugin"),m=e("./ReactBrowserComponentMixin"),b=e("./ReactClass"),h=e("./ReactComponentBrowserEnvironment"),f=e("./ReactDefaultBatchingStrategy"),v=e("./ReactDOMComponent"),E=e("./ReactDOMButton"),_=e("./ReactDOMForm"),y=e("./ReactDOMImg"),g=e("./ReactDOMIDOperations"),w=e("./ReactDOMIframe"),C=e("./ReactDOMInput"),R=e("./ReactDOMOption"),k=e("./ReactDOMSelect"),N=e("./ReactDOMTextarea"),O=e("./ReactDOMTextComponent"),j=e("./ReactElement"),D=e("./ReactEventListener"),M=e("./ReactInjection"),P=e("./ReactInstanceHandles"),x=e("./ReactMount"),T=e("./ReactReconcileTransaction"),S=e("./SelectEventPlugin"),I=e("./ServerReactRootIndex"),A=e("./SimpleEventPlugin"),V=e("./SVGDOMPropertyConfig"),L=e("./createFullPageComponent");t.exports={inject:r}}).call(this,e("_process"))},{"./BeforeInputEventPlugin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/BeforeInputEventPlugin.js","./ChangeEventPlugin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ChangeEventPlugin.js","./ClientReactRootIndex":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ClientReactRootIndex.js","./DefaultEventPluginOrder":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DefaultEventPluginOrder.js","./EnterLeaveEventPlugin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EnterLeaveEventPlugin.js","./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./HTMLDOMPropertyConfig":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/HTMLDOMPropertyConfig.js","./MobileSafariClickEventPlugin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/MobileSafariClickEventPlugin.js","./ReactBrowserComponentMixin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserComponentMixin.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactComponentBrowserEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponentBrowserEnvironment.js","./ReactDOMButton":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMButton.js","./ReactDOMComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMComponent.js","./ReactDOMForm":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMForm.js","./ReactDOMIDOperations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMIDOperations.js","./ReactDOMIframe":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMIframe.js","./ReactDOMImg":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMImg.js","./ReactDOMInput":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMInput.js","./ReactDOMOption":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMOption.js","./ReactDOMSelect":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMSelect.js","./ReactDOMTextComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMTextComponent.js","./ReactDOMTextarea":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMTextarea.js","./ReactDefaultBatchingStrategy":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDefaultBatchingStrategy.js","./ReactDefaultPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDefaultPerf.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactEventListener":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactEventListener.js","./ReactInjection":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInjection.js","./ReactInstanceHandles":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceHandles.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./ReactReconcileTransaction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconcileTransaction.js","./SVGDOMPropertyConfig":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SVGDOMPropertyConfig.js","./SelectEventPlugin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SelectEventPlugin.js","./ServerReactRootIndex":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ServerReactRootIndex.js","./SimpleEventPlugin":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SimpleEventPlugin.js","./createFullPageComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/createFullPageComponent.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDefaultPerf.js":[function(e,t,o){ "use strict";function n(e){return Math.floor(100*e)/100}function r(e,t,o){e[t]=(e[t]||0)+o}var a=e("./DOMProperty"),s=e("./ReactDefaultPerfAnalysis"),l=e("./ReactMount"),i=e("./ReactPerf"),c=e("./performanceNow"),u={_allMeasurements:[],_mountStack:[0],_injected:!1,start:function(){u._injected||i.injection.injectMeasure(u.measure),u._allMeasurements.length=0,i.enableMeasure=!0},stop:function(){i.enableMeasure=!1},getLastMeasurements:function(){return u._allMeasurements},printExclusive:function(e){e=e||u._allMeasurements;var t=s.getExclusiveSummary(e);console.table(t.map(function(e){return{"Component class name":e.componentName,"Total inclusive time (ms)":n(e.inclusive),"Exclusive mount time (ms)":n(e.exclusive),"Exclusive render time (ms)":n(e.render),"Mount time per instance (ms)":n(e.exclusive/e.count),"Render time per instance (ms)":n(e.render/e.count),Instances:e.count}}))},printInclusive:function(e){e=e||u._allMeasurements;var t=s.getInclusiveSummary(e);console.table(t.map(function(e){return{"Owner > component":e.componentName,"Inclusive time (ms)":n(e.time),Instances:e.count}})),console.log("Total time:",s.getTotalTime(e).toFixed(2)+" ms")},getMeasurementsSummaryMap:function(e){var t=s.getInclusiveSummary(e,!0);return t.map(function(e){return{"Owner > component":e.componentName,"Wasted time (ms)":e.time,Instances:e.count}})},printWasted:function(e){e=e||u._allMeasurements,console.table(u.getMeasurementsSummaryMap(e)),console.log("Total time:",s.getTotalTime(e).toFixed(2)+" ms")},printDOM:function(e){e=e||u._allMeasurements;var t=s.getDOMSummary(e);console.table(t.map(function(e){var t={};return t[a.ID_ATTRIBUTE_NAME]=e.id,t.type=e.type,t.args=JSON.stringify(e.args),t})),console.log("Total time:",s.getTotalTime(e).toFixed(2)+" ms")},_recordWrite:function(e,t,o,n){var r=u._allMeasurements[u._allMeasurements.length-1].writes;r[e]=r[e]||[],r[e].push({type:t,time:o,args:n})},measure:function(e,t,o){return function(){for(var n=[],a=0,s=arguments.length;s>a;a++)n.push(arguments[a]);var i,p,d;if("_renderNewRootComponent"===t||"flushBatchedUpdates"===t)return u._allMeasurements.push({exclusive:{},inclusive:{},render:{},counts:{},writes:{},displayNames:{},totalTime:0}),d=c(),p=o.apply(this,n),u._allMeasurements[u._allMeasurements.length-1].totalTime=c()-d,p;if("_mountImageIntoNode"===t||"ReactDOMIDOperations"===e){if(d=c(),p=o.apply(this,n),i=c()-d,"_mountImageIntoNode"===t){var m=l.getID(n[1]);u._recordWrite(m,t,i,n[0])}else"dangerouslyProcessChildrenUpdates"===t?n[0].forEach(function(e){var t={};null!==e.fromIndex&&(t.fromIndex=e.fromIndex),null!==e.toIndex&&(t.toIndex=e.toIndex),null!==e.textContent&&(t.textContent=e.textContent),null!==e.markupIndex&&(t.markup=n[1][e.markupIndex]),u._recordWrite(e.parentID,e.type,i,t)}):u._recordWrite(n[0],t,i,Array.prototype.slice.call(n,1));return p}if("ReactCompositeComponent"!==e||"mountComponent"!==t&&"updateComponent"!==t&&"_renderValidatedComponent"!==t)return o.apply(this,n);if("string"==typeof this._currentElement.type)return o.apply(this,n);var b="mountComponent"===t?n[0]:this._rootNodeID,h="_renderValidatedComponent"===t,f="mountComponent"===t,v=u._mountStack,E=u._allMeasurements[u._allMeasurements.length-1];if(h?r(E.counts,b,1):f&&v.push(0),d=c(),p=o.apply(this,n),i=c()-d,h)r(E.render,b,i);else if(f){var _=v.pop();v[v.length-1]+=i,r(E.exclusive,b,i-_),r(E.inclusive,b,i)}else r(E.inclusive,b,i);return E.displayNames[b]={current:this.getName(),owner:this._currentElement._owner?this._currentElement._owner.getName():"<root>"},p}}};t.exports=u},{"./DOMProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMProperty.js","./ReactDefaultPerfAnalysis":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDefaultPerfAnalysis.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./ReactPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js","./performanceNow":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/performanceNow.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDefaultPerfAnalysis.js":[function(e,t,o){function n(e){for(var t=0,o=0;o<e.length;o++){var n=e[o];t+=n.totalTime}return t}function r(e){for(var t=[],o=0;o<e.length;o++){var n,r=e[o];for(n in r.writes)r.writes[n].forEach(function(e){t.push({id:n,type:u[e.type]||e.type,args:e.args})})}return t}function a(e){for(var t,o={},n=0;n<e.length;n++){var r=e[n],a=i({},r.exclusive,r.inclusive);for(var s in a)t=r.displayNames[s].current,o[t]=o[t]||{componentName:t,inclusive:0,exclusive:0,render:0,count:0},r.render[s]&&(o[t].render+=r.render[s]),r.exclusive[s]&&(o[t].exclusive+=r.exclusive[s]),r.inclusive[s]&&(o[t].inclusive+=r.inclusive[s]),r.counts[s]&&(o[t].count+=r.counts[s])}var l=[];for(t in o)o[t].exclusive>=c&&l.push(o[t]);return l.sort(function(e,t){return t.exclusive-e.exclusive}),l}function s(e,t){for(var o,n={},r=0;r<e.length;r++){var a,s=e[r],u=i({},s.exclusive,s.inclusive);t&&(a=l(s));for(var p in u)if(!t||a[p]){var d=s.displayNames[p];o=d.owner+" > "+d.current,n[o]=n[o]||{componentName:o,time:0,count:0},s.inclusive[p]&&(n[o].time+=s.inclusive[p]),s.counts[p]&&(n[o].count+=s.counts[p])}}var m=[];for(o in n)n[o].time>=c&&m.push(n[o]);return m.sort(function(e,t){return t.time-e.time}),m}function l(e){var t={},o=Object.keys(e.writes),n=i({},e.exclusive,e.inclusive);for(var r in n){for(var a=!1,s=0;s<o.length;s++)if(0===o[s].indexOf(r)){a=!0;break}!a&&e.counts[r]>0&&(t[r]=!0)}return t}var i=e("./Object.assign"),c=1.2,u={_mountImageIntoNode:"set innerHTML",INSERT_MARKUP:"set innerHTML",MOVE_EXISTING:"move",REMOVE_NODE:"remove",TEXT_CONTENT:"set textContent",updatePropertyByID:"update attribute",deletePropertyByID:"delete attribute",updateStylesByID:"update styles",updateInnerHTMLByID:"set innerHTML",dangerouslyReplaceNodeWithMarkupByID:"replace"},p={getExclusiveSummary:a,getInclusiveSummary:s,getDOMSummary:r,getTotalTime:n};t.exports=p},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js":[function(e,t,o){(function(o){"use strict";function n(e,t){Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:function(){return this._store?this._store[t]:null},set:function(e){"production"!==o.env.NODE_ENV?i(!1,"Don't set the %s property of the React element. Instead, specify the correct value when initially creating the element.",t):null,this._store[t]=e}})}function r(e){try{var t={props:!0};for(var o in t)n(e,o);u=!0}catch(r){}}var a=e("./ReactContext"),s=e("./ReactCurrentOwner"),l=e("./Object.assign"),i=e("./warning"),c={key:!0,ref:!0},u=!1,p=function(e,t,n,r,a,s){if(this.type=e,this.key=t,this.ref=n,this._owner=r,this._context=a,"production"!==o.env.NODE_ENV){this._store={props:s,originalProps:l({},s)};try{Object.defineProperty(this._store,"validated",{configurable:!1,enumerable:!1,writable:!0})}catch(i){}if(this._store.validated=!1,u)return void Object.freeze(this)}this.props=s};p.prototype={_isReactElement:!0},"production"!==o.env.NODE_ENV&&r(p.prototype),p.createElement=function(e,t,o){var n,r={},l=null,i=null;if(null!=t){i=void 0===t.ref?null:t.ref,l=void 0===t.key?null:""+t.key;for(n in t)t.hasOwnProperty(n)&&!c.hasOwnProperty(n)&&(r[n]=t[n])}var u=arguments.length-2;if(1===u)r.children=o;else if(u>1){for(var d=Array(u),m=0;u>m;m++)d[m]=arguments[m+2];r.children=d}if(e&&e.defaultProps){var b=e.defaultProps;for(n in b)"undefined"==typeof r[n]&&(r[n]=b[n])}return new p(e,l,i,s.current,a.current,r)},p.createFactory=function(e){var t=p.createElement.bind(null,e);return t.type=e,t},p.cloneAndReplaceProps=function(e,t){var n=new p(e.type,e.key,e.ref,e._owner,e._context,t);return"production"!==o.env.NODE_ENV&&(n._store.validated=e._store.validated),n},p.cloneElement=function(e,t,o){var n,r=l({},e.props),a=e.key,i=e.ref,u=e._owner;if(null!=t){void 0!==t.ref&&(i=t.ref,u=s.current),void 0!==t.key&&(a=""+t.key);for(n in t)t.hasOwnProperty(n)&&!c.hasOwnProperty(n)&&(r[n]=t[n])}var d=arguments.length-2;if(1===d)r.children=o;else if(d>1){for(var m=Array(d),b=0;d>b;b++)m[b]=arguments[b+2];r.children=m}return new p(e.type,a,i,u,e._context,r)},p.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},t.exports=p}).call(this,e("_process"))},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactContext":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactContext.js","./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElementValidator.js":[function(e,t,o){(function(o){"use strict";function n(){if(_.current){var e=_.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function r(e){var t=e&&e.getPublicInstance();if(t){var o=t.constructor;if(o)return o.displayName||o.name||void 0}}function a(){var e=_.current;return e&&r(e)||void 0}function s(e,t){e._store.validated||null!=e.key||(e._store.validated=!0,i('Each child in an array or iterator should have a unique "key" prop.',e,t))}function l(e,t,o){N.test(e)&&i("Child objects should have non-numeric keys so ordering is preserved.",t,o)}function i(e,t,n){var s=a(),l="string"==typeof n?n:n.displayName||n.name,i=s||l,c=R[e]||(R[e]={});if(!c.hasOwnProperty(i)){c[i]=!0;var u=s?" Check the render method of "+s+".":l?" Check the React.render call using <"+l+">.":"",p="";if(t&&t._owner&&t._owner!==_.current){var d=r(t._owner);p=" It was passed a child from "+d+"."}"production"!==o.env.NODE_ENV?C(!1,e+"%s%s See http://fb.me/react-warning-keys for more information.",u,p):null}}function c(e,t){if(Array.isArray(e))for(var o=0;o<e.length;o++){var n=e[o];h.isValidElement(n)&&s(n,t)}else if(h.isValidElement(e))e._store.validated=!0;else if(e){var r=g(e);if(r){if(r!==e.entries)for(var a,i=r.call(e);!(a=i.next()).done;)h.isValidElement(a.value)&&s(a.value,t)}else if("object"==typeof e){var c=f.extractIfFragment(e);for(var u in c)c.hasOwnProperty(u)&&l(u,c[u],t)}}}function u(e,t,r,a){for(var s in t)if(t.hasOwnProperty(s)){var l;try{"production"!==o.env.NODE_ENV?w("function"==typeof t[s],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e||"React class",E[a],s):w("function"==typeof t[s]),l=t[s](r,s,e,a)}catch(i){l=i}if(l instanceof Error&&!(l.message in k)){k[l.message]=!0;var c=n(this);"production"!==o.env.NODE_ENV?C(!1,"Failed propType: %s%s",l.message,c):null}}}function p(e,t){var n=t.type,r="string"==typeof n?n:n.displayName,a=t._owner?t._owner.getPublicInstance().constructor.displayName:null,s=e+"|"+r+"|"+a;if(!O.hasOwnProperty(s)){O[s]=!0;var l="";r&&(l=" <"+r+" />");var i="";a&&(i=" The element was created by "+a+"."),"production"!==o.env.NODE_ENV?C(!1,"Don't set .props.%s of the React component%s. Instead, specify the correct value when initially creating the element or use React.cloneElement to make a new element with updated props.%s",e,l,i):null}}function d(e,t){return e!==e?t!==t:0===e&&0===t?1/e===1/t:e===t}function m(e){if(e._store){var t=e._store.originalProps,o=e.props;for(var n in o)o.hasOwnProperty(n)&&(t.hasOwnProperty(n)&&d(t[n],o[n])||(p(n,e),t[n]=o[n]))}}function b(e){if(null!=e.type){var t=y.getComponentClassForElement(e),n=t.displayName||t.name;t.propTypes&&u(n,t.propTypes,e.props,v.prop),"function"==typeof t.getDefaultProps&&("production"!==o.env.NODE_ENV?C(t.getDefaultProps.isReactClassApproved,"getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."):null)}}var h=e("./ReactElement"),f=e("./ReactFragment"),v=e("./ReactPropTypeLocations"),E=e("./ReactPropTypeLocationNames"),_=e("./ReactCurrentOwner"),y=e("./ReactNativeComponent"),g=e("./getIteratorFn"),w=e("./invariant"),C=e("./warning"),R={},k={},N=/^\d+$/,O={},j={checkAndWarnForMutatedProps:m,createElement:function(e,t,n){"production"!==o.env.NODE_ENV?C(null!=e,"React.createElement: type should not be null or undefined. It should be a string (for DOM elements) or a ReactClass (for composite components)."):null;var r=h.createElement.apply(this,arguments);if(null==r)return r;for(var a=2;a<arguments.length;a++)c(arguments[a],e);return b(r),r},createFactory:function(e){var t=j.createElement.bind(null,e);if(t.type=e,"production"!==o.env.NODE_ENV)try{Object.defineProperty(t,"type",{enumerable:!1,get:function(){return"production"!==o.env.NODE_ENV?C(!1,"Factory.type is deprecated. Access the class directly before passing it to createFactory."):null,Object.defineProperty(this,"type",{value:e}),e}})}catch(n){}return t},cloneElement:function(e,t,o){for(var n=h.cloneElement.apply(this,arguments),r=2;r<arguments.length;r++)c(arguments[r],n.type);return b(n),n}};t.exports=j}).call(this,e("_process"))},{"./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactFragment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactFragment.js","./ReactNativeComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactNativeComponent.js","./ReactPropTypeLocationNames":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocationNames.js","./ReactPropTypeLocations":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocations.js","./getIteratorFn":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getIteratorFn.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactEmptyComponent.js":[function(e,t,o){(function(o){"use strict";function n(e){u[e]=!0}function r(e){delete u[e]}function a(e){return!!u[e]}var s,l=e("./ReactElement"),i=e("./ReactInstanceMap"),c=e("./invariant"),u={},p={injectEmptyComponent:function(e){s=l.createFactory(e)}},d=function(){};d.prototype.componentDidMount=function(){var e=i.get(this);e&&n(e._rootNodeID)},d.prototype.componentWillUnmount=function(){var e=i.get(this);e&&r(e._rootNodeID)},d.prototype.render=function(){return"production"!==o.env.NODE_ENV?c(s,"Trying to return null from a render, but no null placeholder component was injected."):c(s),s()};var m=l.createElement(d),b={emptyElement:m,injection:p,isNullComponentID:a};t.exports=b}).call(this,e("_process"))},{"./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactInstanceMap":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceMap.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactErrorUtils.js":[function(e,t,o){"use strict";var n={guard:function(e,t){return e}};t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactEventEmitterMixin.js":[function(e,t,o){"use strict";function n(e){r.enqueueEvents(e),r.processEventQueue()}var r=e("./EventPluginHub"),a={handleTopLevel:function(e,t,o,a){var s=r.extractEvents(e,t,o,a);n(s)}};t.exports=a},{"./EventPluginHub":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginHub.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactEventListener.js":[function(e,t,o){"use strict";function n(e){var t=p.getID(e),o=u.getReactRootIDFromNodeID(t),n=p.findReactContainerForID(o),r=p.getFirstReactDOM(n);return r}function r(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function a(e){for(var t=p.getFirstReactDOM(b(e.nativeEvent))||window,o=t;o;)e.ancestors.push(o),o=n(o);for(var r=0,a=e.ancestors.length;a>r;r++){t=e.ancestors[r];var s=p.getID(t)||"";f._handleTopLevel(e.topLevelType,t,s,e.nativeEvent)}}function s(e){var t=h(window);e(t)}var l=e("./EventListener"),i=e("./ExecutionEnvironment"),c=e("./PooledClass"),u=e("./ReactInstanceHandles"),p=e("./ReactMount"),d=e("./ReactUpdates"),m=e("./Object.assign"),b=e("./getEventTarget"),h=e("./getUnboundedScrollPosition");m(r.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),c.addPoolingTo(r,c.twoArgumentPooler);var f={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:i.canUseDOM?window:null,setHandleTopLevel:function(e){f._handleTopLevel=e},setEnabled:function(e){f._enabled=!!e},isEnabled:function(){return f._enabled},trapBubbledEvent:function(e,t,o){var n=o;return n?l.listen(n,t,f.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,o){var n=o;return n?l.capture(n,t,f.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=s.bind(null,e);l.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(f._enabled){var o=r.getPooled(e,t);try{d.batchedUpdates(a,o)}finally{r.release(o)}}}};t.exports=f},{"./EventListener":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventListener.js","./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./ReactInstanceHandles":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceHandles.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js","./getEventTarget":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventTarget.js","./getUnboundedScrollPosition":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getUnboundedScrollPosition.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactFragment.js":[function(e,t,o){(function(o){"use strict";var n=e("./ReactElement"),r=e("./warning");if("production"!==o.env.NODE_ENV){var a="_reactFragment",s="_reactDidWarn",l=!1;try{var i=function(){return 1};Object.defineProperty({},a,{enumerable:!1,value:!0}),Object.defineProperty({},"key",{enumerable:!0,get:i}),l=!0}catch(c){}var u=function(e,t){Object.defineProperty(e,t,{enumerable:!0,get:function(){return"production"!==o.env.NODE_ENV?r(this[s],"A ReactFragment is an opaque type. Accessing any of its properties is deprecated. Pass it to one of the React.Children helpers."):null,this[s]=!0,this[a][t]},set:function(e){"production"!==o.env.NODE_ENV?r(this[s],"A ReactFragment is an immutable opaque type. Mutating its properties is deprecated."):null,this[s]=!0,this[a][t]=e}})},p={},d=function(e){var t="";for(var o in e)t+=o+":"+typeof e[o]+",";var n=!!p[t];return p[t]=!0,n}}var m={create:function(e){if("production"!==o.env.NODE_ENV){if("object"!=typeof e||!e||Array.isArray(e))return"production"!==o.env.NODE_ENV?r(!1,"React.addons.createFragment only accepts a single object.",e):null,e;if(n.isValidElement(e))return"production"!==o.env.NODE_ENV?r(!1,"React.addons.createFragment does not accept a ReactElement without a wrapper object."):null,e;if(l){var t={};Object.defineProperty(t,a,{enumerable:!1,value:e}),Object.defineProperty(t,s,{writable:!0,enumerable:!1,value:!1});for(var i in e)u(t,i);return Object.preventExtensions(t),t}}return e},extract:function(e){return"production"!==o.env.NODE_ENV&&l?e[a]?e[a]:("production"!==o.env.NODE_ENV?r(d(e),"Any use of a keyed object should be wrapped in React.addons.createFragment(object) before being passed as a child."):null,e):e},extractIfFragment:function(e){if("production"!==o.env.NODE_ENV&&l){if(e[a])return e[a];for(var t in e)if(e.hasOwnProperty(t)&&n.isValidElement(e[t]))return m.extract(e)}return e}};t.exports=m}).call(this,e("_process"))},{"./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInjection.js":[function(e,t,o){"use strict";var n=e("./DOMProperty"),r=e("./EventPluginHub"),a=e("./ReactComponentEnvironment"),s=e("./ReactClass"),l=e("./ReactEmptyComponent"),i=e("./ReactBrowserEventEmitter"),c=e("./ReactNativeComponent"),u=e("./ReactDOMComponent"),p=e("./ReactPerf"),d=e("./ReactRootIndex"),m=e("./ReactUpdates"),b={Component:a.injection,Class:s.injection,DOMComponent:u.injection,DOMProperty:n.injection,EmptyComponent:l.injection,EventPluginHub:r.injection,EventEmitter:i.injection,NativeComponent:c.injection,Perf:p.injection,RootIndex:d.injection,Updates:m.injection};t.exports=b},{"./DOMProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMProperty.js","./EventPluginHub":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginHub.js","./ReactBrowserEventEmitter":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserEventEmitter.js","./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactComponentEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponentEnvironment.js","./ReactDOMComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMComponent.js","./ReactEmptyComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactEmptyComponent.js","./ReactNativeComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactNativeComponent.js","./ReactPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js","./ReactRootIndex":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactRootIndex.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInputSelection.js":[function(e,t,o){"use strict";function n(e){return a(document.documentElement,e)}var r=e("./ReactDOMSelection"),a=e("./containsNode"),s=e("./focusNode"),l=e("./getActiveElement"),i={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=l();return{focusedElem:e,selectionRange:i.hasSelectionCapabilities(e)?i.getSelection(e):null}},restoreSelection:function(e){var t=l(),o=e.focusedElem,r=e.selectionRange;t!==o&&n(o)&&(i.hasSelectionCapabilities(o)&&i.setSelection(o,r),s(o))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var o=document.selection.createRange();o.parentElement()===e&&(t={start:-o.moveStart("character",-e.value.length),end:-o.moveEnd("character",-e.value.length)})}else t=r.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var o=t.start,n=t.end;if("undefined"==typeof n&&(n=o),"selectionStart"in e)e.selectionStart=o,e.selectionEnd=Math.min(n,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var a=e.createTextRange();a.collapse(!0),a.moveStart("character",o),a.moveEnd("character",n-o),a.select()}else r.setOffsets(e,t)}};t.exports=i},{"./ReactDOMSelection":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactDOMSelection.js","./containsNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/containsNode.js","./focusNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/focusNode.js","./getActiveElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getActiveElement.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceHandles.js":[function(e,t,o){(function(o){"use strict";function n(e){return m+e.toString(36)}function r(e,t){return e.charAt(t)===m||t===e.length}function a(e){return""===e||e.charAt(0)===m&&e.charAt(e.length-1)!==m}function s(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function l(e){return e?e.substr(0,e.lastIndexOf(m)):""}function i(e,t){if("production"!==o.env.NODE_ENV?d(a(e)&&a(t),"getNextDescendantID(%s, %s): Received an invalid React DOM ID.",e,t):d(a(e)&&a(t)),"production"!==o.env.NODE_ENV?d(s(e,t),"getNextDescendantID(...): React has made an invalid assumption about the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.",e,t):d(s(e,t)),e===t)return e;var n,l=e.length+b;for(n=l;n<t.length&&!r(t,n);n++);return t.substr(0,n)}function c(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var s=0,l=0;n>=l;l++)if(r(e,l)&&r(t,l))s=l;else if(e.charAt(l)!==t.charAt(l))break;var i=e.substr(0,s);return"production"!==o.env.NODE_ENV?d(a(i),"getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s",e,t,i):d(a(i)),i}function u(e,t,n,r,a,c){e=e||"",t=t||"","production"!==o.env.NODE_ENV?d(e!==t,"traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.",e):d(e!==t);var u=s(t,e);"production"!==o.env.NODE_ENV?d(u||s(e,t),"traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do not have a parent path.",e,t):d(u||s(e,t));for(var p=0,m=u?l:i,b=e;;b=m(b,t)){var f;if(a&&b===e||c&&b===t||(f=n(b,u,r)),f===!1||b===t)break;"production"!==o.env.NODE_ENV?d(p++<h,"traverseParentPath(%s, %s, ...): Detected an infinite loop while traversing the React DOM ID tree. This may be due to malformed IDs: %s",e,t):d(p++<h)}}var p=e("./ReactRootIndex"),d=e("./invariant"),m=".",b=m.length,h=100,f={createReactRootID:function(){return n(p.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===m&&e.length>1){var t=e.indexOf(m,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,o,n,r){var a=c(e,t);a!==e&&u(e,a,o,n,!1,!0),a!==t&&u(a,t,o,r,!0,!1)},traverseTwoPhase:function(e,t,o){e&&(u("",e,t,o,!0,!1),u(e,"",t,o,!1,!0))},traverseAncestors:function(e,t,o){u("",e,t,o,!0,!1)},_getFirstCommonAncestorID:c,_getNextDescendantID:i,isAncestorIDOf:s,SEPARATOR:m};t.exports=f}).call(this,e("_process"))},{"./ReactRootIndex":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactRootIndex.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceMap.js":[function(e,t,o){"use strict";var n={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactLifeCycle.js":[function(e,t,o){"use strict";var n={currentlyMountingInstance:null,currentlyUnmountingInstance:null};t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMarkupChecksum.js":[function(e,t,o){"use strict";var n=e("./adler32"),r={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=n(e);return e.replace(">"," "+r.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var o=t.getAttribute(r.CHECKSUM_ATTR_NAME);o=o&&parseInt(o,10);var a=n(e);return a===o}};t.exports=r},{"./adler32":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/adler32.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js":[function(e,t,o){(function(o){"use strict";function n(e,t){for(var o=Math.min(e.length,t.length),n=0;o>n;n++)if(e.charAt(n)!==t.charAt(n))return n;return e.length===t.length?-1:o}function r(e){var t=P(e);return t&&Y.getID(t)}function a(e){var t=s(e);if(t)if(U.hasOwnProperty(t)){var n=U[t];n!==e&&("production"!==o.env.NODE_ENV?T(!u(n,t),"ReactMount: Two valid but unequal nodes with the same `%s`: %s",L,t):T(!u(n,t)),U[t]=e)}else U[t]=e;return t}function s(e){return e&&e.getAttribute&&e.getAttribute(L)||""}function l(e,t){var o=s(e);o!==t&&delete U[o],e.setAttribute(L,t),U[t]=e}function i(e){return U.hasOwnProperty(e)&&u(U[e],e)||(U[e]=Y.findReactNodeByID(e)),U[e]}function c(e){var t=C.get(e)._rootNodeID;return g.isNullComponentID(t)?null:(U.hasOwnProperty(t)&&u(U[t],t)||(U[t]=Y.findReactNodeByID(t)),U[t])}function u(e,t){if(e){"production"!==o.env.NODE_ENV?T(s(e)===t,"ReactMount: Unexpected modification of `%s`",L):T(s(e)===t);var n=Y.findReactContainerForID(t);if(n&&M(n,e))return!0}return!1}function p(e){delete U[e]}function d(e){var t=U[e];return t&&u(t,e)?void(z=t):!1}function m(e){z=null,w.traverseAncestors(e,d);var t=z;return z=null,t}function b(e,t,o,n,r){var a=N.mountComponent(e,t,n,D);e._isTopLevel=!0,Y._mountImageIntoNode(a,o,r)}function h(e,t,o,n){var r=j.ReactReconcileTransaction.getPooled();r.perform(b,null,e,t,o,r,n),j.ReactReconcileTransaction.release(r)}var f=e("./DOMProperty"),v=e("./ReactBrowserEventEmitter"),E=e("./ReactCurrentOwner"),_=e("./ReactElement"),y=e("./ReactElementValidator"),g=e("./ReactEmptyComponent"),w=e("./ReactInstanceHandles"),C=e("./ReactInstanceMap"),R=e("./ReactMarkupChecksum"),k=e("./ReactPerf"),N=e("./ReactReconciler"),O=e("./ReactUpdateQueue"),j=e("./ReactUpdates"),D=e("./emptyObject"),M=e("./containsNode"),P=e("./getReactRootElementInContainer"),x=e("./instantiateReactComponent"),T=e("./invariant"),S=e("./setInnerHTML"),I=e("./shouldUpdateReactComponent"),A=e("./warning"),V=w.SEPARATOR,L=f.ID_ATTRIBUTE_NAME,U={},F=1,B=9,H={},W={};if("production"!==o.env.NODE_ENV)var K={};var q=[],z=null,Y={_instancesByReactRootID:H,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,a){return"production"!==o.env.NODE_ENV&&y.checkAndWarnForMutatedProps(t),Y.scrollMonitor(n,function(){O.enqueueElementInternal(e,t),a&&O.enqueueCallbackInternal(e,a)}),"production"!==o.env.NODE_ENV&&(K[r(n)]=P(n)),e},_registerComponent:function(e,t){"production"!==o.env.NODE_ENV?T(t&&(t.nodeType===F||t.nodeType===B),"_registerComponent(...): Target container is not a DOM element."):T(t&&(t.nodeType===F||t.nodeType===B)),v.ensureScrollValueMonitoring();var n=Y.registerContainer(t);return H[n]=e,n},_renderNewRootComponent:function(e,t,n){"production"!==o.env.NODE_ENV?A(null==E.current,"_renderNewRootComponent(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate."):null;var r=x(e,null),a=Y._registerComponent(r,t);return j.batchedUpdates(h,r,a,t,n),"production"!==o.env.NODE_ENV&&(K[a]=P(t)),r},render:function(e,t,n){"production"!==o.env.NODE_ENV?T(_.isValidElement(e),"React.render(): Invalid component element.%s","string"==typeof e?" Instead of passing an element string, make sure to instantiate it by passing it to React.createElement.":"function"==typeof e?" Instead of passing a component class, make sure to instantiate it by passing it to React.createElement.":null!=e&&void 0!==e.props?" This may be caused by unintentionally loading two independent copies of React.":""):T(_.isValidElement(e)); var a=H[r(t)];if(a){var s=a._currentElement;if(I(s,e))return Y._updateRootComponent(a,e,t,n).getPublicInstance();Y.unmountComponentAtNode(t)}var l=P(t),i=l&&Y.isRenderedByReact(l);if("production"!==o.env.NODE_ENV&&(!i||l.nextSibling))for(var c=l;c;){if(Y.isRenderedByReact(c)){"production"!==o.env.NODE_ENV?A(!1,"render(): Target node has markup rendered by React, but there are unrelated nodes as well. This is most commonly caused by white-space inserted around server-rendered markup."):null;break}c=c.nextSibling}var u=i&&!a,p=Y._renderNewRootComponent(e,t,u).getPublicInstance();return n&&n.call(p),p},constructAndRenderComponent:function(e,t,o){var n=_.createElement(e,t);return Y.render(n,o)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return"production"!==o.env.NODE_ENV?T(r,'Tried to get element with id of "%s" but it is not present on the page.',n):T(r),Y.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=r(e);return t&&(t=w.getReactRootIDFromNodeID(t)),t||(t=w.createReactRootID()),W[t]=e,t},unmountComponentAtNode:function(e){"production"!==o.env.NODE_ENV?A(null==E.current,"unmountComponentAtNode(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate."):null,"production"!==o.env.NODE_ENV?T(e&&(e.nodeType===F||e.nodeType===B),"unmountComponentAtNode(...): Target container is not a DOM element."):T(e&&(e.nodeType===F||e.nodeType===B));var t=r(e),n=H[t];return n?(Y.unmountComponentFromNode(n,e),delete H[t],delete W[t],"production"!==o.env.NODE_ENV&&delete K[t],!0):!1},unmountComponentFromNode:function(e,t){for(N.unmountComponent(e),t.nodeType===B&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)},findReactContainerForID:function(e){var t=w.getReactRootIDFromNodeID(e),n=W[t];if("production"!==o.env.NODE_ENV){var r=K[t];if(r&&r.parentNode!==n){"production"!==o.env.NODE_ENV?T(s(r)===t,"ReactMount: Root element ID differed from reactRootID."):T(s(r)===t);var a=n.firstChild;a&&t===s(a)?K[t]=a:"production"!==o.env.NODE_ENV?A(!1,"ReactMount: Root element has been removed from its original container. New container:",r.parentNode):null}}return n},findReactNodeByID:function(e){var t=Y.findReactContainerForID(e);return Y.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=Y.getID(e);return t?t.charAt(0)===V:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(Y.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=q,r=0,a=m(t)||e;for(n[0]=a.firstChild,n.length=1;r<n.length;){for(var s,l=n[r++];l;){var i=Y.getID(l);i?t===i?s=l:w.isAncestorIDOf(i,t)&&(n.length=r=0,n.push(l.firstChild)):n.push(l.firstChild),l=l.nextSibling}if(s)return n.length=0,s}n.length=0,"production"!==o.env.NODE_ENV?T(!1,"findComponentRoot(..., %s): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `%s`.",t,Y.getID(e)):T(!1)},_mountImageIntoNode:function(e,t,r){if("production"!==o.env.NODE_ENV?T(t&&(t.nodeType===F||t.nodeType===B),"mountComponentIntoNode(...): Target container is not valid."):T(t&&(t.nodeType===F||t.nodeType===B)),r){var a=P(t);if(R.canReuseMarkup(e,a))return;var s=a.getAttribute(R.CHECKSUM_ATTR_NAME);a.removeAttribute(R.CHECKSUM_ATTR_NAME);var l=a.outerHTML;a.setAttribute(R.CHECKSUM_ATTR_NAME,s);var i=n(e,l),c=" (client) "+e.substring(i-20,i+20)+"\n (server) "+l.substring(i-20,i+20);"production"!==o.env.NODE_ENV?T(t.nodeType!==B,"You're trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s",c):T(t.nodeType!==B),"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?A(!1,"React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:\n%s",c):null)}"production"!==o.env.NODE_ENV?T(t.nodeType!==B,"You're trying to render a component to the document but you didn't use server rendering. We can't do this without using server rendering due to cross-browser quirks. See React.renderToString() for server rendering."):T(t.nodeType!==B),S(t,e)},getReactRootID:r,getID:a,setID:l,getNode:i,getNodeFromInstance:c,purgeID:p};k.measureMethods(Y,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),t.exports=Y}).call(this,e("_process"))},{"./DOMProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMProperty.js","./ReactBrowserEventEmitter":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserEventEmitter.js","./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactElementValidator":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElementValidator.js","./ReactEmptyComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactEmptyComponent.js","./ReactInstanceHandles":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceHandles.js","./ReactInstanceMap":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceMap.js","./ReactMarkupChecksum":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMarkupChecksum.js","./ReactPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js","./ReactReconciler":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconciler.js","./ReactUpdateQueue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdateQueue.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js","./containsNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/containsNode.js","./emptyObject":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyObject.js","./getReactRootElementInContainer":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getReactRootElementInContainer.js","./instantiateReactComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/instantiateReactComponent.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./setInnerHTML":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/setInnerHTML.js","./shouldUpdateReactComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/shouldUpdateReactComponent.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMultiChild.js":[function(e,t,o){"use strict";function n(e,t,o){b.push({parentID:e,parentNode:null,type:u.INSERT_MARKUP,markupIndex:h.push(t)-1,textContent:null,fromIndex:null,toIndex:o})}function r(e,t,o){b.push({parentID:e,parentNode:null,type:u.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:o})}function a(e,t){b.push({parentID:e,parentNode:null,type:u.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function s(e,t){b.push({parentID:e,parentNode:null,type:u.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function l(){b.length&&(c.processChildrenUpdates(b,h),i())}function i(){b.length=0,h.length=0}var c=e("./ReactComponentEnvironment"),u=e("./ReactMultiChildUpdateTypes"),p=e("./ReactReconciler"),d=e("./ReactChildReconciler"),m=0,b=[],h=[],f={Mixin:{mountChildren:function(e,t,o){var n=d.instantiateChildren(e,t,o);this._renderedChildren=n;var r=[],a=0;for(var s in n)if(n.hasOwnProperty(s)){var l=n[s],i=this._rootNodeID+s,c=p.mountComponent(l,i,t,o);l._mountIndex=a,r.push(c),a++}return r},updateTextContent:function(e){m++;var t=!0;try{var o=this._renderedChildren;d.unmountChildren(o);for(var n in o)o.hasOwnProperty(n)&&this._unmountChildByName(o[n],n);this.setTextContent(e),t=!1}finally{m--,m||(t?i():l())}},updateChildren:function(e,t,o){m++;var n=!0;try{this._updateChildren(e,t,o),n=!1}finally{m--,m||(n?i():l())}},_updateChildren:function(e,t,o){var n=this._renderedChildren,r=d.updateChildren(n,e,t,o);if(this._renderedChildren=r,r||n){var a,s=0,l=0;for(a in r)if(r.hasOwnProperty(a)){var i=n&&n[a],c=r[a];i===c?(this.moveChild(i,l,s),s=Math.max(i._mountIndex,s),i._mountIndex=l):(i&&(s=Math.max(i._mountIndex,s),this._unmountChildByName(i,a)),this._mountChildByNameAtIndex(c,a,l,t,o)),l++}for(a in n)!n.hasOwnProperty(a)||r&&r.hasOwnProperty(a)||this._unmountChildByName(n[a],a)}},unmountChildren:function(){var e=this._renderedChildren;d.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,o){e._mountIndex<o&&r(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){n(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){a(this._rootNodeID,e._mountIndex)},setTextContent:function(e){s(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,o,n,r){var a=this._rootNodeID+t,s=p.mountComponent(e,a,n,r);e._mountIndex=o,this.createChild(e,s)},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null}}};t.exports=f},{"./ReactChildReconciler":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactChildReconciler.js","./ReactComponentEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactComponentEnvironment.js","./ReactMultiChildUpdateTypes":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMultiChildUpdateTypes.js","./ReactReconciler":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconciler.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMultiChildUpdateTypes.js":[function(e,t,o){"use strict";var n=e("./keyMirror"),r=n({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=r},{"./keyMirror":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyMirror.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactNativeComponent.js":[function(e,t,o){(function(o){"use strict";function n(e){if("function"==typeof e.type)return e.type;var t=e.type,o=p[t];return null==o&&(p[t]=o=c(t)),o}function r(e){return"production"!==o.env.NODE_ENV?i(u,"There is no registered component for the tag %s",e.type):i(u),new u(e.type,e.props)}function a(e){return new d(e)}function s(e){return e instanceof d}var l=e("./Object.assign"),i=e("./invariant"),c=null,u=null,p={},d=null,m={injectGenericComponentClass:function(e){u=e},injectTextComponentClass:function(e){d=e},injectComponentClasses:function(e){l(p,e)},injectAutoWrapper:function(e){c=e}},b={getComponentClassForElement:n,createInternalComponent:r,createInstanceForText:a,isTextComponent:s,injection:m};t.exports=b}).call(this,e("_process"))},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactOwner.js":[function(e,t,o){(function(o){"use strict";var n=e("./invariant"),r={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,a){"production"!==o.env.NODE_ENV?n(r.isValidOwner(a),"addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref."):n(r.isValidOwner(a)),a.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,a){"production"!==o.env.NODE_ENV?n(r.isValidOwner(a),"removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This usually means that you're trying to remove a ref to a component that doesn't have an owner (that is, was not created inside of another component's `render` method). Try rendering this component inside of a new top-level component which will hold the ref."):n(r.isValidOwner(a)),a.getPublicInstance().refs[t]===e.getPublicInstance()&&a.detachRef(t)}};t.exports=r}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js":[function(e,t,o){(function(e){"use strict";function o(e,t,o){return o}var n={enableMeasure:!1,storedMeasure:o,measureMethods:function(t,o,r){if("production"!==e.env.NODE_ENV)for(var a in r)r.hasOwnProperty(a)&&(t[a]=n.measure(o,r[a],t[a]))},measure:function(t,o,r){if("production"!==e.env.NODE_ENV){var a=null,s=function(){return n.enableMeasure?(a||(a=n.storedMeasure(t,o,r)),a.apply(this,arguments)):r.apply(this,arguments)};return s.displayName=t+"_"+o,s}return r},injection:{injectMeasure:function(e){n.storedMeasure=e}}};t.exports=n}).call(this,e("_process"))},{_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocationNames.js":[function(e,t,o){(function(e){"use strict";var o={};"production"!==e.env.NODE_ENV&&(o={prop:"prop",context:"context",childContext:"child context"}),t.exports=o}).call(this,e("_process"))},{_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocations.js":[function(e,t,o){"use strict";var n=e("./keyMirror"),r=n({prop:null,context:null,childContext:null});t.exports=r},{"./keyMirror":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyMirror.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypes.js":[function(e,t,o){"use strict";function n(e){function t(t,o,n,r,a){if(r=r||g,null==o[n]){var s=_[a];return t?new Error("Required "+s+" `"+n+"` was not specified in "+("`"+r+"`.")):null}return e(o,n,r,a)}var o=t.bind(null,!1);return o.isRequired=t.bind(null,!0),o}function r(e){function t(t,o,n,r){var a=t[o],s=h(a);if(s!==e){var l=_[r],i=f(a);return new Error("Invalid "+l+" `"+o+"` of type `"+i+"` "+("supplied to `"+n+"`, expected `"+e+"`."))}return null}return n(t)}function a(){return n(y.thatReturns(null))}function s(e){function t(t,o,n,r){var a=t[o];if(!Array.isArray(a)){var s=_[r],l=h(a);return new Error("Invalid "+s+" `"+o+"` of type "+("`"+l+"` supplied to `"+n+"`, expected an array."))}for(var i=0;i<a.length;i++){var c=e(a,i,n,r);if(c instanceof Error)return c}return null}return n(t)}function l(){function e(e,t,o,n){if(!v.isValidElement(e[t])){var r=_[n];return new Error("Invalid "+r+" `"+t+"` supplied to "+("`"+o+"`, expected a ReactElement."))}return null}return n(e)}function i(e){function t(t,o,n,r){if(!(t[o]instanceof e)){var a=_[r],s=e.name||g;return new Error("Invalid "+a+" `"+o+"` supplied to "+("`"+n+"`, expected instance of `"+s+"`."))}return null}return n(t)}function c(e){function t(t,o,n,r){for(var a=t[o],s=0;s<e.length;s++)if(a===e[s])return null;var l=_[r],i=JSON.stringify(e);return new Error("Invalid "+l+" `"+o+"` of value `"+a+"` "+("supplied to `"+n+"`, expected one of "+i+"."))}return n(t)}function u(e){function t(t,o,n,r){var a=t[o],s=h(a);if("object"!==s){var l=_[r];return new Error("Invalid "+l+" `"+o+"` of type "+("`"+s+"` supplied to `"+n+"`, expected an object."))}for(var i in a)if(a.hasOwnProperty(i)){var c=e(a,i,n,r);if(c instanceof Error)return c}return null}return n(t)}function p(e){function t(t,o,n,r){for(var a=0;a<e.length;a++){var s=e[a];if(null==s(t,o,n,r))return null}var l=_[r];return new Error("Invalid "+l+" `"+o+"` supplied to "+("`"+n+"`."))}return n(t)}function d(){function e(e,t,o,n){if(!b(e[t])){var r=_[n];return new Error("Invalid "+r+" `"+t+"` supplied to "+("`"+o+"`, expected a ReactNode."))}return null}return n(e)}function m(e){function t(t,o,n,r){var a=t[o],s=h(a);if("object"!==s){var l=_[r];return new Error("Invalid "+l+" `"+o+"` of type `"+s+"` "+("supplied to `"+n+"`, expected `object`."))}for(var i in e){var c=e[i];if(c){var u=c(a,i,n,r);if(u)return u}}return null}return n(t)}function b(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(b);if(null===e||v.isValidElement(e))return!0;e=E.extractIfFragment(e);for(var t in e)if(!b(e[t]))return!1;return!0;default:return!1}}function h(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function f(e){var t=h(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var v=e("./ReactElement"),E=e("./ReactFragment"),_=e("./ReactPropTypeLocationNames"),y=e("./emptyFunction"),g="<<anonymous>>",w=l(),C=d(),R={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:a(),arrayOf:s,element:w,instanceOf:i,node:C,objectOf:u,oneOf:c,oneOfType:p,shape:m};t.exports=R},{"./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactFragment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactFragment.js","./ReactPropTypeLocationNames":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPropTypeLocationNames.js","./emptyFunction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPutListenerQueue.js":[function(e,t,o){"use strict";function n(){this.listenersToPut=[]}var r=e("./PooledClass"),a=e("./ReactBrowserEventEmitter"),s=e("./Object.assign");s(n.prototype,{enqueuePutListener:function(e,t,o){this.listenersToPut.push({rootNodeID:e,propKey:t,propValue:o})},putListeners:function(){for(var e=0;e<this.listenersToPut.length;e++){var t=this.listenersToPut[e];a.putListener(t.rootNodeID,t.propKey,t.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./ReactBrowserEventEmitter":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserEventEmitter.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconcileTransaction.js":[function(e,t,o){"use strict";function n(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.putListenerQueue=i.getPooled()}var r=e("./CallbackQueue"),a=e("./PooledClass"),s=e("./ReactBrowserEventEmitter"),l=e("./ReactInputSelection"),i=e("./ReactPutListenerQueue"),c=e("./Transaction"),u=e("./Object.assign"),p={initialize:l.getSelectionInformation,close:l.restoreSelection},d={initialize:function(){var e=s.isEnabled();return s.setEnabled(!1),e},close:function(e){s.setEnabled(e)}},m={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},b={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},h=[b,p,d,m],f={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,i.release(this.putListenerQueue),this.putListenerQueue=null}};u(n.prototype,c.Mixin,f),a.addPoolingTo(n),t.exports=n},{"./CallbackQueue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CallbackQueue.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./ReactBrowserEventEmitter":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactBrowserEventEmitter.js","./ReactInputSelection":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInputSelection.js","./ReactPutListenerQueue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPutListenerQueue.js","./Transaction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Transaction.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconciler.js":[function(e,t,o){(function(o){"use strict";function n(){r.attachRefs(this,this._currentElement)}var r=e("./ReactRef"),a=e("./ReactElementValidator"),s={mountComponent:function(e,t,r,s){var l=e.mountComponent(t,r,s);return"production"!==o.env.NODE_ENV&&a.checkAndWarnForMutatedProps(e._currentElement),r.getReactMountReady().enqueue(n,e),l},unmountComponent:function(e){r.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,s,l){var i=e._currentElement;if(t!==i||null==t._owner){"production"!==o.env.NODE_ENV&&a.checkAndWarnForMutatedProps(t);var c=r.shouldUpdateRefs(i,t);c&&r.detachRefs(e,i),e.receiveComponent(t,s,l),c&&s.getReactMountReady().enqueue(n,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}};t.exports=s}).call(this,e("_process"))},{"./ReactElementValidator":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElementValidator.js","./ReactRef":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactRef.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactRef.js":[function(e,t,o){"use strict";function n(e,t,o){"function"==typeof e?e(t.getPublicInstance()):a.addComponentAsRefTo(t,e,o)}function r(e,t,o){"function"==typeof e?e(null):a.removeComponentAsRefFrom(t,e,o)}var a=e("./ReactOwner"),s={};s.attachRefs=function(e,t){var o=t.ref;null!=o&&n(o,e,t._owner)},s.shouldUpdateRefs=function(e,t){return t._owner!==e._owner||t.ref!==e.ref},s.detachRefs=function(e,t){var o=t.ref;null!=o&&r(o,e,t._owner)},t.exports=s},{"./ReactOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactOwner.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactRootIndex.js":[function(e,t,o){"use strict";var n={injectCreateReactRootIndex:function(e){r.createReactRootIndex=e}},r={createReactRootIndex:null,injection:n};t.exports=r},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactServerRendering.js":[function(e,t,o){(function(o){"use strict";function n(e){"production"!==o.env.NODE_ENV?p(a.isValidElement(e),"renderToString(): You must pass a valid ReactElement."):p(a.isValidElement(e));var t;try{var n=s.createReactRootID();return t=i.getPooled(!1),t.perform(function(){var o=u(e,null),r=o.mountComponent(n,t,c);return l.addChecksumToMarkup(r)},null)}finally{i.release(t)}}function r(e){"production"!==o.env.NODE_ENV?p(a.isValidElement(e),"renderToStaticMarkup(): You must pass a valid ReactElement."):p(a.isValidElement(e));var t;try{var n=s.createReactRootID();return t=i.getPooled(!0),t.perform(function(){var o=u(e,null);return o.mountComponent(n,t,c)},null)}finally{i.release(t)}}var a=e("./ReactElement"),s=e("./ReactInstanceHandles"),l=e("./ReactMarkupChecksum"),i=e("./ReactServerRenderingTransaction"),c=e("./emptyObject"),u=e("./instantiateReactComponent"),p=e("./invariant");t.exports={renderToString:n,renderToStaticMarkup:r}}).call(this,e("_process"))},{"./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactInstanceHandles":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceHandles.js","./ReactMarkupChecksum":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMarkupChecksum.js","./ReactServerRenderingTransaction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactServerRenderingTransaction.js","./emptyObject":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyObject.js","./instantiateReactComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/instantiateReactComponent.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactServerRenderingTransaction.js":[function(e,t,o){"use strict";function n(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=a.getPooled(null),this.putListenerQueue=s.getPooled()}var r=e("./PooledClass"),a=e("./CallbackQueue"),s=e("./ReactPutListenerQueue"),l=e("./Transaction"),i=e("./Object.assign"),c=e("./emptyFunction"),u={initialize:function(){this.reactMountReady.reset()},close:c},p={initialize:function(){this.putListenerQueue.reset()},close:c},d=[p,u],m={getTransactionWrappers:function(){return d},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){a.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};i(n.prototype,l.Mixin,m),r.addPoolingTo(n),t.exports=n},{"./CallbackQueue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CallbackQueue.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./ReactPutListenerQueue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPutListenerQueue.js","./Transaction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Transaction.js","./emptyFunction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdateQueue.js":[function(e,t,o){(function(o){"use strict";function n(e){e!==a.currentlyMountingInstance&&c.enqueueUpdate(e)}function r(e,t){"production"!==o.env.NODE_ENV?p(null==s.current,"%s(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.",t):p(null==s.current);var n=i.get(e);return n?n===a.currentlyUnmountingInstance?null:n:("production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?d(!t,"%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op.",t,t):null),null)}var a=e("./ReactLifeCycle"),s=e("./ReactCurrentOwner"),l=e("./ReactElement"),i=e("./ReactInstanceMap"),c=e("./ReactUpdates"),u=e("./Object.assign"),p=e("./invariant"),d=e("./warning"),m={enqueueCallback:function(e,t){"production"!==o.env.NODE_ENV?p("function"==typeof t,"enqueueCallback(...): You called `setProps`, `replaceProps`, `setState`, `replaceState`, or `forceUpdate` with a callback that isn't callable."):p("function"==typeof t);var s=r(e);return s&&s!==a.currentlyMountingInstance?(s._pendingCallbacks?s._pendingCallbacks.push(t):s._pendingCallbacks=[t],void n(s)):null},enqueueCallbackInternal:function(e,t){"production"!==o.env.NODE_ENV?p("function"==typeof t,"enqueueCallback(...): You called `setProps`, `replaceProps`, `setState`, `replaceState`, or `forceUpdate` with a callback that isn't callable."):p("function"==typeof t),e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],n(e)},enqueueForceUpdate:function(e){var t=r(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,n(t))},enqueueReplaceState:function(e,t){var o=r(e,"replaceState");o&&(o._pendingStateQueue=[t],o._pendingReplaceState=!0,n(o))},enqueueSetState:function(e,t){var o=r(e,"setState");if(o){var a=o._pendingStateQueue||(o._pendingStateQueue=[]);a.push(t),n(o)}},enqueueSetProps:function(e,t){var a=r(e,"setProps");if(a){"production"!==o.env.NODE_ENV?p(a._isTopLevel,"setProps(...): You called `setProps` on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's `render` method to pass the correct value as props to the component where it is created."):p(a._isTopLevel);var s=a._pendingElement||a._currentElement,i=u({},s.props,t);a._pendingElement=l.cloneAndReplaceProps(s,i),n(a)}},enqueueReplaceProps:function(e,t){var a=r(e,"replaceProps");if(a){"production"!==o.env.NODE_ENV?p(a._isTopLevel,"replaceProps(...): You called `replaceProps` on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's `render` method to pass the correct value as props to the component where it is created."):p(a._isTopLevel);var s=a._pendingElement||a._currentElement;a._pendingElement=l.cloneAndReplaceProps(s,t),n(a)}},enqueueElementInternal:function(e,t){e._pendingElement=t,n(e)}};t.exports=m}).call(this,e("_process"))},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactInstanceMap":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceMap.js","./ReactLifeCycle":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactLifeCycle.js","./ReactUpdates":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactUpdates.js":[function(e,t,o){(function(o){"use strict";function n(){"production"!==o.env.NODE_ENV?v(j.ReactReconcileTransaction&&w,"ReactUpdates: must inject a reconcile transaction class and batching strategy"):v(j.ReactReconcileTransaction&&w)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null, this.callbackQueue=u.getPooled(),this.reconcileTransaction=j.ReactReconcileTransaction.getPooled()}function a(e,t,o,r,a){n(),w.batchedUpdates(e,t,o,r,a)}function s(e,t){return e._mountOrder-t._mountOrder}function l(e){var t=e.dirtyComponentsLength;"production"!==o.env.NODE_ENV?v(t===_.length,"Expected flush transaction's stored dirty-components length (%s) to match dirty-components array length (%s).",t,_.length):v(t===_.length),_.sort(s);for(var n=0;t>n;n++){var r=_[n],a=r._pendingCallbacks;if(r._pendingCallbacks=null,b.performUpdateIfNecessary(r,e.reconcileTransaction),a)for(var l=0;l<a.length;l++)e.callbackQueue.enqueue(a[l],r.getPublicInstance())}}function i(e){return n(),"production"!==o.env.NODE_ENV?E(null==d.current,"enqueueUpdate(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate."):null,w.isBatchingUpdates?void _.push(e):void w.batchedUpdates(i,e)}function c(e,t){"production"!==o.env.NODE_ENV?v(w.isBatchingUpdates,"ReactUpdates.asap: Can't enqueue an asap callback in a context whereupdates are not being batched."):v(w.isBatchingUpdates),y.enqueue(e,t),g=!0}var u=e("./CallbackQueue"),p=e("./PooledClass"),d=e("./ReactCurrentOwner"),m=e("./ReactPerf"),b=e("./ReactReconciler"),h=e("./Transaction"),f=e("./Object.assign"),v=e("./invariant"),E=e("./warning"),_=[],y=u.getPooled(),g=!1,w=null,C={initialize:function(){this.dirtyComponentsLength=_.length},close:function(){this.dirtyComponentsLength!==_.length?(_.splice(0,this.dirtyComponentsLength),N()):_.length=0}},R={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},k=[C,R];f(r.prototype,h.Mixin,{getTransactionWrappers:function(){return k},destructor:function(){this.dirtyComponentsLength=null,u.release(this.callbackQueue),this.callbackQueue=null,j.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,o){return h.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,o)}}),p.addPoolingTo(r);var N=function(){for(;_.length||g;){if(_.length){var e=r.getPooled();e.perform(l,null,e),r.release(e)}if(g){g=!1;var t=y;y=u.getPooled(),t.notifyAll(),u.release(t)}}};N=m.measure("ReactUpdates","flushBatchedUpdates",N);var O={injectReconcileTransaction:function(e){"production"!==o.env.NODE_ENV?v(e,"ReactUpdates: must provide a reconcile transaction class"):v(e),j.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){"production"!==o.env.NODE_ENV?v(e,"ReactUpdates: must provide a batching strategy"):v(e),"production"!==o.env.NODE_ENV?v("function"==typeof e.batchedUpdates,"ReactUpdates: must provide a batchedUpdates() function"):v("function"==typeof e.batchedUpdates),"production"!==o.env.NODE_ENV?v("boolean"==typeof e.isBatchingUpdates,"ReactUpdates: must provide an isBatchingUpdates boolean attribute"):v("boolean"==typeof e.isBatchingUpdates),w=e}},j={ReactReconcileTransaction:null,batchedUpdates:a,enqueueUpdate:i,flushBatchedUpdates:N,injection:O,asap:c};t.exports=j}).call(this,e("_process"))},{"./CallbackQueue":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CallbackQueue.js","./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./ReactPerf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactPerf.js","./ReactReconciler":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactReconciler.js","./Transaction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Transaction.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SVGDOMPropertyConfig.js":[function(e,t,o){"use strict";var n=e("./DOMProperty"),r=n.injection.MUST_USE_ATTRIBUTE,a={Properties:{cx:r,cy:r,d:r,dx:r,dy:r,fill:r,fillOpacity:r,fontFamily:r,fontSize:r,fx:r,fy:r,gradientTransform:r,gradientUnits:r,markerEnd:r,markerMid:r,markerStart:r,offset:r,opacity:r,patternContentUnits:r,patternUnits:r,points:r,preserveAspectRatio:r,r:r,rx:r,ry:r,spreadMethod:r,stopColor:r,stopOpacity:r,stroke:r,strokeDasharray:r,strokeLinecap:r,strokeOpacity:r,strokeWidth:r,textAnchor:r,transform:r,version:r,viewBox:r,x1:r,x2:r,x:r,y1:r,y2:r,y:r},DOMAttributeNames:{fillOpacity:"fill-opacity",fontFamily:"font-family",fontSize:"font-size",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",patternContentUnits:"patternContentUnits",patternUnits:"patternUnits",preserveAspectRatio:"preserveAspectRatio",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeDasharray:"stroke-dasharray",strokeLinecap:"stroke-linecap",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"}};t.exports=a},{"./DOMProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/DOMProperty.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SelectEventPlugin.js":[function(e,t,o){"use strict";function n(e){if("selectionStart"in e&&l.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var o=document.selection.createRange();return{parentElement:o.parentElement(),text:o.text,top:o.boundingTop,left:o.boundingLeft}}}function r(e){if(E||null==h||h!==c())return null;var t=n(h);if(!v||!d(v,t)){v=t;var o=i.getPooled(b.select,f,e);return o.type="select",o.target=h,s.accumulateTwoPhaseDispatches(o),o}}var a=e("./EventConstants"),s=e("./EventPropagators"),l=e("./ReactInputSelection"),i=e("./SyntheticEvent"),c=e("./getActiveElement"),u=e("./isTextInputElement"),p=e("./keyOf"),d=e("./shallowEqual"),m=a.topLevelTypes,b={select:{phasedRegistrationNames:{bubbled:p({onSelect:null}),captured:p({onSelectCapture:null})},dependencies:[m.topBlur,m.topContextMenu,m.topFocus,m.topKeyDown,m.topMouseDown,m.topMouseUp,m.topSelectionChange]}},h=null,f=null,v=null,E=!1,_={eventTypes:b,extractEvents:function(e,t,o,n){switch(e){case m.topFocus:(u(t)||"true"===t.contentEditable)&&(h=t,f=o,v=null);break;case m.topBlur:h=null,f=null,v=null;break;case m.topMouseDown:E=!0;break;case m.topContextMenu:case m.topMouseUp:return E=!1,r(n);case m.topSelectionChange:case m.topKeyDown:case m.topKeyUp:return r(n)}}};t.exports=_},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./EventPropagators":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPropagators.js","./ReactInputSelection":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInputSelection.js","./SyntheticEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticEvent.js","./getActiveElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getActiveElement.js","./isTextInputElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isTextInputElement.js","./keyOf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js","./shallowEqual":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/shallowEqual.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ServerReactRootIndex.js":[function(e,t,o){"use strict";var n=Math.pow(2,53),r={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};t.exports=r},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SimpleEventPlugin.js":[function(e,t,o){(function(o){"use strict";var n=e("./EventConstants"),r=e("./EventPluginUtils"),a=e("./EventPropagators"),s=e("./SyntheticClipboardEvent"),l=e("./SyntheticEvent"),i=e("./SyntheticFocusEvent"),c=e("./SyntheticKeyboardEvent"),u=e("./SyntheticMouseEvent"),p=e("./SyntheticDragEvent"),d=e("./SyntheticTouchEvent"),m=e("./SyntheticUIEvent"),b=e("./SyntheticWheelEvent"),h=e("./getEventCharCode"),f=e("./invariant"),v=e("./keyOf"),E=e("./warning"),_=n.topLevelTypes,y={blur:{phasedRegistrationNames:{bubbled:v({onBlur:!0}),captured:v({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:v({onClick:!0}),captured:v({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:v({onContextMenu:!0}),captured:v({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:v({onCopy:!0}),captured:v({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:v({onCut:!0}),captured:v({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:v({onDoubleClick:!0}),captured:v({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:v({onDrag:!0}),captured:v({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:v({onDragEnd:!0}),captured:v({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:v({onDragEnter:!0}),captured:v({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:v({onDragExit:!0}),captured:v({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:v({onDragLeave:!0}),captured:v({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:v({onDragOver:!0}),captured:v({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:v({onDragStart:!0}),captured:v({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:v({onDrop:!0}),captured:v({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:v({onFocus:!0}),captured:v({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:v({onInput:!0}),captured:v({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:v({onKeyDown:!0}),captured:v({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:v({onKeyPress:!0}),captured:v({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:v({onKeyUp:!0}),captured:v({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:v({onLoad:!0}),captured:v({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:v({onError:!0}),captured:v({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:v({onMouseDown:!0}),captured:v({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:v({onMouseMove:!0}),captured:v({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:v({onMouseOut:!0}),captured:v({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:v({onMouseOver:!0}),captured:v({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:v({onMouseUp:!0}),captured:v({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:v({onPaste:!0}),captured:v({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:v({onReset:!0}),captured:v({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:v({onScroll:!0}),captured:v({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:v({onSubmit:!0}),captured:v({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:v({onTouchCancel:!0}),captured:v({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:v({onTouchEnd:!0}),captured:v({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:v({onTouchMove:!0}),captured:v({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:v({onTouchStart:!0}),captured:v({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:v({onWheel:!0}),captured:v({onWheelCapture:!0})}}},g={topBlur:y.blur,topClick:y.click,topContextMenu:y.contextMenu,topCopy:y.copy,topCut:y.cut,topDoubleClick:y.doubleClick,topDrag:y.drag,topDragEnd:y.dragEnd,topDragEnter:y.dragEnter,topDragExit:y.dragExit,topDragLeave:y.dragLeave,topDragOver:y.dragOver,topDragStart:y.dragStart,topDrop:y.drop,topError:y.error,topFocus:y.focus,topInput:y.input,topKeyDown:y.keyDown,topKeyPress:y.keyPress,topKeyUp:y.keyUp,topLoad:y.load,topMouseDown:y.mouseDown,topMouseMove:y.mouseMove,topMouseOut:y.mouseOut,topMouseOver:y.mouseOver,topMouseUp:y.mouseUp,topPaste:y.paste,topReset:y.reset,topScroll:y.scroll,topSubmit:y.submit,topTouchCancel:y.touchCancel,topTouchEnd:y.touchEnd,topTouchMove:y.touchMove,topTouchStart:y.touchStart,topWheel:y.wheel};for(var w in g)g[w].dependencies=[w];var C={eventTypes:y,executeDispatch:function(e,t,n){var a=r.executeDispatch(e,t,n);"production"!==o.env.NODE_ENV?E("boolean"!=typeof a,"Returning `false` from an event handler is deprecated and will be ignored in a future release. Instead, manually call e.stopPropagation() or e.preventDefault(), as appropriate."):null,a===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var v=g[e];if(!v)return null;var E;switch(e){case _.topInput:case _.topLoad:case _.topError:case _.topReset:case _.topSubmit:E=l;break;case _.topKeyPress:if(0===h(r))return null;case _.topKeyDown:case _.topKeyUp:E=c;break;case _.topBlur:case _.topFocus:E=i;break;case _.topClick:if(2===r.button)return null;case _.topContextMenu:case _.topDoubleClick:case _.topMouseDown:case _.topMouseMove:case _.topMouseOut:case _.topMouseOver:case _.topMouseUp:E=u;break;case _.topDrag:case _.topDragEnd:case _.topDragEnter:case _.topDragExit:case _.topDragLeave:case _.topDragOver:case _.topDragStart:case _.topDrop:E=p;break;case _.topTouchCancel:case _.topTouchEnd:case _.topTouchMove:case _.topTouchStart:E=d;break;case _.topScroll:E=m;break;case _.topWheel:E=b;break;case _.topCopy:case _.topCut:case _.topPaste:E=s}"production"!==o.env.NODE_ENV?f(E,"SimpleEventPlugin: Unhandled event type, `%s`.",e):f(E);var y=E.getPooled(v,n,r);return a.accumulateTwoPhaseDispatches(y),y}};t.exports=C}).call(this,e("_process"))},{"./EventConstants":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventConstants.js","./EventPluginUtils":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPluginUtils.js","./EventPropagators":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/EventPropagators.js","./SyntheticClipboardEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticClipboardEvent.js","./SyntheticDragEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticDragEvent.js","./SyntheticEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticEvent.js","./SyntheticFocusEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticFocusEvent.js","./SyntheticKeyboardEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticKeyboardEvent.js","./SyntheticMouseEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticMouseEvent.js","./SyntheticTouchEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticTouchEvent.js","./SyntheticUIEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticUIEvent.js","./SyntheticWheelEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticWheelEvent.js","./getEventCharCode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventCharCode.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./keyOf":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticClipboardEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticEvent"),a={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};r.augmentClass(n,a),t.exports=n},{"./SyntheticEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticEvent.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticCompositionEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticEvent"),a={data:null};r.augmentClass(n,a),t.exports=n},{"./SyntheticEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticEvent.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticDragEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticMouseEvent"),a={dataTransfer:null};r.augmentClass(n,a),t.exports=n},{"./SyntheticMouseEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticMouseEvent.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticEvent.js":[function(e,t,o){"use strict";function n(e,t,o){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=o;var n=this.constructor.Interface;for(var r in n)if(n.hasOwnProperty(r)){var a=n[r];a?this[r]=a(o):this[r]=o[r]}var l=null!=o.defaultPrevented?o.defaultPrevented:o.returnValue===!1;l?this.isDefaultPrevented=s.thatReturnsTrue:this.isDefaultPrevented=s.thatReturnsFalse,this.isPropagationStopped=s.thatReturnsFalse}var r=e("./PooledClass"),a=e("./Object.assign"),s=e("./emptyFunction"),l=e("./getEventTarget"),i={type:null,target:l,currentTarget:s.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};a(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=s.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=s.thatReturnsTrue},persist:function(){this.isPersistent=s.thatReturnsTrue},isPersistent:s.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=i,n.augmentClass=function(e,t){var o=this,n=Object.create(o.prototype);a(n,e.prototype),e.prototype=n,e.prototype.constructor=e,e.Interface=a({},o.Interface,t),e.augmentClass=o.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(n,r.threeArgumentPooler),t.exports=n},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./PooledClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/PooledClass.js","./emptyFunction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js","./getEventTarget":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventTarget.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticFocusEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticUIEvent"),a={relatedTarget:null};r.augmentClass(n,a),t.exports=n},{"./SyntheticUIEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticUIEvent.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticInputEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticEvent"),a={data:null};r.augmentClass(n,a),t.exports=n},{"./SyntheticEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticEvent.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticKeyboardEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticUIEvent"),a=e("./getEventCharCode"),s=e("./getEventKey"),l=e("./getEventModifierState"),i={key:s,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:l,charCode:function(e){return"keypress"===e.type?a(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?a(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};r.augmentClass(n,i),t.exports=n},{"./SyntheticUIEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticUIEvent.js","./getEventCharCode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventCharCode.js","./getEventKey":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventKey.js","./getEventModifierState":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventModifierState.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticMouseEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticUIEvent"),a=e("./ViewportMetrics"),s=e("./getEventModifierState"),l={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:s,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+a.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+a.currentScrollTop}};r.augmentClass(n,l),t.exports=n},{"./SyntheticUIEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticUIEvent.js","./ViewportMetrics":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ViewportMetrics.js","./getEventModifierState":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventModifierState.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticTouchEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticUIEvent"),a=e("./getEventModifierState"),s={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:a};r.augmentClass(n,s),t.exports=n},{"./SyntheticUIEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticUIEvent.js","./getEventModifierState":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventModifierState.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticUIEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticEvent"),a=e("./getEventTarget"),s={view:function(e){if(e.view)return e.view;var t=a(e);if(null!=t&&t.window===t)return t;var o=t.ownerDocument;return o?o.defaultView||o.parentWindow:window},detail:function(e){return e.detail||0}};r.augmentClass(n,s),t.exports=n},{"./SyntheticEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticEvent.js","./getEventTarget":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventTarget.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticWheelEvent.js":[function(e,t,o){"use strict";function n(e,t,o){r.call(this,e,t,o)}var r=e("./SyntheticMouseEvent"),a={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};r.augmentClass(n,a),t.exports=n},{"./SyntheticMouseEvent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/SyntheticMouseEvent.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Transaction.js":[function(e,t,o){(function(o){"use strict";var n=e("./invariant"),r={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,r,a,s,l,i,c){"production"!==o.env.NODE_ENV?n(!this.isInTransaction(),"Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction."):n(!this.isInTransaction());var u,p;try{this._isInTransaction=!0,u=!0,this.initializeAll(0),p=e.call(t,r,a,s,l,i,c),u=!1}finally{try{if(u)try{this.closeAll(0)}catch(d){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return p},initializeAll:function(e){for(var t=this.transactionWrappers,o=e;o<t.length;o++){var n=t[o];try{this.wrapperInitData[o]=a.OBSERVED_ERROR,this.wrapperInitData[o]=n.initialize?n.initialize.call(this):null}finally{if(this.wrapperInitData[o]===a.OBSERVED_ERROR)try{this.initializeAll(o+1)}catch(r){}}}},closeAll:function(e){"production"!==o.env.NODE_ENV?n(this.isInTransaction(),"Transaction.closeAll(): Cannot close transaction when none are open."):n(this.isInTransaction());for(var t=this.transactionWrappers,r=e;r<t.length;r++){var s,l=t[r],i=this.wrapperInitData[r];try{s=!0,i!==a.OBSERVED_ERROR&&l.close&&l.close.call(this,i),s=!1}finally{if(s)try{this.closeAll(r+1)}catch(c){}}}this.wrapperInitData.length=0}},a={Mixin:r,OBSERVED_ERROR:{}};t.exports=a}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ViewportMetrics.js":[function(e,t,o){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){n.currentScrollLeft=e.x,n.currentScrollTop=e.y}};t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/accumulateInto.js":[function(e,t,o){(function(o){"use strict";function n(e,t){if("production"!==o.env.NODE_ENV?r(null!=t,"accumulateInto(...): Accumulated items must not be null or undefined."):r(null!=t),null==e)return t;var n=Array.isArray(e),a=Array.isArray(t);return n&&a?(e.push.apply(e,t),e):n?(e.push(t),e):a?[e].concat(t):[e,t]}var r=e("./invariant");t.exports=n}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/adler32.js":[function(e,t,o){"use strict";function n(e){for(var t=1,o=0,n=0;n<e.length;n++)t=(t+e.charCodeAt(n))%r,o=(o+t)%r;return t|o<<16}var r=65521;t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/camelize.js":[function(e,t,o){function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/camelizeStyleName.js":[function(e,t,o){"use strict";function n(e){return r(e.replace(a,"ms-"))}var r=e("./camelize"),a=/^-ms-/;t.exports=n},{"./camelize":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/camelize.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/containsNode.js":[function(e,t,o){function n(e,t){return e&&t?e===t?!0:r(e)?!1:r(t)?n(e,t.parentNode):e.contains?e.contains(t):e.compareDocumentPosition?!!(16&e.compareDocumentPosition(t)):!1:!1}var r=e("./isTextNode");t.exports=n},{"./isTextNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isTextNode.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/createArrayFromMixed.js":[function(e,t,o){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function r(e){return n(e)?Array.isArray(e)?e.slice():a(e):[e]}var a=e("./toArray");t.exports=r},{"./toArray":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/toArray.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/createFullPageComponent.js":[function(e,t,o){(function(o){"use strict";function n(e){var t=a.createFactory(e),n=r.createClass({tagName:e.toUpperCase(),displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){"production"!==o.env.NODE_ENV?s(!1,"%s tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.",this.constructor.displayName):s(!1)},render:function(){return t(this.props)}});return n}var r=e("./ReactClass"),a=e("./ReactElement"),s=e("./invariant");t.exports=n}).call(this,e("_process"))},{"./ReactClass":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactClass.js","./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/createNodesFromMarkup.js":[function(e,t,o){(function(o){function n(e){var t=e.match(u);return t&&t[1].toLowerCase()}function r(e,t){var r=c;"production"!==o.env.NODE_ENV?i(!!c,"createNodesFromMarkup dummy not initialized"):i(!!c);var a=n(e),u=a&&l(a);if(u){r.innerHTML=u[1]+e+u[2];for(var p=u[0];p--;)r=r.lastChild}else r.innerHTML=e;var d=r.getElementsByTagName("script");d.length&&("production"!==o.env.NODE_ENV?i(t,"createNodesFromMarkup(...): Unexpected <script> element rendered."):i(t),s(d).forEach(t));for(var m=s(r.childNodes);r.lastChild;)r.removeChild(r.lastChild);return m}var a=e("./ExecutionEnvironment"),s=e("./createArrayFromMixed"),l=e("./getMarkupWrap"),i=e("./invariant"),c=a.canUseDOM?document.createElement("div"):null,u=/^\s*<(\w+)/;t.exports=r}).call(this,e("_process"))},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./createArrayFromMixed":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/createArrayFromMixed.js","./getMarkupWrap":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getMarkupWrap.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/dangerousStyleValue.js":[function(e,t,o){"use strict";function n(e,t){var o=null==t||"boolean"==typeof t||""===t;if(o)return"";var n=isNaN(t);return n||0===t||a.hasOwnProperty(e)&&a[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var r=e("./CSSProperty"),a=r.isUnitlessNumber;t.exports=n},{"./CSSProperty":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/CSSProperty.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js":[function(e,t,o){function n(e){return function(){return e}}function r(){}r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},t.exports=r},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyObject.js":[function(e,t,o){ (function(e){"use strict";var o={};"production"!==e.env.NODE_ENV&&Object.freeze(o),t.exports=o}).call(this,e("_process"))},{_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/escapeTextContentForBrowser.js":[function(e,t,o){"use strict";function n(e){return a[e]}function r(e){return(""+e).replace(s,n)}var a={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},s=/[&><"']/g;t.exports=r},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/findDOMNode.js":[function(e,t,o){(function(o){"use strict";function n(e){if("production"!==o.env.NODE_ENV){var t=r.current;null!==t&&("production"!==o.env.NODE_ENV?c(t._warnedAboutRefsInRender,"%s is accessing getDOMNode or findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",t.getName()||"A component"):null,t._warnedAboutRefsInRender=!0)}return null==e?null:i(e)?e:a.has(e)?s.getNodeFromInstance(e):("production"!==o.env.NODE_ENV?l(null==e.render||"function"!=typeof e.render,"Component (with keys: %s) contains `render` method but is not mounted in the DOM",Object.keys(e)):l(null==e.render||"function"!=typeof e.render),void("production"!==o.env.NODE_ENV?l(!1,"Element appears to be neither ReactComponent nor DOMNode (keys: %s)",Object.keys(e)):l(!1)))}var r=e("./ReactCurrentOwner"),a=e("./ReactInstanceMap"),s=e("./ReactMount"),l=e("./invariant"),i=e("./isNode"),c=e("./warning");t.exports=n}).call(this,e("_process"))},{"./ReactCurrentOwner":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCurrentOwner.js","./ReactInstanceMap":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceMap.js","./ReactMount":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactMount.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./isNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isNode.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/flattenChildren.js":[function(e,t,o){(function(o){"use strict";function n(e,t,n){var r=e,a=!r.hasOwnProperty(n);"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?s(a,"flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.",n):null),a&&null!=t&&(r[n]=t)}function r(e){if(null==e)return e;var t={};return a(e,n,t),t}var a=e("./traverseAllChildren"),s=e("./warning");t.exports=r}).call(this,e("_process"))},{"./traverseAllChildren":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/traverseAllChildren.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/focusNode.js":[function(e,t,o){"use strict";function n(e){try{e.focus()}catch(t){}}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/forEachAccumulated.js":[function(e,t,o){"use strict";var n=function(e,t,o){Array.isArray(e)?e.forEach(t,o):e&&t.call(o,e)};t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getActiveElement.js":[function(e,t,o){function n(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventCharCode.js":[function(e,t,o){"use strict";function n(e){var t,o=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===o&&(t=13)):t=o,t>=32||13===t?t:0}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventKey.js":[function(e,t,o){"use strict";function n(e){if(e.key){var t=a[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var o=r(e);return 13===o?"Enter":String.fromCharCode(o)}return"keydown"===e.type||"keyup"===e.type?s[e.keyCode]||"Unidentified":""}var r=e("./getEventCharCode"),a={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},s={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=n},{"./getEventCharCode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventCharCode.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventModifierState.js":[function(e,t,o){"use strict";function n(e){var t=this,o=t.nativeEvent;if(o.getModifierState)return o.getModifierState(e);var n=a[e];return n?!!o[n]:!1}function r(e){return n}var a={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=r},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getEventTarget.js":[function(e,t,o){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getIteratorFn.js":[function(e,t,o){"use strict";function n(e){var t=e&&(r&&e[r]||e[a]);return"function"==typeof t?t:void 0}var r="function"==typeof Symbol&&Symbol.iterator,a="@@iterator";t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getMarkupWrap.js":[function(e,t,o){(function(o){function n(e){return"production"!==o.env.NODE_ENV?a(!!s,"Markup wrapping node not initialized"):a(!!s),d.hasOwnProperty(e)||(e="*"),l.hasOwnProperty(e)||("*"===e?s.innerHTML="<link />":s.innerHTML="<"+e+"></"+e+">",l[e]=!s.firstChild),l[e]?d[e]:null}var r=e("./ExecutionEnvironment"),a=e("./invariant"),s=r.canUseDOM?document.createElement("div"):null,l={circle:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},i=[1,'<select multiple="true">',"</select>"],c=[1,"<table>","</table>"],u=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,"<svg>","</svg>"],d={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:i,option:i,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:u,th:u,circle:p,defs:p,ellipse:p,g:p,line:p,linearGradient:p,path:p,polygon:p,polyline:p,radialGradient:p,rect:p,stop:p,text:p};t.exports=n}).call(this,e("_process"))},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getNodeForCharacterOffset.js":[function(e,t,o){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function a(e,t){for(var o=n(e),a=0,s=0;o;){if(3===o.nodeType){if(s=a+o.textContent.length,t>=a&&s>=t)return{node:o,offset:t-a};a=s}o=n(r(o))}}t.exports=a},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getReactRootElementInContainer.js":[function(e,t,o){"use strict";function n(e){return e?e.nodeType===r?e.documentElement:e.firstChild:null}var r=9;t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getTextContentAccessor.js":[function(e,t,o){"use strict";function n(){return!a&&r.canUseDOM&&(a="textContent"in document.documentElement?"textContent":"innerText"),a}var r=e("./ExecutionEnvironment"),a=null;t.exports=n},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getUnboundedScrollPosition.js":[function(e,t,o){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/hyphenate.js":[function(e,t,o){function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/hyphenateStyleName.js":[function(e,t,o){"use strict";function n(e){return r(e).replace(a,"-ms-")}var r=e("./hyphenate"),a=/^ms-/;t.exports=n},{"./hyphenate":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/hyphenate.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/instantiateReactComponent.js":[function(e,t,o){(function(o){"use strict";function n(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function r(e,t){var r;if(null!==e&&e!==!1||(e=s.emptyElement),"object"==typeof e){var a=e;"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?u(a&&("function"==typeof a.type||"string"==typeof a.type),"Only functions or strings can be mounted as React components."):null),r=t===a.type&&"string"==typeof a.type?l.createInternalComponent(a):n(a.type)?new a.type(a):new p}else"string"==typeof e||"number"==typeof e?r=l.createInstanceForText(e):"production"!==o.env.NODE_ENV?c(!1,"Encountered invalid React node of type %s",typeof e):c(!1);return"production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?u("function"==typeof r.construct&&"function"==typeof r.mountComponent&&"function"==typeof r.receiveComponent&&"function"==typeof r.unmountComponent,"Only React Components can be mounted."):null),r.construct(e),r._mountIndex=0,r._mountImage=null,"production"!==o.env.NODE_ENV&&(r._isOwnerNecessary=!1,r._warnedAboutRefsInRender=!1),"production"!==o.env.NODE_ENV&&Object.preventExtensions&&Object.preventExtensions(r),r}var a=e("./ReactCompositeComponent"),s=e("./ReactEmptyComponent"),l=e("./ReactNativeComponent"),i=e("./Object.assign"),c=e("./invariant"),u=e("./warning"),p=function(){};i(p.prototype,a.Mixin,{_instantiateReactComponent:r}),t.exports=r}).call(this,e("_process"))},{"./Object.assign":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/Object.assign.js","./ReactCompositeComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactCompositeComponent.js","./ReactEmptyComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactEmptyComponent.js","./ReactNativeComponent":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactNativeComponent.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js":[function(e,t,o){(function(e){"use strict";var o=function(t,o,n,r,a,s,l,i){if("production"!==e.env.NODE_ENV&&void 0===o)throw new Error("invariant requires an error message argument");if(!t){var c;if(void 0===o)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[n,r,a,s,l,i],p=0;c=new Error("Invariant Violation: "+o.replace(/%s/g,function(){return u[p++]}))}throw c.framesToPop=1,c}};t.exports=o}).call(this,e("_process"))},{_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isEventSupported.js":[function(e,t,o){"use strict";function n(e,t){if(!a.canUseDOM||t&&!("addEventListener"in document))return!1;var o="on"+e,n=o in document;if(!n){var s=document.createElement("div");s.setAttribute(o,"return;"),n="function"==typeof s[o]}return!n&&r&&"wheel"===e&&(n=document.implementation.hasFeature("Events.wheel","3.0")),n}var r,a=e("./ExecutionEnvironment");a.canUseDOM&&(r=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=n},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isNode.js":[function(e,t,o){function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isTextInputElement.js":[function(e,t,o){"use strict";function n(e){return e&&("INPUT"===e.nodeName&&r[e.type]||"TEXTAREA"===e.nodeName)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isTextNode.js":[function(e,t,o){function n(e){return r(e)&&3==e.nodeType}var r=e("./isNode");t.exports=n},{"./isNode":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/isNode.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyMirror.js":[function(e,t,o){(function(o){"use strict";var n=e("./invariant"),r=function(e){var t,r={};"production"!==o.env.NODE_ENV?n(e instanceof Object&&!Array.isArray(e),"keyMirror(...): Argument must be an object."):n(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(r[t]=t);return r};t.exports=r}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/keyOf.js":[function(e,t,o){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/mapObject.js":[function(e,t,o){"use strict";function n(e,t,o){if(!e)return null;var n={};for(var a in e)r.call(e,a)&&(n[a]=t.call(o,e[a],a,e));return n}var r=Object.prototype.hasOwnProperty;t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/memoizeStringOnly.js":[function(e,t,o){"use strict";function n(e){var t={};return function(o){return t.hasOwnProperty(o)||(t[o]=e.call(this,o)),t[o]}}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/onlyChild.js":[function(e,t,o){(function(o){"use strict";function n(e){return"production"!==o.env.NODE_ENV?a(r.isValidElement(e),"onlyChild must be passed a children with exactly one child."):a(r.isValidElement(e)),e}var r=e("./ReactElement"),a=e("./invariant");t.exports=n}).call(this,e("_process"))},{"./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/performance.js":[function(e,t,o){"use strict";var n,r=e("./ExecutionEnvironment");r.canUseDOM&&(n=window.performance||window.msPerformance||window.webkitPerformance),t.exports=n||{}},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/performanceNow.js":[function(e,t,o){var n=e("./performance");n&&n.now||(n=Date);var r=n.now.bind(n);t.exports=r},{"./performance":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/performance.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/quoteAttributeValueForBrowser.js":[function(e,t,o){"use strict";function n(e){return'"'+r(e)+'"'}var r=e("./escapeTextContentForBrowser");t.exports=n},{"./escapeTextContentForBrowser":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/escapeTextContentForBrowser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/setInnerHTML.js":[function(e,t,o){"use strict";var n=e("./ExecutionEnvironment"),r=/^[ \r\n\t\f]/,a=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,s=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(s=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),n.canUseDOM){var l=document.createElement("div");l.innerHTML=" ",""===l.innerHTML&&(s=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),r.test(t)||"<"===t[0]&&a.test(t)){e.innerHTML="\ufeff"+t;var o=e.firstChild;1===o.data.length?e.removeChild(o):o.deleteData(0,1)}else e.innerHTML=t})}t.exports=s},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/setTextContent.js":[function(e,t,o){"use strict";var n=e("./ExecutionEnvironment"),r=e("./escapeTextContentForBrowser"),a=e("./setInnerHTML"),s=function(e,t){e.textContent=t};n.canUseDOM&&("textContent"in document.documentElement||(s=function(e,t){a(e,r(t))})),t.exports=s},{"./ExecutionEnvironment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ExecutionEnvironment.js","./escapeTextContentForBrowser":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/escapeTextContentForBrowser.js","./setInnerHTML":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/setInnerHTML.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/shallowEqual.js":[function(e,t,o){"use strict";function n(e,t){if(e===t)return!0;var o;for(o in e)if(e.hasOwnProperty(o)&&(!t.hasOwnProperty(o)||e[o]!==t[o]))return!1;for(o in t)if(t.hasOwnProperty(o)&&!e.hasOwnProperty(o))return!1;return!0}t.exports=n},{}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/shouldUpdateReactComponent.js":[function(e,t,o){(function(o){"use strict";function n(e,t){if(null!=e&&null!=t){var n=typeof e,a=typeof t;if("string"===n||"number"===n)return"string"===a||"number"===a;if("object"===a&&e.type===t.type&&e.key===t.key){var s=e._owner===t._owner,l=null,i=null,c=null;return"production"!==o.env.NODE_ENV&&(s||(null!=e._owner&&null!=e._owner.getPublicInstance()&&null!=e._owner.getPublicInstance().constructor&&(l=e._owner.getPublicInstance().constructor.displayName),null!=t._owner&&null!=t._owner.getPublicInstance()&&null!=t._owner.getPublicInstance().constructor&&(i=t._owner.getPublicInstance().constructor.displayName),null!=t.type&&null!=t.type.displayName&&(c=t.type.displayName),null!=t.type&&"string"==typeof t.type&&(c=t.type),"string"==typeof t.type&&"input"!==t.type&&"textarea"!==t.type||(null!=e._owner&&e._owner._isOwnerNecessary===!1||null!=t._owner&&t._owner._isOwnerNecessary===!1)&&(null!=e._owner&&(e._owner._isOwnerNecessary=!0),null!=t._owner&&(t._owner._isOwnerNecessary=!0),"production"!==o.env.NODE_ENV?r(!1,"<%s /> is being rendered by both %s and %s using the same key (%s) in the same place. Currently, this means that they don't preserve state. This behavior should be very rare so we're considering deprecating it. Please contact the React team and explain your use case so that we can take that into consideration.",c||"Unknown Component",l||"[Unknown]",i||"[Unknown]",e.key):null))),s}}return!1}var r=e("./warning");t.exports=n}).call(this,e("_process"))},{"./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/toArray.js":[function(e,t,o){(function(o){function n(e){var t=e.length;if("production"!==o.env.NODE_ENV?r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e),"toArray: Array-like object expected"):r(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),"production"!==o.env.NODE_ENV?r("number"==typeof t,"toArray: Object needs a length property"):r("number"==typeof t),"production"!==o.env.NODE_ENV?r(0===t||t-1 in e,"toArray: Object should have keys for indices"):r(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var a=Array(t),s=0;t>s;s++)a[s]=e[s];return a}var r=e("./invariant");t.exports=n}).call(this,e("_process"))},{"./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/traverseAllChildren.js":[function(e,t,o){(function(o){"use strict";function n(e){return v[e]}function r(e,t){return e&&null!=e.key?s(e.key):t.toString(36)}function a(e){return(""+e).replace(E,n)}function s(e){return"$"+a(e)}function l(e,t,n,a,i){var p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||c.isValidElement(e))return a(i,e,""===t?h+r(e,0):t,n),1;var v,E,y,g=0;if(Array.isArray(e))for(var w=0;w<e.length;w++)v=e[w],E=(""!==t?t+f:h)+r(v,w),y=n+g,g+=l(v,E,y,a,i);else{var C=d(e);if(C){var R,k=C.call(e);if(C!==e.entries)for(var N=0;!(R=k.next()).done;)v=R.value,E=(""!==t?t+f:h)+r(v,N++),y=n+g,g+=l(v,E,y,a,i);else for("production"!==o.env.NODE_ENV&&("production"!==o.env.NODE_ENV?b(_,"Using Maps as children is not yet fully supported. It is an experimental feature that might be removed. Convert it to a sequence / iterable of keyed ReactElements instead."):null,_=!0);!(R=k.next()).done;){var O=R.value;O&&(v=O[1],E=(""!==t?t+f:h)+s(O[0])+f+r(v,0),y=n+g,g+=l(v,E,y,a,i))}}else if("object"===p){"production"!==o.env.NODE_ENV?m(1!==e.nodeType,"traverseAllChildren(...): Encountered an invalid child; DOM elements are not valid children of React components."):m(1!==e.nodeType);var j=u.extract(e);for(var D in j)j.hasOwnProperty(D)&&(v=j[D],E=(""!==t?t+f:h)+s(D)+f+r(v,0),y=n+g,g+=l(v,E,y,a,i))}}return g}function i(e,t,o){return null==e?0:l(e,"",0,t,o)}var c=e("./ReactElement"),u=e("./ReactFragment"),p=e("./ReactInstanceHandles"),d=e("./getIteratorFn"),m=e("./invariant"),b=e("./warning"),h=p.SEPARATOR,f=":",v={"=":"=0",".":"=1",":":"=2"},E=/[=.:]/g,_=!1;t.exports=i}).call(this,e("_process"))},{"./ReactElement":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactElement.js","./ReactFragment":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactFragment.js","./ReactInstanceHandles":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/ReactInstanceHandles.js","./getIteratorFn":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/getIteratorFn.js","./invariant":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/invariant.js","./warning":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/warning.js":[function(e,t,o){(function(o){"use strict";var n=e("./emptyFunction"),r=n;"production"!==o.env.NODE_ENV&&(r=function(e,t){for(var o=[],n=2,r=arguments.length;r>n;n++)o.push(arguments[n]);if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(t.length<10||/^[s\W]*$/.test(t))throw new Error("The warning format should be able to uniquely identify this warning. Please, use a more descriptive format than: "+t);if(0!==t.indexOf("Failed Composite propType: ")&&!e){var a=0,s="Warning: "+t.replace(/%s/g,function(){return o[a++]});console.warn(s);try{throw new Error(s)}catch(l){}}}),t.exports=r}).call(this,e("_process"))},{"./emptyFunction":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/emptyFunction.js",_process:"/home/allen/workspace/react-bootstrap-table/node_modules/browserify/node_modules/process/browser.js"}],"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js":[function(e,t,o){t.exports=e("./lib/React")},{"./lib/React":"/home/allen/workspace/react-bootstrap-table/node_modules/react/lib/React.js"}],"/home/allen/workspace/react-bootstrap-table/src/BootstrapTable.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function h(e,t,o){var n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n){var r=Object.getPrototypeOf(e);return null===r?void 0:h(r,t,o)}if("value"in n&&n.writable)return n.value;var a=n.get;if(void 0!==a)return a.call(o)},s=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=n(e("react")),c=n(e("classnames")),u=n(e("./Const")),p=n(e("./TableHeader")),d=n(e("./TableBody")),m=n(e("./pagination/PaginationList")),b=function(e){function t(e){if(l(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.state={data:this.props.data},this.props.cellEdit&&(this.props.cellEdit.__onCompleteEdit__=this.handleEditCell.bind(this),this.props.cellEdit.mode!==u.CELL_EDIT_NONE&&(this.props.selectRow.clickToSelect=!1)),this.sortTable=!1,this.order=u.SORT_DESC,this.sortField=null,this.keyField=null,this.props.children.forEach(function(e){if(e.props.dataSort&&(this.sortTable=!0),e.props.isKey){if(null!=this.keyField)throw"Error. Multiple key column be detected in TableHeaderColumn.";this.keyField=e.props.dataField}},this),null==this.keyField)throw"Error. No any key column defined in TableHeaderColumn. Use 'isKey={true}' to specify a unique column."}return s(t,e),r(t,{componentWillMount:{value:function(){this.props.pagination&&this.handlePaginationData(1,u.SIZE_PER_PAGE)}},componentDidMount:{value:function(){this._adjustHeaderWidth()}},componentDidUpdate:{value:function(){this._adjustHeaderWidth()}},render:{value:function(){var e=c("react-bs-table"),t={height:this.props.height},o=this.props.children.map(function(e,t){return{name:e.props.dataField,align:e.props.dataAlign,sort:e.props.dataSort,format:e.props.dataFormat,index:t}},this),n=this.renderPagination();return i.createElement("div",null,i.createElement("div",{ref:"table",style:t,className:e},i.createElement(p,{rowSelectType:this.props.selectRow.mode,onSort:this.handleSort.bind(this),onSelectAllRow:this.handleSelectAllRow.bind(this)},this.props.children),i.createElement(d,{data:this.state.data,columns:o,striped:this.props.striped,hover:this.props.hover,keyField:this.keyField,condensed:this.props.condensed,selectRow:this.props.selectRow,cellEdit:this.props.cellEdit,parentRender:!0})),i.createElement("div",null,n))}},handleSort:{value:function(e,t){this.order=e,this.sortField=t,this.setState({data:this._sort(this.state.data,e,t)})}},handlePaginationData:{value:function(e,t){for(var o=e*t-1,n=o-(t-1),r=[],a=n;o>=a&&(r.push(this.props.data[a]),a+1!=this.props.data.length);a++);this.sortTable&&null!=this.sortField&&(r=this._sort(r,this.order,this.sortField)),this.setState({data:r})}},handleSelectAllRow:{value:function(e){var t=e.currentTarget.checked;if(t){var o=this.props.data.map(function(e){return e[this.keyField]},this);this.props.selectRow.__onSelectAll__(o)}else this.props.selectRow.__onSelectAll__([])}},handleEditCell:{value:function(e,t,o){var n;this.props.children.forEach(function(e,t){return t==o?(n=e.props.dataField,!1):void 0}),this.state.data[t][n]=e,this.setState({data:this.state.data}),this.props.cellEdit.afterSaveCell&&this.props.cellEdit.afterSaveCell(this.state.data[t],n,e)}},_sort:{value:function(e,t,o){return e.sort(function(e,n){return t==u.SORT_ASC?e[o]>n[o]?-1:e[o]<n[o]?1:0:e[o]<n[o]?-1:e[o]>n[o]?1:0}),e}},_adjustHeaderWidth:{value:function(){this.refs.table.getDOMNode().childNodes[0].childNodes[0].style.width=this.refs.table.getDOMNode().childNodes[1].childNodes[0].offsetWidth-1+"px"}},renderPagination:{value:function(){return this.props.pagination?i.createElement(m,{changePage:this.handlePaginationData.bind(this),sizePerPage:u.SIZE_PER_PAGE,dataSize:this.props.data.length}):null}}}),t}(i.Component);b.propTypes={height:i.PropTypes.string,data:i.PropTypes.array,striped:i.PropTypes.bool,hover:i.PropTypes.bool,condensed:i.PropTypes.bool,pagination:i.PropTypes.bool,selectRow:i.PropTypes.shape({mode:i.PropTypes.string,bgColor:i.PropTypes.string,onSelect:i.PropTypes.func,onSelectAll:i.PropTypes.func,clickToSelect:i.PropTypes.bool}),cellEdit:i.PropTypes.shape({mode:i.PropTypes.string,blurToSave:i.PropTypes.bool,afterSaveCell:i.PropTypes.func})},b.defaultProps={height:"100%",striped:!1,hover:!1,condensed:!1,pagination:!1,selectRow:{mode:u.ROW_SELECT_NONE,bgColor:u.ROW_SELECT_BG_COLOR,onSelect:void 0,onSelectAll:void 0,clickToSelect:!1},cellEdit:{mode:u.CELL_EDIT_NONE,blurToSave:!1,afterSaveCell:void 0}},t.exports=b},{"./Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js","./TableBody":"/home/allen/workspace/react-bootstrap-table/src/TableBody.js","./TableHeader":"/home/allen/workspace/react-bootstrap-table/src/TableHeader.js","./pagination/PaginationList":"/home/allen/workspace/react-bootstrap-table/src/pagination/PaginationList.js",classnames:"/home/allen/workspace/react-bootstrap-table/node_modules/classnames/index.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/Const.js":[function(e,t,o){"use strict";t.exports={SORT_DESC:"desc",SORT_ASC:"asc",SIZE_PER_PAGE:10,SIZE_PER_LIST:5,NEXT_PAGE:">",LAST_PAGE:">>",PRE_PAGE:"<",FIRST_PAGE:"<<",ROW_SELECT_BG_COLOR:"",ROW_SELECT_NONE:"none",ROW_SELECT_SINGLE:"radio",ROW_SELECT_MULTI:"checkbox",CELL_EDIT_NONE:"none",CELL_EDIT_CLICK:"click",CELL_EDIT_DBCLICK:"dbclick"}},{}],"/home/allen/workspace/react-bootstrap-table/src/SelectRowHeaderColumn.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{ constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("react")),i=(n(e("classnames")),n(e("./Const")),function(e){function t(){s(this,t),null!=e&&e.apply(this,arguments)}return a(t,e),r(t,{render:{value:function(){var e={width:35};return l.createElement("th",{style:e},l.createElement("div",{className:"th-inner table-header-column"},this.props.children))}}}),t}(l.Component));t.exports=i},{"./Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js",classnames:"/home/allen/workspace/react-bootstrap-table/node_modules/classnames/index.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/TableBody.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function h(e,t,o){var n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n){var r=Object.getPrototypeOf(e);return null===r?void 0:h(r,t,o)}if("value"in n&&n.writable)return n.value;var a=n.get;if(void 0!==a)return a.call(o)},s=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=n(e("react")),c=n(e("./Const")),u=n(e("./TableRow")),p=n(e("./TableColumn")),d=n(e("./TableEditColumn")),m=n(e("classnames")),b=function(e){function t(e){l(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.state={currEditCell:null,selectedRowKey:[]},this.props.selectRow&&(this.props.selectRow.__onSelect__=this.handleSelectRow.bind(this),this.props.selectRow.__onSelectAll__=this.handleSelectAllRow.bind(this))}return s(t,e),r(t,{render:{value:function(){var e=m("table-container"),t=m("table","table-bordered",{"table-striped":this.props.striped,"table-hover":this.props.hover,"table-condensed":this.props.condensed}),o=this._isSelectRowDefined(),n=this.renderTableHeader(o),r=this.props.data.map(function(e,t){var n=this.props.columns.map(function(o,n){var r=e[o.name];if(this.props.parentRender||o.name===this.props.keyField||null==this.state.currEditCell||this.state.currEditCell.rid!=t||this.state.currEditCell.cid!=n){if("undefined"!=typeof o.format){var a=o.format(r,e);return i.createElement(p,{dataAlign:o.align,key:n,cellEdit:this.props.cellEdit,onEdit:this.handleEditCell.bind(this)},i.createElement("div",{dangerouslySetInnerHTML:{__html:a}}))}return i.createElement(p,{dataAlign:o.align,key:n,cellEdit:this.props.cellEdit,onEdit:this.handleEditCell.bind(this)},r)}return i.createElement(d,{completeEdit:this.handleCompleteEditCell.bind(this),key:n,blurToSave:this.props.cellEdit.blurToSave,rowIndex:t,colIndex:n},r)},this),r=-1!=this.state.selectedRowKey.indexOf(e[this.props.keyField]),a=o?this.renderSelectRowColumn(r):null;return i.createElement(u,{isSelected:r,key:t,selectRow:o?this.props.selectRow:void 0},a,n)},this);return i.createElement("div",{className:e},i.createElement("table",{className:t},n,i.createElement("tbody",null,r)))}},renderTableHeader:{value:function(e){var t=null;if(e){var o={width:35};t=i.createElement("th",{style:o,key:-1})}var n=this.props.columns.map(function(e,t){return i.createElement("th",{key:t})});return i.createElement("thead",null,i.createElement("tr",null,t,n))}},handleSelectRow:{value:function(e,t){var o,n;this.props.data.forEach(function(t,r){r==e-1&&(o=t[this.props.keyField],n=t)},this),this.props.selectRow.mode==c.ROW_SELECT_SINGLE&&(this.state.selectedRowKey=[]),t?this.state.selectedRowKey.push(o):this.state.selectedRowKey=this.state.selectedRowKey.filter(function(e){return o!==e}),this.setState({selectedRowKey:this.state.selectedRowKey}),this.props.selectRow.onSelect&&this.props.selectRow.onSelect(n,t)}},handleSelectAllRow:{value:function(e){this.setState({selectedRowKey:e}),this.props.selectRow.onSelectAll&&this.props.selectRow.onSelectAll(0!=e.length)}},handleSelectRowColumChange:{value:function(e){this.props.selectRow.clickToSelect||this.props.selectRow.__onSelect__(e.currentTarget.parentElement.parentElement.rowIndex,e.currentTarget.checked)}},handleEditCell:{value:function(e,t){this.props.parentRender=!1,this._isSelectRowDefined()&&t--,e--,this.setState({currEditCell:{rid:e,cid:t}})}},handleCompleteEditCell:{value:function(e,t,o){this.setState({currEditCell:null}),null!=e&&this.props.cellEdit.__onCompleteEdit__(e,t,o)}},renderSelectRowColumn:{value:function(e){return this.props.selectRow.mode==c.ROW_SELECT_SINGLE?i.createElement(p,null,i.createElement("input",{type:"radio",name:"selection",checked:e,onChange:this.handleSelectRowColumChange.bind(this)})):i.createElement(p,null,i.createElement("input",{type:"checkbox",checked:e,onChange:this.handleSelectRowColumChange.bind(this)}))}},_isSelectRowDefined:{value:function(){return this.props.selectRow.mode==c.ROW_SELECT_SINGLE||this.props.selectRow.mode==c.ROW_SELECT_MULTI}}}),t}(i.Component);b.propTypes={data:i.PropTypes.array,columns:i.PropTypes.array,striped:i.PropTypes.bool,hover:i.PropTypes.bool,condensed:i.PropTypes.bool,keyField:i.PropTypes.string,parentRender:i.PropTypes.bool},t.exports=b},{"./Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js","./TableColumn":"/home/allen/workspace/react-bootstrap-table/src/TableColumn.js","./TableEditColumn":"/home/allen/workspace/react-bootstrap-table/src/TableEditColumn.js","./TableRow":"/home/allen/workspace/react-bootstrap-table/src/TableRow.js",classnames:"/home/allen/workspace/react-bootstrap-table/node_modules/classnames/index.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/TableColumn.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function d(e,t,o){var n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n){var r=Object.getPrototypeOf(e);return null===r?void 0:d(r,t,o)}if("value"in n&&n.writable)return n.value;var a=n.get;if(void 0!==a)return a.call(o)},s=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},c=n(e("react")),u=n(e("./Const")),p=function(e){function t(e){l(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e)}return s(t,e),r(t,{handleCellEdit:{value:function(e){if(this.props.cellEdit.mode==u.CELL_EDIT_DBCLICK)if(document.selection&&document.selection.empty)document.selection.empty();else if(window.getSelection){var t=window.getSelection();t.removeAllRanges()}this.props.onEdit(e.currentTarget.parentElement.rowIndex,e.currentTarget.cellIndex)}},render:{value:function(){var e={textAlign:this.props.dataAlign},t={};return this.props.cellEdit&&(this.props.cellEdit.mode==u.CELL_EDIT_CLICK?t.onClick=this.handleCellEdit.bind(this):this.props.cellEdit.mode==u.CELL_EDIT_DBCLICK&&(t.onDoubleClick=this.handleCellEdit.bind(this))),c.createElement("td",i({style:e},t),this.props.children)}}}),t}(c.Component);p.propTypes={dataAlign:c.PropTypes.string},p.defaultProps={dataAlign:"left"},t.exports=p},{"./Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/TableEditColumn.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("react")),i=(n(e("./Const")),function(e){function t(){s(this,t),null!=e&&e.apply(this,arguments)}return a(t,e),r(t,{handleKeyPress:{value:function(e){13==e.keyCode?this.props.completeEdit(e.currentTarget.value,this.props.rowIndex,this.props.colIndex):27==e.keyCode&&this.props.completeEdit(null,this.props.rowIndex,this.props.colIndex)}},handleBlur:{value:function(e){this.props.blurToSave&&this.props.completeEdit(e.currentTarget.value,this.props.rowIndex,this.props.colIndex)}},componentDidMount:{value:function(){var e=this.refs.inputRef.getDOMNode();e.value=this.props.children,e.focus()}},render:{value:function(){return l.createElement("td",null,l.createElement("input",{ref:"inputRef",type:"text",onKeyDown:this.handleKeyPress.bind(this),onBlur:this.handleBlur.bind(this)}))}}}),t}(l.Component));i.propTypes={completeEdit:l.PropTypes.func,rowIndex:l.PropTypes.number,colIndex:l.PropTypes.number,blurToSave:l.PropTypes.bool},t.exports=i},{"./Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/TableHeader.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function m(e,t,o){var n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n){var r=Object.getPrototypeOf(e);return null===r?void 0:m(r,t,o)}if("value"in n&&n.writable)return n.value;var a=n.get;if(void 0!==a)return a.call(o)},s=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=n(e("react")),c=n(e("./Const")),u=n(e("classnames")),p=n(e("./SelectRowHeaderColumn")),d=function(e){function t(e){l(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.props.children.forEach(function(e){e.props.clearSortCaret=this.clearSortCaret.bind(this)},this)}return s(t,e),r(t,{clearSortCaret:{value:function(e,t){for(var o=this.refs.header.getDOMNode(),n=0;n<o.childElementCount;n++){var r=o.childNodes[n].childNodes[0];r.getElementsByClassName("order").length>0&&r.removeChild(r.getElementsByClassName("order")[0])}this.props.onSort(e,t)}},render:{value:function(){var e=u("table-header"),t=this.renderSelectRowHeader();return i.createElement("div",{className:e},i.createElement("table",{className:"table table-hover table-bordered"},i.createElement("thead",null,i.createElement("tr",{ref:"header"},t,this.props.children))))}},renderSelectRowHeader:{value:function(){return this.props.rowSelectType==c.ROW_SELECT_SINGLE?i.createElement(p,null):this.props.rowSelectType==c.ROW_SELECT_MULTI?i.createElement(p,null,i.createElement("input",{type:"checkbox",onChange:this.props.onSelectAllRow})):null}}}),t}(i.Component);d.propTypes={rowSelectType:i.PropTypes.string,onSort:i.PropTypes.func,onSelectAllRow:i.PropTypes.func},d.defaultProps={},t.exports=d},{"./Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js","./SelectRowHeaderColumn":"/home/allen/workspace/react-bootstrap-table/src/SelectRowHeaderColumn.js",classnames:"/home/allen/workspace/react-bootstrap-table/node_modules/classnames/index.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/TableHeaderColumn.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("react")),i=n(e("classnames")),c=n(e("./Const")),u=function(e){function t(){s(this,t),null!=e&&e.apply(this,arguments)}return a(t,e),r(t,{handleColumnClick:{value:function(e){this.props.dataSort&&(this.order=this.order==c.SORT_DESC?c.SORT_ASC:c.SORT_DESC,this.props.clearSortCaret(this.order,this.props.dataField),this.refs.innerDiv.getDOMNode().appendChild(this.renderSortCaret()))}},render:{value:function(){var e={textAlign:this.props.dataAlign},t=i(this.props.dataSort?"sort-column":"");return l.createElement("th",{className:t,style:e},l.createElement("div",{ref:"innerDiv",className:"th-inner table-header-column",onClick:this.handleColumnClick.bind(this)},this.props.children))}},renderSortCaret:{value:function(){var e=document.createElement("span");e.className="order",this.order==c.SORT_ASC&&(e.className+=" dropup");var t=document.createElement("span");return t.className="caret",t.style.margin="10px 5px",e.appendChild(t),e}}}),t}(l.Component);u.propTypes={dataField:l.PropTypes.string,dataAlign:l.PropTypes.string,dataSort:l.PropTypes.bool,clearSortCaret:l.PropTypes.func,dataFormat:l.PropTypes.func,isKey:l.PropTypes.bool},u.defaultProps={dataAlign:"left",dataSort:!1,dataFormat:void 0,isKey:!1},t.exports=u},{"./Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js",classnames:"/home/allen/workspace/react-bootstrap-table/node_modules/classnames/index.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/TableRow.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},l=n(e("react")),i=(n(e("./Const")),function(e){function t(){s(this,t),null!=e&&e.apply(this,arguments)}return a(t,e),r(t,{rowClick:{value:function(e){this.props.selectRow.__onSelect__(e.currentTarget.rowIndex,!this.props.isSelected)}},render:{value:function(){var e={backgroundColor:this.props.isSelected?this.props.selectRow.bgColor:null};return this.props.selectRow&&this.props.selectRow.clickToSelect?l.createElement("tr",{style:e,onClick:this.rowClick.bind(this)},this.props.children):l.createElement("tr",{style:e},this.props.children)}}}),t}(l.Component));i.propTypes={isSelected:l.PropTypes.bool},t.exports=i},{"./Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/pagination/PageButton.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function p(e,t,o){var n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n){var r=Object.getPrototypeOf(e);return null===r?void 0:p(r,t,o)}if("value"in n&&n.writable)return n.value;var a=n.get;if(void 0!==a)return a.call(o)},s=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=n(e("react")),c=n(e("classnames")),u=function(e){function t(e){l(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e)}return s(t,e),r(t,{pageBtnClick:{value:function(e){e.preventDefault(),this.props.changePage(e.currentTarget.text)}},render:{value:function(){var e=this.props.active?c("active"):null;return i.createElement("li",{className:e},i.createElement("a",{href:"#",onClick:this.pageBtnClick.bind(this)},this.props.children))}}}),t}(i.Component);u.propTypes={changePage:i.PropTypes.func,active:i.PropTypes.bool},t.exports=u},{classnames:"/home/allen/workspace/react-bootstrap-table/node_modules/classnames/index.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}],"/home/allen/workspace/react-bootstrap-table/src/pagination/PaginationList.js":[function(e,t,o){"use strict";var n=function(e){return e&&e.__esModule?e["default"]:e},r=function(){function e(e,t){for(var o in t){var n=t[o];n.configurable=!0,n.value&&(n.writable=!0)}Object.defineProperties(e,t)}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),a=function d(e,t,o){var n=Object.getOwnPropertyDescriptor(e,t);if(void 0===n){var r=Object.getPrototypeOf(e);return null===r?void 0:d(r,t,o)}if("value"in n&&n.writable)return n.value;var a=n.get;if(void 0!==a)return a.call(o)},s=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)},l=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},i=n(e("react")),c=n(e("./PageButton.js")),u=n(e("../Const")),p=function(e){function t(e){l(this,t),a(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.sizePerList=u.SIZE_PER_LIST,this.totalPages=Math.ceil(this.props.dataSize/this.props.sizePerPage),this.state={currentPage:1,sizePerPage:this.props.sizePerPage}}return s(t,e),r(t,{changePage:{value:function(e){e=e==u.PRE_PAGE?this.state.currentPage-1<1?1:this.state.currentPage-1:e==u.NEXT_PAGE?this.state.currentPage+1>this.totalPages?this.totalPages:this.state.currentPage+1:e==u.LAST_PAGE?this.totalPages:e==u.FIRST_PAGE?1:parseInt(e),e!=this.state.currentPage&&(this.setState({currentPage:e}),this.props.changePage(e,this.state.sizePerPage))}},changeSizePerPage:{value:function(e){e.preventDefault();var t=parseInt(e.currentTarget.text);t!=this.state.sizePerPage&&(this.totalPages=Math.ceil(this.props.dataSize/t),this.state.currentPage>this.totalPages&&(this.state.currentPage=this.totalPages),this.setState({sizePerPage:t,currentPage:this.state.currentPage}),this.props.changePage(this.state.currentPage,t))}},render:{value:function(){var e=this.makePage(),t={marginTop:"0px"};return i.createElement("div",{className:"row"},i.createElement("div",{className:"col-md-1"},i.createElement("div",{className:"dropdown"},i.createElement("button",{className:"btn btn-default dropdown-toggle",type:"button",id:"pageDropDown","data-toggle":"dropdown","aria-expanded":"true"},this.state.sizePerPage,i.createElement("span",{className:"caret"})),i.createElement("ul",{className:"dropdown-menu",role:"menu","aria-labelledby":"pageDropDown"},i.createElement("li",{role:"presentation"},i.createElement("a",{role:"menuitem",tabIndex:"-1",href:"#",onClick:this.changeSizePerPage.bind(this)},"10")),i.createElement("li",{role:"presentation"},i.createElement("a",{role:"menuitem",tabIndex:"-1",href:"#",onClick:this.changeSizePerPage.bind(this)},"25")),i.createElement("li",{role:"presentation"},i.createElement("a",{role:"menuitem",tabIndex:"-1",href:"#",onClick:this.changeSizePerPage.bind(this)},"30")),i.createElement("li",{role:"presentation"},i.createElement("a",{role:"menuitem",tabIndex:"-1",href:"#",onClick:this.changeSizePerPage.bind(this)},"50"))))),i.createElement("div",{className:"col-md-6"},i.createElement("ul",{className:"pagination",style:t},e)))}},makePage:{value:function(){var e=this.getPages();return e.map(function(e){var t=e==this.state.currentPage;return i.createElement(c,{changePage:this.changePage.bind(this),active:t,key:e},e)},this)}},getPages:{value:function(){var e=1,t=this.totalPages;e=Math.max(this.state.currentPage-Math.floor(this.sizePerList/2),1),t=e+this.sizePerList-1,t>this.totalPages&&(t=this.totalPages,e=t-this.sizePerList+1);for(var o=[u.FIRST_PAGE,u.PRE_PAGE],n=e;t>=n;n++)n>0&&o.push(n);return o.push(u.NEXT_PAGE),o.push(u.LAST_PAGE),o}}}),t}(i.Component);p.propTypes={sizePerPage:i.PropTypes.number,dataSize:i.PropTypes.number,changePage:i.PropTypes.func},p.defaultProps={sizePerPage:u.SIZE_PER_PAGE},t.exports=p},{"../Const":"/home/allen/workspace/react-bootstrap-table/src/Const.js","./PageButton.js":"/home/allen/workspace/react-bootstrap-table/src/pagination/PageButton.js",react:"/home/allen/workspace/react-bootstrap-table/node_modules/react/react.js"}]},{},["./src/index.js"]); //# sourceMappingURL=react-bootstrap-table.min.js.map
files/rxjs/2.2.24/rx.lite.js
dpellier/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 () { }, 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.then === 'function' && p.then !== Rx.Observable.prototype.then; }, 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 === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. 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'; } // 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; }; }()); 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) { 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 an iterable into an Observable sequence * * @example * var res = Rx.Observable.fromIterable(new Map()); * var res = Rx.Observable.fromIterable(new Set(), 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. */ Observable.fromIterable = function (iterable, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var iterator; try { iterator = iterable[$iterator$](); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next; try { next = iterator.next(); } catch (err) { observer.onError(err); return; } 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; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * 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.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; 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. * * @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)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(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); }); } 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 (typeof el.item === 'function' && typeof el.length === 'number') { 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; } // 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'; /** * 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) { if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName); }, function (h) { Ember.removeListener(element, eventName); }, 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 new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * 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) { other || (other = observableThrow(new Error('Timeout'))); 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); }); }; /** * 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) { 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]); * 2 - res = source.skipUntilWithTime(5000, [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, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * 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]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @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) { scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(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.subject.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.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 = [], previous = true; var subscription = combineLatestSource( this.source, this.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; } }, 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(); } ); this.subject.onNext(false); return subscription; } function PausableBufferedObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.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)); /** * 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)); }); }; /** * 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) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; 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));
test/PaginationSpec.js
dozoisch/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Pagination from '../src/Pagination'; describe('<Pagination>', () => { it('should have class', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination>Item content</Pagination> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'pagination')); }); it('should show the correct active button', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} activePage={3} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons.length, 5); pageButtons[2].className.should.match(/\bactive\b/); }); it('should call onSelect when page button is selected', (done) => { function onSelect(eventKey) { assert.equal(eventKey, 2); done(); } const instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} onSelect={onSelect} /> ); ReactTestUtils.Simulate.click( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a')[1] ); }); it('should only show part of buttons and active button in the middle of buttons when given maxButtons', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination items={30} activePage={10} maxButtons={9} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // 9 visible page buttons and 1 ellipsis button assert.equal(pageButtons.length, 10); // active button is the second one assert.equal(pageButtons[0].firstChild.textContent, '6'); pageButtons[4].className.should.match(/\bactive\b/); }); it('should show the ellipsis, boundaryLinks, first, last, prev and next button with default labels', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination first last prev next ellipsis maxButtons={3} activePage={10} items={20} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // add first, last, prev, next and ellipsis button assert.equal(pageButtons.length, 8); assert.equal(pageButtons[0].textContent, '«'); assert.equal(pageButtons[1].textContent, '‹'); assert.equal(pageButtons[5].textContent, '…'); assert.equal(pageButtons[6].textContent, '›'); assert.equal(pageButtons[7].textContent, '»'); }); it('should show the boundaryLinks, first, last, prev and next button', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination first last prev next ellipsis boundaryLinks maxButtons={3} activePage={10} items={20} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // add first, last, prev, next and ellipsis button assert.equal(pageButtons[2].textContent, '1'); assert.equal(pageButtons[3].textContent, '…'); assert.equal(pageButtons[7].textContent, '…'); assert.equal(pageButtons[8].textContent, '20'); }); it('should show the ellipsis, first, last, prev and next button with custom labels', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination first="first" last="last" prev="prev" next="next" ellipsis="more" maxButtons={3} activePage={10} items={20} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // add first, last, prev, next and ellipsis button assert.equal(pageButtons.length, 8); assert.equal(pageButtons[0].textContent, 'first'); assert.equal(pageButtons[1].textContent, 'prev'); assert.equal(pageButtons[5].textContent, 'more'); assert.equal(pageButtons[6].textContent, 'next'); assert.equal(pageButtons[7].textContent, 'last'); }); it('should enumerate pagenums correctly when ellipsis=true', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination first last prev next ellipsis maxButtons={5} activePage={1} items={1} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons[0].textContent, '«'); assert.equal(pageButtons[1].textContent, '‹'); assert.equal(pageButtons[2].textContent, '1'); assert.equal(pageButtons[3].textContent, '›'); assert.equal(pageButtons[4].textContent, '»'); }); it('should render next and last buttons as disabled when items=0 and ellipsis=true', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination last next ellipsis maxButtons={1} activePage={1} items={0} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons[0].textContent, '›'); assert.equal(pageButtons[1].textContent, '»'); assert.include(pageButtons[0].className, 'disabled'); assert.include(pageButtons[1].className, 'disabled'); }); it('should wrap buttons in SafeAnchor when no buttonComponentClass prop is supplied', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination maxButtons={2} activePage={1} items={2} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons[0].children[0].tagName, 'A'); assert.equal(pageButtons[1].children[0].tagName, 'A'); assert.equal(pageButtons[0].children[0].getAttribute('href'), ''); assert.equal(pageButtons[1].children[0].getAttribute('href'), ''); }); it('should wrap each button in a buttonComponentClass when it is present', () => { class DummyElement extends React.Component { render() { return <div>{this.props.children}</div>; } } const instance = ReactTestUtils.renderIntoDocument( <Pagination maxButtons={2} activePage={1} items={2} buttonComponentClass={DummyElement} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons[0].children[0].tagName, 'DIV'); assert.equal(pageButtons[1].children[0].tagName, 'DIV'); }); it('should call onSelect with custom buttonComponentClass', (done) => { class DummyElement extends React.Component { render() { return <div onClick={this.props.onClick} />; } } function onSelect(eventKey) { assert.equal(eventKey, 3); done(); } const instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} onSelect={onSelect} buttonComponentClass={DummyElement} /> ); ReactTestUtils.Simulate.click( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'div')[2] ); }); it('should not fire "onSelect" event on disabled buttons', () => { function onSelect() { throw Error('this event should not happen'); } const instance = ReactTestUtils.renderIntoDocument( <Pagination onSelect={onSelect} last next ellipsis maxButtons={1} activePage={1} items={0} /> ); const liElements = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // buttons are disabled assert.include(liElements[0].className, 'disabled'); assert.include(liElements[1].className, 'disabled'); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a'); const nextButton = pageButtons[0]; const lastButton = pageButtons[1]; ReactTestUtils.Simulate.click(nextButton); ReactTestUtils.Simulate.click(lastButton); }); it('should pass page number to buttonComponentClass', () => { class DummyElement extends React.Component { render() { return ( <a href={`?page=${this.props.eventKey}`}> {this.props.eventKey} </a> ); } } const instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} buttonComponentClass={DummyElement} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a'); assert.equal(pageButtons[1].getAttribute('href'), '?page=2'); }); });
src/svg-icons/image/collections.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCollections = (props) => ( <SvgIcon {...props}> <path d="M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"/> </SvgIcon> ); ImageCollections = pure(ImageCollections); ImageCollections.displayName = 'ImageCollections'; export default ImageCollections;
node_modules/react-native-pull/PullList.js
odapplications/WebView-with-Lower-Tab-Menu
'use strict'; import React, { Component } from 'react'; import { ListView } from 'react-native'; import Pullable from './Pullable'; /** 支持android&ios可以下拉刷新的PullList组件 Demo: import {PullList} from 'react-native-pullview'; <PullList onPulling={} onPullOk={} onPullRelease={} isPullEnd={true} topIndicatorRender={({pulling, pullok, pullrelease}) => {}} topIndicatorHeight={60} {...ListView.props} > Demo2: topIndicatorRender(pulling, pullok, pullrelease) { return <View style={{flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 60}}> <ActivityIndicator size="small" color="gray" /> {pulling ? <Text>下拉刷新2...</Text> : null} {pullok ? <Text>松开刷新2......</Text> : null} {pullrelease ? <Text>玩命刷新中2......</Text> : null} </View>; } <PullList onPullRelease={this.props.onRefresh} topIndicatorRender={this.topIndicatorRender} topIndicatorHeight={60} {...ListView.props} /> */ export default class extends Pullable { constructor(props) { super(props); this.getMetrics = this.getMetrics.bind(this); this.scrollTo = this.scrollTo.bind(this); this.scrollToEnd = this.scrollToEnd.bind(this); } getMetrics(args) { this.scroll.getMetrics(args); } scrollTo(...args) { this.scroll.scrollTo(...args); } scrollToEnd(args) { this.scroll.scrollToEnd(args); } getScrollable() { return ( <ListView ref={(c) => {this.scroll = c;}} scrollEnabled={this.state.scrollEnabled} onScroll={this.onScroll} {...this.props} /> ); } }
src/components/icons/ExploreIcon.js
InsideSalesOfficial/insidesales-components
import React from 'react'; const ExploreIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="1 1 22 22"> {props.title && <title>{props.title}</title>} <path d="M12 10.9c-.61 0-1.1.49-1.1 1.1s.49 1.1 1.1 1.1c.61 0 1.1-.49 1.1-1.1s-.49-1.1-1.1-1.1zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2.19 12.19L6 18l3.81-8.19L18 6l-3.81 8.19z" /> <path d="M0 0h24v24H0z" fill="none" /> </svg> ); export default ExploreIcon;
src/docs/Props.js
choudlet/ps-react-choudlet
import React from 'react'; import PropTypes from 'prop-types'; const Props = ({props}) => { return ( <table className="props"> <thead> <tr> <th>Name</th> <th>Description</th> <th>Type</th> <th>Default</th> <th>Required</th> </tr> </thead> <tbody> { Object.keys(props).map(key => { return ( <tr key={key}> <td>{key}</td> <td>{props[key].description}</td> <td>{props[key].type.name}</td> <td>{props[key].defaultValue && props[key].defaultValue.value}</td> <td>{props[key].required && "X"}</td> </tr> ); }) } </tbody> </table> ) } Props.propTypes = { props: PropTypes.object.isRequired }; export default Props;
sites/default/files/js/js_ij8BGR2xDDdV0pEt5h7JnhdHVNKd-xYZjJzFaqFjOmQ.js
TheCraftyCanvas/inklings
/** * hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+ * <http://cherne.net/brian/resources/jquery.hoverIntent.html> * * @param f onMouseOver function || An object with configuration options * @param g onMouseOut function || Nothing (use configuration options object) * @author Brian Cherne brian(at)cherne(dot)net */ (function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);; /* Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Version 2.1.2 */ (function(a){a.fn.bgiframe=(a.browser.msie&&/msie 6\.0/i.test(navigator.userAgent)?function(d){d=a.extend({top:"auto",left:"auto",width:"auto",height:"auto",opacity:true,src:"javascript:false;"},d);var c='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+d.src+'"style="display:block;position:absolute;z-index:-1;'+(d.opacity!==false?"filter:Alpha(Opacity='0');":"")+"top:"+(d.top=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+'px')":b(d.top))+";left:"+(d.left=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+'px')":b(d.left))+";width:"+(d.width=="auto"?"expression(this.parentNode.offsetWidth+'px')":b(d.width))+";height:"+(d.height=="auto"?"expression(this.parentNode.offsetHeight+'px')":b(d.height))+';"/>';return this.each(function(){if(a(this).children("iframe.bgiframe").length===0){this.insertBefore(document.createElement(c),this.firstChild)}})}:function(){return this});a.fn.bgIframe=a.fn.bgiframe;function b(c){return c&&c.constructor===Number?c+"px":c}})(jQuery);; /* * Superfish v1.4.8 - jQuery menu widget * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt */ /* * This is not the original jQuery Supersubs plugin. * Please refer to the README for more information. */ (function($){ $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')), over = function(){ var $$ = $(this), menu = getMenu($$); clearTimeout(menu.sfTimer); $$.showSuperfishUl().siblings().hideSuperfishUl(); }, out = function(){ var $$ = $(this), menu = getMenu($$), o = sf.op; clearTimeout(menu.sfTimer); menu.sfTimer=setTimeout(function(){ o.retainPath=($.inArray($$[0],o.$path)>-1); $$.hideSuperfishUl(); if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);} },o.delay); }, getMenu = function($menu){ var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0]; sf.op = sf.o[menu.serial]; return menu; }, addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); }; return this.each(function() { var s = this.serial = sf.o.length; var o = $.extend({},sf.defaults,op); o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){ $(this).addClass([o.hoverClass,c.bcClass].join(' ')) .filter('li:has(ul)').removeClass(o.pathClass); }); sf.o[s] = sf.op = o; $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() { if (o.autoArrows) addArrow( $('>a:first-child',this) ); }) .not('.'+c.bcClass) .hideSuperfishUl(); var $a = $('a',this); $a.each(function(i){ var $li = $a.eq(i).parents('li'); $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);}); }); o.onInit.call(this); }).each(function() { var menuClasses = [c.menuClass]; if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass); $(this).addClass(menuClasses.join(' ')); }); }; var sf = $.fn.superfish; sf.o = []; sf.op = {}; sf.IE7fix = function(){ var o = sf.op; if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined) this.toggleClass(sf.c.shadowClass+'-off'); }; sf.c = { bcClass: 'sf-breadcrumb', menuClass: 'sf-js-enabled', anchorClass: 'sf-with-ul', arrowClass: 'sf-sub-indicator', shadowClass: 'sf-shadow' }; sf.defaults = { hoverClass: 'sfHover', pathClass: 'overideThisToUse', pathLevels: 1, delay: 800, animation: {opacity:'show'}, speed: 'normal', autoArrows: true, dropShadows: true, disableHI: false, // true disables hoverIntent detection onInit: function(){}, // callback functions onBeforeShow: function(){}, onShow: function(){}, onHide: function(){} }; $.fn.extend({ hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass) .find('>ul').css({top: '-99999em'}).addClass('sf-hidden'); o.onHide.call($ul); return this; }, showSuperfishUl : function(){ var o = sf.op, sh = sf.c.shadowClass+'-off', $ul = this.addClass(o.hoverClass) .find('>ul.sf-hidden').css({display: 'none', top: ''}).removeClass('sf-hidden'); sf.IE7fix.call($ul); o.onBeforeShow.call($ul); $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); return this; } }); })(jQuery);; /* * Supersubs v0.2b - jQuery plugin * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of * their longest list item children. If you use this, please expect bugs and report them * to the jQuery Google Group with the word 'Superfish' in the subject line. * */ /* * This is not the original jQuery Supersubs plugin. * Please refer to the README for more information. */ (function($){ // $ will refer to jQuery within this closure $.fn.supersubs = function(options){ var opts = $.extend({}, $.fn.supersubs.defaults, options); // return original object to support chaining return this.each(function() { // cache selections var $$ = $(this); // support metadata var o = $.meta ? $.extend({}, opts, $$.data()) : opts; // get the font size of menu. // .css('fontSize') returns various results cross-browser, so measure an em dash instead var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({ 'padding' : 0, 'position' : 'absolute', 'top' : '-99999em', 'width' : 'auto' }).appendTo($$).width(); //clientWidth is faster, but was incorrect here // remove em dash $('#menu-fontsize').remove(); // Jump on level if it's a "NavBar" if ($$.hasClass('sf-navbar')) { $$ = $('li > ul', $$); } // cache all ul elements $ULs = $$.find('ul:not(.sf-megamenu)'); // loop through each ul in menu $ULs.each(function(i) { // cache this ul var $ul = $ULs.eq(i); // get all (li) children of this ul var $LIs = $ul.children(); // get all anchor grand-children var $As = $LIs.children('a'); // force content to one line and save current float property var liFloat = $LIs.css('white-space','nowrap').css('float'); // remove width restrictions and floats so elements remain vertically stacked var emWidth = $ul.add($LIs).add($As).css({ 'float' : 'none', 'width' : 'auto' }) // this ul will now be shrink-wrapped to longest li due to position:absolute // so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer .end().end()[0].clientWidth / fontsize; // add more width to ensure lines don't turn over at certain sizes in various browsers emWidth += o.extraWidth; // restrict to at least minWidth and at most maxWidth if (emWidth > o.maxWidth) { emWidth = o.maxWidth; } else if (emWidth < o.minWidth) { emWidth = o.minWidth; } emWidth += 'em'; // set ul to width in ems $ul.css('width',emWidth); // restore li floats to avoid IE bugs // set li width to full width of this ul // revert white-space to normal $LIs.css({ 'float' : liFloat, 'width' : '100%', 'white-space' : 'normal' }) // update offset position of descendant ul to reflect new width of parent .each(function(){ var $childUl = $('>ul',this); var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right'; $childUl.css(offsetDirection,emWidth); }); }); }); }; // expose defaults $.fn.supersubs.defaults = { minWidth: 9, // requires em unit. maxWidth: 25, // requires em unit. extraWidth: 0 // extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values }; })(jQuery); // plugin code ends; /* * Supposition v0.2 - an optional enhancer for Superfish jQuery menu widget. * * Copyright (c) 2008 Joel Birch - based mostly on work by Jesse Klaasse and credit goes largely to him. * Special thanks to Karl Swedberg for valuable input. * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ /* * This is not the original jQuery Supersubs plugin. * Please refer to the README for more information. */ (function($){ $.fn.supposition = function(){ var $w = $(window), /*do this once instead of every onBeforeShow call*/ _offset = function(dir) { return window[dir == 'y' ? 'pageYOffset' : 'pageXOffset'] || document.documentElement && document.documentElement[dir=='y' ? 'scrollTop' : 'scrollLeft'] || document.body[dir=='y' ? 'scrollTop' : 'scrollLeft']; }, onHide = function(){ this.css({bottom:''}); }, onBeforeShow = function(){ this.each(function(){ var $u = $(this); $u.css('display','block'); var menuWidth = $u.width(), menuParentWidth = $u.closest('li').outerWidth(true), menuParentLeft = $u.closest('li').offset().left, totalRight = $w.width() + _offset('x'), menuRight = $u.offset().left + menuWidth, exactMenuWidth = (menuRight > (menuParentWidth + menuParentLeft)) ? menuWidth - (menuRight - (menuParentWidth + menuParentLeft)) : menuWidth; if ($u.parents('.sf-js-enabled').hasClass('rtl')) { if (menuParentLeft < exactMenuWidth) { $u.css('left', menuParentWidth + 'px'); $u.css('right', 'auto'); } } else { if (menuRight > totalRight && menuParentLeft > menuWidth) { $u.css('right', menuParentWidth + 'px'); $u.css('left', 'auto'); } } var windowHeight = $w.height(), offsetTop = $u.offset().top, menuParentShadow = ($u.closest('.sf-menu').hasClass('sf-shadow') && $u.css('padding-bottom').length > 0) ? parseInt($u.css('padding-bottom').slice(0,-2)) : 0, menuParentHeight = ($u.closest('.sf-menu').hasClass('sf-vertical')) ? '-' + menuParentShadow : $u.parent().outerHeight(true) - menuParentShadow, menuHeight = $u.height(), baseline = windowHeight + _offset('y'); var expandUp = ((offsetTop + menuHeight > baseline) && (offsetTop > menuHeight)); if (expandUp) { $u.css('bottom', menuParentHeight + 'px'); $u.css('top', 'auto'); } $u.css('display','none'); }); }; return this.each(function() { var o = $.fn.superfish.o[this.serial]; /* get this menu's options */ /* if callbacks already set, store them */ var _onBeforeShow = o.onBeforeShow, _onHide = o.onHide; $.extend($.fn.superfish.o[this.serial],{ onBeforeShow: function() { onBeforeShow.call(this); /* fire our Supposition callback */ _onBeforeShow.call(this); /* fire stored callbacks */ }, onHide: function() { onHide.call(this); /* fire our Supposition callback */ _onHide.call(this); /* fire stored callbacks */ } }); }); }; })(jQuery);; /* * sf-Touchscreen v1.0b - Provides touchscreen compatibility for the jQuery Superfish plugin. * * Developer's note: * Built as a part of the Superfish project for Drupal (http://drupal.org/project/superfish) * Found any bug? have any cool ideas? contact me right away! http://drupal.org/user/619294/contact * * jQuery version: 1.3.x or higher. * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($){ $.fn.sftouchscreen = function() { // Return original object to support chaining. return this.each( function() { // Select hyperlinks from parent menu items. $(this).find('li > ul').closest('li').children('a').each( function() { var $item = $(this); // No .toggle() here as it's not possible to reset it. $item.click( function(event){ // Already clicked? proceed to the URI. if ($item.hasClass('sf-clicked')) { var $uri = $item.attr('href'); window.location = $uri; } else { event.preventDefault(); $item.addClass('sf-clicked'); } }).closest('li').mouseleave( function(){ // So, we reset everything. $item.removeClass('sf-clicked'); }); }); }); }; })(jQuery);; (function($){ Drupal.behaviors.contextReactionBlock = {attach: function(context) { $('form.context-editor:not(.context-block-processed)') .addClass('context-block-processed') .each(function() { var id = $(this).attr('id'); Drupal.contextBlockEditor = Drupal.contextBlockEditor || {}; $(this).bind('init.pageEditor', function(event) { Drupal.contextBlockEditor[id] = new DrupalContextBlockEditor($(this)); }); $(this).bind('start.pageEditor', function(event, context) { // Fallback to first context if param is empty. if (!context) { context = $(this).data('defaultContext'); } Drupal.contextBlockEditor[id].editStart($(this), context); }); $(this).bind('end.pageEditor', function(event) { Drupal.contextBlockEditor[id].editFinish(); }); }); // // Admin Form ======================================================= // // ContextBlockForm: Init. $('#context-blockform:not(.processed)').each(function() { $(this).addClass('processed'); Drupal.contextBlockForm = new DrupalContextBlockForm($(this)); Drupal.contextBlockForm.setState(); }); // ContextBlockForm: Attach block removal handlers. // Lives in behaviors as it may be required for attachment to new DOM elements. $('#context-blockform a.remove:not(.processed)').each(function() { $(this).addClass('processed'); $(this).click(function() { $(this).parents('tr').eq(0).remove(); Drupal.contextBlockForm.setState(); return false; }); }); }}; /** * Context block form. Default form for editing context block reactions. */ DrupalContextBlockForm = function(blockForm) { this.state = {}; this.setState = function() { $('table.context-blockform-region', blockForm).each(function() { var region = $(this).attr('id').split('context-blockform-region-')[1]; var blocks = []; $('tr', $(this)).each(function() { var bid = $(this).attr('id'); var weight = $(this).find('select').val(); blocks.push({'bid' : bid, 'weight' : weight}); }); Drupal.contextBlockForm.state[region] = blocks; }); // Serialize here and set form element value. $('form input.context-blockform-state').val(JSON.stringify(this.state)); // Hide enabled blocks from selector that are used $('table.context-blockform-region tr').each(function() { var bid = $(this).attr('id'); $('div.context-blockform-selector input[value='+bid+']').parents('div.form-item').eq(0).hide(); }); // Show blocks in selector that are unused $('div.context-blockform-selector input').each(function() { var bid = $(this).val(); if ($('table.context-blockform-region tr#'+bid).size() === 0) { $(this).parents('div.form-item').eq(0).show(); } }); }; // make sure we update the state right before submits, this takes care of an // apparent race condition between saving the state and the weights getting set // by tabledrag $('#ctools-export-ui-edit-item-form').submit(function() { Drupal.contextBlockForm.setState(); }); // Tabledrag // Add additional handlers to update our blocks. $.each(Drupal.settings.tableDrag, function(base) { var table = $('#' + base + ':not(.processed)', blockForm); if (table && table.is('.context-blockform-region')) { table.addClass('processed'); table.bind('mouseup', function(event) { Drupal.contextBlockForm.setState(); return; }); } }); // Add blocks to a region $('td.blocks a', blockForm).each(function() { $(this).click(function() { var region = $(this).attr('href').split('#')[1]; var selected = $("div.context-blockform-selector input:checked"); if (selected.size() > 0) { selected.each(function() { // create new block markup var block = document.createElement('tr'); var text = $(this).parents('div.form-item').eq(0).hide().children('label').text(); var select = '<div class="form-item form-type-select"><select class="tabledrag-hide form-select">'; var i; for (i = -10; i < 10; ++i) { select += '<option>' + i + '</option>'; } select += '</select></div>'; $(block).attr('id', $(this).attr('value')).addClass('draggable'); $(block).html("<td>"+ text + "</td><td>" + select + "</td><td><a href='' class='remove'>X</a></td>"); // add block item to region var base = "context-blockform-region-"+ region; Drupal.tableDrag[base].makeDraggable(block); $('table#'+base).append(block); if ($.cookie('Drupal.tableDrag.showWeight') == 1) { $('table#'+base).find('.tabledrag-hide').css('display', ''); $('table#'+base).find('.tabledrag-handle').css('display', 'none'); } else { $('table#'+base).find('.tabledrag-hide').css('display', 'none'); $('table#'+base).find('.tabledrag-handle').css('display', ''); } Drupal.attachBehaviors($('table#'+base)); Drupal.contextBlockForm.setState(); $(this).removeAttr('checked'); }); } return false; }); }); }; /** * Context block editor. AHAH editor for live block reaction editing. */ DrupalContextBlockEditor = function(editor) { this.editor = editor; this.state = {}; this.blocks = {}; this.regions = {}; // Category selector handler. // Also set to "Choose a category" option as browsers can retain // form values from previous page load. $('select.context-block-browser-categories', editor).change(function() { var category = $(this).val(); var params = { containment: 'document', revert: true, dropOnEmpty: true, placeholder: 'draggable-placeholder', forcePlaceholderSize: true, helper: 'clone', appendTo: 'body', connectWith: ($.ui.version === '1.6') ? ['.ui-sortable'] : '.ui-sortable' }; $('div.category', editor).hide().sortable('destroy'); $('div.category-'+category, editor).show().sortable(params); }); $('select.context-block-browser-categories', editor).val(0).change(); return this; }; DrupalContextBlockEditor.prototype.initBlocks = function(blocks) { var self = this; this.blocks = blocks; blocks.each(function() { if($(this).hasClass('context-block-empty')) { $(this).removeClass('context-block-hidden'); } $(this).addClass('draggable'); $(this).prepend($('<a class="context-block-handle"></a>')); $(this).prepend($('<a class="context-block-remove"></a>').click(function() { $(this).parent ('.block').eq(0).fadeOut('medium', function() { $(this).remove(); self.updateBlocks(); }); return false; })); }); }; DrupalContextBlockEditor.prototype.initRegions = function(regions) { this.regions = regions; }; /** * Update UI to match the current block states. */ DrupalContextBlockEditor.prototype.updateBlocks = function() { var browser = $('div.context-block-browser'); // For all enabled blocks, mark corresponding addables as having been added. $('.block, .admin-block').each(function() { var bid = $(this).attr('id').split('block-')[1]; // Ugh. $('#context-block-addable-'+bid, browser).draggable('disable').addClass('context-block-added').removeClass('context-block-addable'); }); // For all hidden addables with no corresponding blocks, mark as addable. $('.context-block-item', browser).each(function() { var bid = $(this).attr('id').split('context-block-addable-')[1]; if ($('#block-'+bid).size() === 0) { $(this).draggable('enable').removeClass('context-block-added').addClass('context-block-addable'); } }); // Mark empty regions. $(this.regions).each(function() { if ($('.block:has(a.context-block)', this).size() > 0) { $(this).removeClass('context-block-region-empty'); } else { $(this).addClass('context-block-region-empty'); } }); }; /** * Live update a region. */ DrupalContextBlockEditor.prototype.updateRegion = function(event, ui, region, op) { switch (op) { case 'over': $(region).removeClass('context-block-region-empty'); break; case 'out': if ( // jQuery UI 1.8 $('.draggable-placeholder', region).size() === 1 && $('.block:has(a.context-block)', region).size() == 0 // jQuery UI 1.6 // $('div.draggable-placeholder', region).size() === 0 && // $('div.block:has(a.context-block)', region).size() == 1 && // $('div.block:has(a.context-block)', region).attr('id') == ui.item.attr('id') ) { $(region).addClass('context-block-region-empty'); } break; } }; /** * Remove script elements while dragging & dropping. */ DrupalContextBlockEditor.prototype.scriptFix = function(event, ui, editor, context) { if ($('script', ui.item)) { var placeholder = $(Drupal.settings.contextBlockEditor.scriptPlaceholder); var label = $('div.handle label', ui.item).text(); placeholder.children('strong').html(label); $('script', ui.item).parent().empty().append(placeholder); } }; /** * Add a block to a region through an AHAH load of the block contents. */ DrupalContextBlockEditor.prototype.addBlock = function(event, ui, editor, context) { var self = this; if (ui.item.is('.context-block-addable')) { var bid = ui.item.attr('id').split('context-block-addable-')[1]; // Construct query params for our AJAX block request. var params = Drupal.settings.contextBlockEditor.params; params.context_block = bid + ',' + context; // Replace item with loading block. var blockLoading = $('<div class="context-block-item context-block-loading"><span class="icon"></span></div>'); ui.item.addClass('context-block-added'); ui.item.after(blockLoading); ui.sender.append(ui.item); $.getJSON(Drupal.settings.contextBlockEditor.path, params, function(data) { if (data.status) { var newBlock = $(data.block); if ($('script', newBlock)) { $('script', newBlock).remove(); } blockLoading.fadeOut(function() { $(this).replaceWith(newBlock); self.initBlocks(newBlock); self.updateBlocks(); Drupal.attachBehaviors(); }); } else { blockLoading.fadeOut(function() { $(this).remove(); }); } }); } else if (ui.item.is(':has(a.context-block)')) { self.updateBlocks(); } }; /** * Update form hidden field with JSON representation of current block visibility states. */ DrupalContextBlockEditor.prototype.setState = function() { var self = this; $(this.regions).each(function() { var region = $('a.context-block-region', this).attr('id').split('context-block-region-')[1]; var blocks = []; $('a.context-block', $(this)).each(function() { if ($(this).attr('class').indexOf('edit-') != -1) { var bid = $(this).attr('id').split('context-block-')[1]; var context = $(this).attr('class').split('edit-')[1].split(' ')[0]; context = context ? context : 0; var block = {'bid': bid, 'context': context}; blocks.push(block); } }); self.state[region] = blocks; }); // Serialize here and set form element value. $('input.context-block-editor-state', this.editor).val(JSON.stringify(this.state)); }; /** * Disable text selection. */ DrupalContextBlockEditor.prototype.disableTextSelect = function() { if ($.browser.safari) { $('.block:has(a.context-block):not(:has(input,textarea))').css('WebkitUserSelect','none'); } else if ($.browser.mozilla) { $('.block:has(a.context-block):not(:has(input,textarea))').css('MozUserSelect','none'); } else if ($.browser.msie) { $('.block:has(a.context-block):not(:has(input,textarea))').bind('selectstart.contextBlockEditor', function() { return false; }); } else { $(this).bind('mousedown.contextBlockEditor', function() { return false; }); } }; /** * Enable text selection. */ DrupalContextBlockEditor.prototype.enableTextSelect = function() { if ($.browser.safari) { $('*').css('WebkitUserSelect',''); } else if ($.browser.mozilla) { $('*').css('MozUserSelect',''); } else if ($.browser.msie) { $('*').unbind('selectstart.contextBlockEditor'); } else { $(this).unbind('mousedown.contextBlockEditor'); } }; /** * Start editing. Attach handlers, begin draggable/sortables. */ DrupalContextBlockEditor.prototype.editStart = function(editor, context) { var self = this; // This is redundant to the start handler found in context_ui.js. // However it's necessary that we trigger this class addition before // we call .sortable() as the empty regions need to be visible. $(document.body).addClass('context-editing'); this.editor.addClass('context-editing'); this.disableTextSelect(); this.initBlocks($('.block:has(a.context-block.edit-'+context+')')); this.initRegions($('a.context-block-region').parent()); this.updateBlocks(); // First pass, enable sortables on all regions. $(this.regions).each(function() { var region = $(this); var params = { containment: 'document', revert: true, dropOnEmpty: true, placeholder: 'draggable-placeholder', forcePlaceholderSize: true, items: '> .block:has(a.context-block.editable)', handle: 'a.context-block-handle', start: function(event, ui) { self.scriptFix(event, ui, editor, context); }, stop: function(event, ui) { self.addBlock(event, ui, editor, context); }, receive: function(event, ui) { self.addBlock(event, ui, editor, context); }, over: function(event, ui) { self.updateRegion(event, ui, region, 'over'); }, out: function(event, ui) { self.updateRegion(event, ui, region, 'out'); } }; region.sortable(params); }); // Second pass, hook up all regions via connectWith to each other. $(this.regions).each(function() { $(this).sortable('option', 'connectWith', ['.ui-sortable']); }); // Terrible, terrible workaround for parentoffset issue in Safari. // The proper fix for this issue has been committed to jQuery UI, but was // not included in the 1.6 release. Therefore, we do a browser agent hack // to ensure that Safari users are covered by the offset fix found here: // http://dev.jqueryui.com/changeset/2073. if ($.ui.version === '1.6' && $.browser.safari) { $.browser.mozilla = true; } }; /** * Finish editing. Remove handlers. */ DrupalContextBlockEditor.prototype.editFinish = function() { this.editor.removeClass('context-editing'); this.enableTextSelect(); // Remove UI elements. $(this.blocks).each(function() { $('a.context-block-handle, a.context-block-remove', this).remove(); if($(this).hasClass('context-block-empty')) { $(this).addClass('context-block-hidden'); } $(this).removeClass('draggable'); }); this.regions.sortable('destroy'); this.setState(); // Unhack the user agent. if ($.ui.version === '1.6' && $.browser.safari) { $.browser.mozilla = false; } }; })(jQuery); ;
src/app/ui/Routes/PublicRouteWeb.js
arikanmstf/mylibrary
// @flow import React from 'react'; import type { ComponentType } from 'react'; import { HOME } from 'constants/routes/routeNames'; import { connect } from 'react-redux'; import { Route, Redirect } from 'react-router-dom'; import { mapStateToProps } from './actions'; const PublicRouteWeb = ( { component: Component, isLoggedIn, isInitialized, ...rest }: { component: ComponentType<*>, isLoggedIn: boolean, isInitialized: boolean } ) => { if (isInitialized === null) { return null; } return isInitialized && isLoggedIn ? ( <Redirect to={HOME} /> ) : ( <Route {...rest} render={(props) => (<Component {...props} />)} /> ); }; export default connect(mapStateToProps)(PublicRouteWeb);
src/components/common/LeftNav.js
noahjohn9259/carcareapp
import React from 'react'; import Paper from 'material-ui/Paper'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; const LeftNav = () => ( <div> <Paper> <Menu> <MenuItem primaryText="Maps" /> <MenuItem primaryText="Books" /> <MenuItem primaryText="Flights" /> <MenuItem primaryText="Apps" /> </Menu> </Paper> </div> ); export default LeftNav;
docs/src/examples/elements/Header/Content/HeaderExampleIconProp.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Header } from 'semantic-ui-react' const HeaderExampleIconProp = () => ( <Header as='h2' icon='plug' content='Uptime Guarantee' /> ) export default HeaderExampleIconProp
src/components/InfoBar/InfoBar.js
prakash-u/react-redux
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { load } from 'redux/modules/info'; @connect(state => ({ info: state.info.data }), { load }) export default class InfoBar extends Component { static propTypes = { info: PropTypes.shape({ message: PropTypes.string, time: PropTypes.number }), load: PropTypes.func.isRequired }; static defaultProps = { info: null }; render() { const { info, load } = this.props; // eslint-disable-line no-shadow const styles = require('./InfoBar.scss'); return ( <div className={`${styles.infoBar} well`}> <div className="container"> This is an info bar <strong>{info ? info.message : 'no info!'}</strong> <span className={styles.time}>{info && new Date(info.time).toString()}</span> <button className="btn btn-primary" onClick={load}> Reload from server </button> </div> </div> ); } }
src/common/components/Posts.js
k2052/journal.k2052.me
import React from 'react' import { Link } from 'react-router' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { changePost } from 'actions//posts' function mapStateToProps(state) { return { posts: state.posts } } function mapDispatchToProps(dispatch) { return bindActionCreators({ changePost }, dispatch); } class Posts extends React.Component { constructor(props) { super(props); this.changePost = this.changePost.bind(this); } changePost(id) { this.props.changePost(id); } render () { let postsRows = [] this.props.posts.map((post, index) => { postsRows.push( <li key={index}> <Link to={`/${post.slug}.html`} className="Posts__Post__Title" onClick={(e) => this.changePost(index)}> <h2> <div className="Posts__Post__Title__Span">{post.title}</div> <aside className="Posts__Post__Date">{post.date}</aside> </h2> </Link> </li> ) }) return ( <ul className="Posts"> {postsRows} </ul> ) } } export default connect(mapStateToProps, mapDispatchToProps)(Posts);
src/parser/hunter/shared/modules/features/CancelledCasts.js
sMteX/WoWAnalyzer
import React from 'react'; import CoreCancelledCasts from 'parser/shared/modules/CancelledCasts'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import Icon from 'common/Icon'; /** * Tracks the amount of cancelled casts in %. * * Example log: https://www.warcraftlogs.com/reports/Pp17Crv6gThLYmdf#fight=8&type=damage-done&source=76 */ class CancelledCasts extends CoreCancelledCasts { static IGNORED_ABILITIES = [ //Include the spells that you do not want to be tracked and spells that are castable while casting SPELLS.EXPLOSIVE_SHOT_DAMAGE.id, ]; get suggestionThresholds() { return { actual: this.cancelledPercentage, isGreaterThan: { minor: 0.025, average: 0.05, major: 0.1, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You cancelled {formatPercentage(this.cancelledPercentage)}% of your spells. While it is expected that you will have to cancel a few casts to react to a boss mechanic or to move, you should try to ensure that you are cancelling as few casts as possible. This is generally done by planning ahead in terms of positioning, and moving while you're casting instant cast spells.</>) .icon('inv_misc_map_01') .actual(`${formatPercentage(actual)}% casts cancelled`) .recommended(`<${formatPercentage(recommended)}% is recommended`); }); } statistic() { const tooltipText = Object.keys(this.cancelledSpellList).map(cancelledSpell => ( <li> {this.cancelledSpellList[cancelledSpell].spellName}: {this.cancelledSpellList[cancelledSpell].amount} </li> )); return ( <StatisticBox position={STATISTIC_ORDER.CORE(14)} icon={<Icon icon="inv_misc_map_01" />} value={`${formatPercentage(this.cancelledPercentage)}%`} label="Cancelled Casts" tooltip={( <> You started casting a total of {this.totalCasts} spells with a cast timer. You cancelled {this.castsCancelled} of those casts. <ul> {tooltipText} </ul> </> )} /> ); } } export default CancelledCasts;
packages/material-ui-icons/src/ThumbDownOutlined.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v2c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm0 12l-4.34 4.34L12 14H3v-2l3-7h9v10zm4-12h4v12h-4z" /> , 'ThumbDownOutlined');
assets/javascripts/kitten/components/structure/cards/simple-card/index.js
KissKissBankBank/kitten
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import styled from 'styled-components' import { Image } from './components/image' import { Title } from './components/title' import { Subtitle } from './components/subtitle' import { Paragraph } from './components/paragraph' import { pxToRem } from '../../../../helpers/utils/typography' import COLORS from '../../../../constants/colors-config' const ContainerStyle = styled.a` display: block; overflow: auto; text-decoration: inherit; color: inherit; line-height: 1; position: relative; .k-SimpleCard__imageContainer { max-width: 100%; position: relative; margin-bottom: ${pxToRem(20)}; transition: opacity ease 600ms; z-index: 1; background-color: var(--SimpleCard-image-container-background); overflow: hidden; } .k-SimpleCard__imageContainer--ratio { padding-top: calc(100% / (var(--SimpleCard-image-container-ratio))); & > .k-SimpleCard__image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-position: center; object-fit: cover; } } .k-SimpleCard__playerButton { width: var(--SimpleCard-player-button-size); height: var(--SimpleCard-player-button-size); background: ${COLORS.font1}; position: absolute; top: calc(50% - var(--SimpleCard-player-button-size) / 2); left: calc(50% - var(--SimpleCard-player-button-size) / 2); display: flex; align-items: center; justify-content: center; z-index: 2; } .k-SimpleCard__image { width: 100%; display: block; transition: transform 0.4s ease-in-out; } .k-SimpleCard__title { transition: color 0.4s ease-in-out; } &[href]:hover, &[href]:focus { .k-SimpleCard__image { transform: scale(1.07); } .k-SimpleCard__title { color: ${COLORS.primary1}; } } ` export const SimpleCard = ({ imageProps, withPlayerButtonOnImage, arrowColor, ariaLabel, href, title, titleProps, subtitle, paragraph, imageContainerRatio, imageContainerBackground, className, playerButtonSize, ...others }) => ( <ContainerStyle as={href ? 'a' : 'div'} {...others} href={href} className={classNames('k-SimpleCard', className)} > <Image imageContainerRatio={imageContainerRatio} imageContainerBackground={imageContainerBackground} imageProps={imageProps} withPlayerButtonOnImage={withPlayerButtonOnImage} arrowColor={arrowColor} ariaLabel={ariaLabel} playerButtonSize={playerButtonSize} /> {title && <Title title={title} titleProps={titleProps} />} {subtitle && <Subtitle subtitle={subtitle} />} {paragraph && <Paragraph paragraph={paragraph} />} </ContainerStyle> ) SimpleCard.propTypes = { imageProps: PropTypes.shape({ src: PropTypes.string.isRequired, alt: PropTypes.string.isRequired, }), withPlayerButtonOnImage: PropTypes.bool, ariaLabel: PropTypes.string, arrowColor: PropTypes.string, href: PropTypes.string, playerButtonSize: PropTypes.number, imageContainerBackground: PropTypes.string, imageContainerRatio: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), title: PropTypes.node, titleProps: PropTypes.object, subtitle: PropTypes.node, paragraph: PropTypes.node, } SimpleCard.defaultProps = { imageProps: { src: '', alt: '', }, withPlayerButtonOnImage: false, arrowColor: 'background1', href: '#', imageContainerBackground: COLORS.line1, playerButtonSize: 70, imageContainerRatio: null, title: null, titleProps: {}, subtitle: null, paragraph: null, }
examples/PrefillingTextInput.js
react-materialize/react-materialize
import React from 'react'; import Input from '../src/Input'; import Row from '../src/Row'; export default <Row> <Input s={6} label="First Name" validate defaultValue='Alvin' /> </Row>;
ajax/libs/onsen/2.0.0-beta.2/js/onsenui.min.js
vetruvet/cdnjs
/*! onsenui v2.0.0-beta.2 - 2015-12-01 */ function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}!function(){function getAttributes(element){return Node_get_attributes.call(element)}function setAttribute(element,attribute,value){try{Element_setAttribute.call(element,attribute,value)}catch(e){}}function removeAttribute(element,attribute){Element_removeAttribute.call(element,attribute)}function childNodes(element){return Node_get_childNodes.call(element)}function empty(element){for(;element.childNodes.length;)element.removeChild(element.lastChild)}function insertAdjacentHTML(element,position,html){HTMLElement_insertAdjacentHTMLPropertyDescriptor.value.call(element,position,html)}function inUnsafeMode(){var isUnsafe=!0;try{detectionDiv.innerHTML="<test/>"}catch(ex){isUnsafe=!1}return isUnsafe}function cleanse(html,targetElement){function cleanseAttributes(element){var attributes=getAttributes(element);if(attributes&&attributes.length){for(var events,i=0,len=attributes.length;len>i;i++){var attribute=attributes[i],name=attribute.name;"o"!==name[0]&&"O"!==name[0]||"n"!==name[1]&&"N"!==name[1]||(events=events||[],events.push({name:attribute.name,value:attribute.value}))}if(events)for(var i=0,len=events.length;len>i;i++){var attribute=events[i];removeAttribute(element,attribute.name),setAttribute(element,"x-"+attribute.name,attribute.value)}}for(var children=childNodes(element),i=0,len=children.length;len>i;i++)cleanseAttributes(children[i])}var cleaner=document.implementation.createHTMLDocument("cleaner");empty(cleaner.documentElement),MSApp.execUnsafeLocalFunction(function(){insertAdjacentHTML(cleaner.documentElement,"afterbegin",html)});var scripts=cleaner.documentElement.querySelectorAll("script");Array.prototype.forEach.call(scripts,function(script){switch(script.type.toLowerCase()){case"":script.type="text/inert";break;case"text/javascript":case"text/ecmascript":case"text/x-javascript":case"text/jscript":case"text/livescript":case"text/javascript1.1":case"text/javascript1.2":case"text/javascript1.3":script.type="text/inert-"+script.type.slice("text/".length);break;case"application/javascript":case"application/ecmascript":case"application/x-javascript":script.type="application/inert-"+script.type.slice("application/".length)}}),cleanseAttributes(cleaner.documentElement);var cleanedNodes=[];return"HTML"===targetElement.tagName?cleanedNodes=Array.prototype.slice.call(document.adoptNode(cleaner.documentElement).childNodes):(cleaner.head&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.head).childNodes))),cleaner.body&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.body).childNodes)))),cleanedNodes}function cleansePropertySetter(property,setter){var propertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,property),originalSetter=propertyDescriptor.set;Object.defineProperty(HTMLElement.prototype,property,{get:propertyDescriptor.get,set:function(value){if(window.WinJS&&window.WinJS._execUnsafe&&inUnsafeMode())originalSetter.call(this,value);else{var that=this,nodes=cleanse(value,that);MSApp.execUnsafeLocalFunction(function(){setter(propertyDescriptor,that,nodes)})}},enumerable:propertyDescriptor.enumerable,configurable:propertyDescriptor.configurable})}if(window.MSApp&&MSApp.execUnsafeLocalFunction){var Element_setAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"setAttribute").value,Element_removeAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"removeAttribute").value,HTMLElement_insertAdjacentHTMLPropertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,"insertAdjacentHTML"),Node_get_attributes=Object.getOwnPropertyDescriptor(Node.prototype,"attributes").get,Node_get_childNodes=Object.getOwnPropertyDescriptor(Node.prototype,"childNodes").get,detectionDiv=document.createElement("div");cleansePropertySetter("innerHTML",function(propertyDescriptor,target,elements){empty(target);for(var i=0,len=elements.length;len>i;i++)target.appendChild(elements[i])}),cleansePropertySetter("outerHTML",function(propertyDescriptor,target,elements){for(var i=0,len=elements.length;len>i;i++)target.insertAdjacentElement("afterend",elements[i]);target.parentNode.removeChild(target); })}}(),"undefined"==typeof WeakMap&&!function(){var defineProperty=Object.defineProperty,counter=Date.now()%1e9,WeakMap=function(){this.name="__st"+(1e9*Math.random()>>>0)+(counter++ +"__")};WeakMap.prototype={set:function(key,value){var entry=key[this.name];return entry&&entry[0]===key?entry[1]=value:defineProperty(key,this.name,{value:[key,value],writable:!0}),this},get:function(key){var entry;return(entry=key[this.name])&&entry[0]===key?entry[1]:void 0},"delete":function(key){var entry=key[this.name];return entry&&entry[0]===key?(entry[0]=entry[1]=void 0,!0):!1},has:function(key){var entry=key[this.name];return entry?entry[0]===key:!1}},window.WeakMap=WeakMap}(),function(global){function scheduleCallback(observer){scheduledObservers.push(observer),isScheduled||(isScheduled=!0,setImmediate(dispatchCallbacks))}function wrapIfNeeded(node){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(node)||node}function dispatchCallbacks(){isScheduled=!1;var observers=scheduledObservers;scheduledObservers=[],observers.sort(function(o1,o2){return o1.uid_-o2.uid_});var anyNonEmpty=!1;observers.forEach(function(observer){var queue=observer.takeRecords();removeTransientObserversFor(observer),queue.length&&(observer.callback_(queue,observer),anyNonEmpty=!0)}),anyNonEmpty&&dispatchCallbacks()}function removeTransientObserversFor(observer){observer.nodes_.forEach(function(node){var registrations=registrationsTable.get(node);registrations&&registrations.forEach(function(registration){registration.observer===observer&&registration.removeTransientObservers()})})}function forEachAncestorAndObserverEnqueueRecord(target,callback){for(var node=target;node;node=node.parentNode){var registrations=registrationsTable.get(node);if(registrations)for(var j=0;j<registrations.length;j++){var registration=registrations[j],options=registration.options;if(node===target||options.subtree){var record=callback(options);record&&registration.enqueue(record)}}}}function JsMutationObserver(callback){this.callback_=callback,this.nodes_=[],this.records_=[],this.uid_=++uidCounter}function MutationRecord(type,target){this.type=type,this.target=target,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function copyMutationRecord(original){var record=new MutationRecord(original.type,original.target);return record.addedNodes=original.addedNodes.slice(),record.removedNodes=original.removedNodes.slice(),record.previousSibling=original.previousSibling,record.nextSibling=original.nextSibling,record.attributeName=original.attributeName,record.attributeNamespace=original.attributeNamespace,record.oldValue=original.oldValue,record}function getRecord(type,target){return currentRecord=new MutationRecord(type,target)}function getRecordWithOldValue(oldValue){return recordWithOldValue?recordWithOldValue:(recordWithOldValue=copyMutationRecord(currentRecord),recordWithOldValue.oldValue=oldValue,recordWithOldValue)}function clearRecords(){currentRecord=recordWithOldValue=void 0}function recordRepresentsCurrentMutation(record){return record===recordWithOldValue||record===currentRecord}function selectRecord(lastRecord,newRecord){return lastRecord===newRecord?lastRecord:recordWithOldValue&&recordRepresentsCurrentMutation(lastRecord)?recordWithOldValue:null}function Registration(observer,target,options){this.observer=observer,this.target=target,this.options=options,this.transientObservedNodes=[]}var setImmediate,registrationsTable=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))setImmediate=setTimeout;else if(window.setImmediate)setImmediate=window.setImmediate;else{var setImmediateQueue=[],sentinel=String(Math.random());window.addEventListener("message",function(e){if(e.data===sentinel){var queue=setImmediateQueue;setImmediateQueue=[],queue.forEach(function(func){func()})}}),setImmediate=function(func){setImmediateQueue.push(func),window.postMessage(sentinel,"*")}}var isScheduled=!1,scheduledObservers=[],uidCounter=0;JsMutationObserver.prototype={observe:function(target,options){if(target=wrapIfNeeded(target),!options.childList&&!options.attributes&&!options.characterData||options.attributeOldValue&&!options.attributes||options.attributeFilter&&options.attributeFilter.length&&!options.attributes||options.characterDataOldValue&&!options.characterData)throw new SyntaxError;var registrations=registrationsTable.get(target);registrations||registrationsTable.set(target,registrations=[]);for(var registration,i=0;i<registrations.length;i++)if(registrations[i].observer===this){registration=registrations[i],registration.removeListeners(),registration.options=options;break}registration||(registration=new Registration(this,target,options),registrations.push(registration),this.nodes_.push(target)),registration.addListeners()},disconnect:function(){this.nodes_.forEach(function(node){for(var registrations=registrationsTable.get(node),i=0;i<registrations.length;i++){var registration=registrations[i];if(registration.observer===this){registration.removeListeners(),registrations.splice(i,1);break}}},this),this.records_=[]},takeRecords:function(){var copyOfRecords=this.records_;return this.records_=[],copyOfRecords}};var currentRecord,recordWithOldValue;Registration.prototype={enqueue:function(record){var records=this.observer.records_,length=records.length;if(records.length>0){var lastRecord=records[length-1],recordToReplaceLast=selectRecord(lastRecord,record);if(recordToReplaceLast)return void(records[length-1]=recordToReplaceLast)}else scheduleCallback(this.observer);records[length]=record},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(node){var options=this.options;options.attributes&&node.addEventListener("DOMAttrModified",this,!0),options.characterData&&node.addEventListener("DOMCharacterDataModified",this,!0),options.childList&&node.addEventListener("DOMNodeInserted",this,!0),(options.childList||options.subtree)&&node.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(node){var options=this.options;options.attributes&&node.removeEventListener("DOMAttrModified",this,!0),options.characterData&&node.removeEventListener("DOMCharacterDataModified",this,!0),options.childList&&node.removeEventListener("DOMNodeInserted",this,!0),(options.childList||options.subtree)&&node.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(node){if(node!==this.target){this.addListeners_(node),this.transientObservedNodes.push(node);var registrations=registrationsTable.get(node);registrations||registrationsTable.set(node,registrations=[]),registrations.push(this)}},removeTransientObservers:function(){var transientObservedNodes=this.transientObservedNodes;this.transientObservedNodes=[],transientObservedNodes.forEach(function(node){this.removeListeners_(node);for(var registrations=registrationsTable.get(node),i=0;i<registrations.length;i++)if(registrations[i]===this){registrations.splice(i,1);break}},this)},handleEvent:function(e){switch(e.stopImmediatePropagation(),e.type){case"DOMAttrModified":var name=e.attrName,namespace=e.relatedNode.namespaceURI,target=e.target,record=new getRecord("attributes",target);record.attributeName=name,record.attributeNamespace=namespace;var oldValue=e.attrChange===MutationEvent.ADDITION?null:e.prevValue;forEachAncestorAndObserverEnqueueRecord(target,function(options){return!options.attributes||options.attributeFilter&&options.attributeFilter.length&&-1===options.attributeFilter.indexOf(name)&&-1===options.attributeFilter.indexOf(namespace)?void 0:options.attributeOldValue?getRecordWithOldValue(oldValue):record});break;case"DOMCharacterDataModified":var target=e.target,record=getRecord("characterData",target),oldValue=e.prevValue;forEachAncestorAndObserverEnqueueRecord(target,function(options){return options.characterData?options.characterDataOldValue?getRecordWithOldValue(oldValue):record:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(e.target);case"DOMNodeInserted":var addedNodes,removedNodes,changedNode=e.target;"DOMNodeInserted"===e.type?(addedNodes=[changedNode],removedNodes=[]):(addedNodes=[],removedNodes=[changedNode]);var previousSibling=changedNode.previousSibling,nextSibling=changedNode.nextSibling,record=getRecord("childList",e.target.parentNode);record.addedNodes=addedNodes,record.removedNodes=removedNodes,record.previousSibling=previousSibling,record.nextSibling=nextSibling,forEachAncestorAndObserverEnqueueRecord(e.relatedNode,function(options){return options.childList?record:void 0})}clearRecords()}},global.JsMutationObserver=JsMutationObserver,global.MutationObserver||(global.MutationObserver=JsMutationObserver)}(this),window.CustomElements=window.CustomElements||{flags:{}},function(scope){var flags=scope.flags,modules=[],addModule=function(module){modules.push(module)},initializeModules=function(){modules.forEach(function(module){module(scope)})};scope.addModule=addModule,scope.initializeModules=initializeModules,scope.hasNative=Boolean(document.registerElement),scope.useNative=!flags.register&&scope.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||HTMLImports.useNative)}(window.CustomElements),window.CustomElements.addModule(function(scope){function forSubtree(node,cb){findAllElements(node,function(e){return cb(e)?!0:void forRoots(e,cb)}),forRoots(node,cb)}function findAllElements(node,find,data){var e=node.firstElementChild;if(!e)for(e=node.firstChild;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;for(;e;)find(e,data)!==!0&&findAllElements(e,find,data),e=e.nextElementSibling;return null}function forRoots(node,cb){for(var root=node.shadowRoot;root;)forSubtree(root,cb),root=root.olderShadowRoot}function forDocumentTree(doc,cb){_forDocumentTree(doc,cb,[])}function _forDocumentTree(doc,cb,processingDocuments){if(doc=wrap(doc),!(processingDocuments.indexOf(doc)>=0)){processingDocuments.push(doc);for(var n,imports=doc.querySelectorAll("link[rel="+IMPORT_LINK_TYPE+"]"),i=0,l=imports.length;l>i&&(n=imports[i]);i++)n["import"]&&_forDocumentTree(n["import"],cb,processingDocuments);cb(doc)}}var IMPORT_LINK_TYPE=window.HTMLImports?HTMLImports.IMPORT_LINK_TYPE:"none";scope.forDocumentTree=forDocumentTree,scope.forSubtree=forSubtree}),window.CustomElements.addModule(function(scope){function addedNode(node){return added(node)||addedSubtree(node)}function added(node){return scope.upgrade(node)?!0:void attached(node)}function addedSubtree(node){forSubtree(node,function(e){return added(e)?!0:void 0})}function attachedNode(node){attached(node),inDocument(node)&&forSubtree(node,function(e){attached(e)})}function deferMutation(fn){pendingMutations.push(fn),isPendingMutations||(isPendingMutations=!0,setTimeout(takeMutations))}function takeMutations(){isPendingMutations=!1;for(var p,$p=pendingMutations,i=0,l=$p.length;l>i&&(p=$p[i]);i++)p();pendingMutations=[]}function attached(element){hasPolyfillMutations?deferMutation(function(){_attached(element)}):_attached(element)}function _attached(element){element.__upgraded__&&(element.attachedCallback||element.detachedCallback)&&!element.__attached&&inDocument(element)&&(element.__attached=!0,element.attachedCallback&&element.attachedCallback())}function detachedNode(node){detached(node),forSubtree(node,function(e){detached(e)})}function detached(element){hasPolyfillMutations?deferMutation(function(){_detached(element)}):_detached(element)}function _detached(element){element.__upgraded__&&(element.attachedCallback||element.detachedCallback)&&element.__attached&&!inDocument(element)&&(element.__attached=!1,element.detachedCallback&&element.detachedCallback())}function inDocument(element){for(var p=element,doc=wrap(document);p;){if(p==doc)return!0;p=p.parentNode||p.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&p.host}}function watchShadow(node){if(node.shadowRoot&&!node.shadowRoot.__watched){flags.dom&&console.log("watching shadow-root for: ",node.localName);for(var root=node.shadowRoot;root;)observe(root),root=root.olderShadowRoot}}function handler(mutations){if(flags.dom){var mx=mutations[0];if(mx&&"childList"===mx.type&&mx.addedNodes&&mx.addedNodes){for(var d=mx.addedNodes[0];d&&d!==document&&!d.host;)d=d.parentNode;var u=d&&(d.URL||d._URL||d.host&&d.host.localName)||"";u=u.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",mutations.length,u||"")}mutations.forEach(function(mx){"childList"===mx.type&&(forEach(mx.addedNodes,function(n){n.localName&&addedNode(n)}),forEach(mx.removedNodes,function(n){n.localName&&detachedNode(n)}))}),flags.dom&&console.groupEnd()}function takeRecords(node){for(node=wrap(node),node||(node=wrap(document));node.parentNode;)node=node.parentNode;var observer=node.__observer;observer&&(handler(observer.takeRecords()),takeMutations())}function observe(inRoot){if(!inRoot.__observer){var observer=new MutationObserver(handler);observer.observe(inRoot,{childList:!0,subtree:!0}),inRoot.__observer=observer}}function upgradeDocument(doc){doc=wrap(doc),flags.dom&&console.group("upgradeDocument: ",doc.baseURI.split("/").pop()),addedNode(doc),observe(doc),flags.dom&&console.groupEnd()}function upgradeDocumentTree(doc){forDocumentTree(doc,upgradeDocument)}var flags=scope.flags,forSubtree=scope.forSubtree,forDocumentTree=scope.forDocumentTree,hasPolyfillMutations=!window.MutationObserver||window.MutationObserver===window.JsMutationObserver;scope.hasPolyfillMutations=hasPolyfillMutations;var isPendingMutations=!1,pendingMutations=[],forEach=Array.prototype.forEach.call.bind(Array.prototype.forEach),originalCreateShadowRoot=Element.prototype.createShadowRoot;originalCreateShadowRoot&&(Element.prototype.createShadowRoot=function(){var root=originalCreateShadowRoot.call(this);return CustomElements.watchShadow(this),root}),scope.watchShadow=watchShadow,scope.upgradeDocumentTree=upgradeDocumentTree,scope.upgradeSubtree=addedSubtree,scope.upgradeAll=addedNode,scope.attachedNode=attachedNode,scope.takeRecords=takeRecords}),window.CustomElements.addModule(function(scope){function upgrade(node){if(!node.__upgraded__&&node.nodeType===Node.ELEMENT_NODE){var is=node.getAttribute("is"),definition=scope.getRegisteredDefinition(is||node.localName);if(definition){if(is&&definition.tag==node.localName)return upgradeWithDefinition(node,definition);if(!is&&!definition["extends"])return upgradeWithDefinition(node,definition)}}}function upgradeWithDefinition(element,definition){return flags.upgrade&&console.group("upgrade:",element.localName),definition.is&&element.setAttribute("is",definition.is),implementPrototype(element,definition),element.__upgraded__=!0,created(element),scope.attachedNode(element),scope.upgradeSubtree(element),flags.upgrade&&console.groupEnd(),element}function implementPrototype(element,definition){Object.__proto__?element.__proto__=definition.prototype:(customMixin(element,definition.prototype,definition["native"]),element.__proto__=definition.prototype)}function customMixin(inTarget,inSrc,inNative){for(var used={},p=inSrc;p!==inNative&&p!==HTMLElement.prototype;){for(var k,keys=Object.getOwnPropertyNames(p),i=0;k=keys[i];i++)used[k]||(Object.defineProperty(inTarget,k,Object.getOwnPropertyDescriptor(p,k)),used[k]=1);p=Object.getPrototypeOf(p)}}function created(element){element.createdCallback&&element.createdCallback()}var flags=scope.flags;scope.upgrade=upgrade,scope.upgradeWithDefinition=upgradeWithDefinition,scope.implementPrototype=implementPrototype}),window.CustomElements.addModule(function(scope){function register(name,options){var definition=options||{};if(!name)throw new Error("document.registerElement: first argument `name` must not be empty");if(name.indexOf("-")<0)throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+String(name)+"'.");if(isReservedTag(name))throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+String(name)+"'. The type name is invalid.");if(getRegisteredDefinition(name))throw new Error("DuplicateDefinitionError: a type with name '"+String(name)+"' is already registered");return definition.prototype||(definition.prototype=Object.create(HTMLElement.prototype)),definition.__name=name.toLowerCase(),definition.lifecycle=definition.lifecycle||{},definition.ancestry=ancestry(definition["extends"]),resolveTagName(definition),resolvePrototypeChain(definition),overrideAttributeApi(definition.prototype),registerDefinition(definition.__name,definition),definition.ctor=generateConstructor(definition),definition.ctor.prototype=definition.prototype,definition.prototype.constructor=definition.ctor,scope.ready&&upgradeDocumentTree(document),definition.ctor}function overrideAttributeApi(prototype){if(!prototype.setAttribute._polyfilled){var setAttribute=prototype.setAttribute;prototype.setAttribute=function(name,value){changeAttribute.call(this,name,value,setAttribute)};var removeAttribute=prototype.removeAttribute;prototype.removeAttribute=function(name){changeAttribute.call(this,name,null,removeAttribute)},prototype.setAttribute._polyfilled=!0}}function changeAttribute(name,value,operation){name=name.toLowerCase();var oldValue=this.getAttribute(name);operation.apply(this,arguments);var newValue=this.getAttribute(name);this.attributeChangedCallback&&newValue!==oldValue&&this.attributeChangedCallback(name,oldValue,newValue)}function isReservedTag(name){for(var i=0;i<reservedTagList.length;i++)if(name===reservedTagList[i])return!0}function ancestry(extnds){var extendee=getRegisteredDefinition(extnds);return extendee?ancestry(extendee["extends"]).concat([extendee]):[]}function resolveTagName(definition){for(var a,baseTag=definition["extends"],i=0;a=definition.ancestry[i];i++)baseTag=a.is&&a.tag;definition.tag=baseTag||definition.__name,baseTag&&(definition.is=definition.__name)}function resolvePrototypeChain(definition){if(!Object.__proto__){var nativePrototype=HTMLElement.prototype;if(definition.is){var inst=document.createElement(definition.tag),expectedPrototype=Object.getPrototypeOf(inst);expectedPrototype===definition.prototype&&(nativePrototype=expectedPrototype)}for(var ancestor,proto=definition.prototype;proto&&proto!==nativePrototype;)ancestor=Object.getPrototypeOf(proto),proto.__proto__=ancestor,proto=ancestor;definition["native"]=nativePrototype}}function instantiate(definition){return upgradeWithDefinition(domCreateElement(definition.tag),definition)}function getRegisteredDefinition(name){return name?registry[name.toLowerCase()]:void 0}function registerDefinition(name,definition){registry[name]=definition}function generateConstructor(definition){return function(){return instantiate(definition)}}function createElementNS(namespace,tag,typeExtension){return namespace===HTML_NAMESPACE?createElement(tag,typeExtension):domCreateElementNS(namespace,tag)}function createElement(tag,typeExtension){tag&&(tag=tag.toLowerCase()),typeExtension&&(typeExtension=typeExtension.toLowerCase());var definition=getRegisteredDefinition(typeExtension||tag);if(definition){if(tag==definition.tag&&typeExtension==definition.is)return new definition.ctor;if(!typeExtension&&!definition.is)return new definition.ctor}var element;return typeExtension?(element=createElement(tag),element.setAttribute("is",typeExtension),element):(element=domCreateElement(tag),tag.indexOf("-")>=0&&implementPrototype(element,HTMLElement),element)}function wrapDomMethodToForceUpgrade(obj,methodName){var orig=obj[methodName];obj[methodName]=function(){var n=orig.apply(this,arguments);return upgradeAll(n),n}}var isInstance,isIE11OrOlder=scope.isIE11OrOlder,upgradeDocumentTree=scope.upgradeDocumentTree,upgradeAll=scope.upgradeAll,upgradeWithDefinition=scope.upgradeWithDefinition,implementPrototype=scope.implementPrototype,useNative=scope.useNative,reservedTagList=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],registry={},HTML_NAMESPACE="http://www.w3.org/1999/xhtml",domCreateElement=document.createElement.bind(document),domCreateElementNS=document.createElementNS.bind(document);isInstance=Object.__proto__||useNative?function(obj,base){return obj instanceof base}:function(obj,ctor){for(var p=obj;p;){if(p===ctor.prototype)return!0;p=p.__proto__}return!1},wrapDomMethodToForceUpgrade(Node.prototype,"cloneNode"),wrapDomMethodToForceUpgrade(document,"importNode"),isIE11OrOlder&&!function(){var importNode=document.importNode;document.importNode=function(){var n=importNode.apply(document,arguments);if(n.nodeType==n.DOCUMENT_FRAGMENT_NODE){var f=document.createDocumentFragment();return f.appendChild(n),f}return n}}(),document.registerElement=register,document.createElement=createElement,document.createElementNS=createElementNS,scope.registry=registry,scope["instanceof"]=isInstance,scope.reservedTagList=reservedTagList,scope.getRegisteredDefinition=getRegisteredDefinition,document.register=document.registerElement}),function(scope){function bootstrap(){upgradeDocumentTree(wrap(document)),window.HTMLImports&&(HTMLImports.__importsParsingHook=function(elt){upgradeDocumentTree(wrap(elt["import"]))}),CustomElements.ready=!0,setTimeout(function(){CustomElements.readyTime=Date.now(),window.HTMLImports&&(CustomElements.elapsed=CustomElements.readyTime-HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})}var useNative=scope.useNative,initializeModules=scope.initializeModules,isIE11OrOlder=/Trident/.test(navigator.userAgent);if(useNative){var nop=function(){};scope.watchShadow=nop,scope.upgrade=nop,scope.upgradeAll=nop,scope.upgradeDocumentTree=nop,scope.upgradeSubtree=nop,scope.takeRecords=nop,scope["instanceof"]=function(obj,base){return obj instanceof base}}else initializeModules();var upgradeDocumentTree=scope.upgradeDocumentTree;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(node){return node}),isIE11OrOlder&&"function"!=typeof window.CustomEvent&&(window.CustomEvent=function(inType,params){params=params||{};var e=document.createEvent("CustomEvent");return e.initCustomEvent(inType,Boolean(params.bubbles),Boolean(params.cancelable),params.detail),e},window.CustomEvent.prototype=window.Event.prototype),"complete"===document.readyState||scope.flags.eager)bootstrap();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var loadEvent=window.HTMLImports&&!HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(loadEvent,bootstrap)}else bootstrap();scope.isIE11OrOlder=isIE11OrOlder}(window.CustomElements),window.CustomEvent||!function(){var CustomEvent;CustomEvent=function(event,params){var evt;return params=params||{bubbles:!1,cancelable:!1,detail:void 0},evt=document.createEvent("CustomEvent"),evt.initCustomEvent(event,params.bubbles,params.cancelable,params.detail),evt},CustomEvent.prototype=window.Event.prototype,window.CustomEvent=CustomEvent}(),function(){"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)})}(),"document"in self&&("classList"in document.createElement("_")&&(!document.createElementNS||"classList"in document.createElementNS("http://www.w3.org/2000/svg","g"))?!function(){"use strict";var testElement=document.createElement("_");if(testElement.classList.add("c1","c2"),!testElement.classList.contains("c2")){var createMethod=function(method){var original=DOMTokenList.prototype[method];DOMTokenList.prototype[method]=function(token){var i,len=arguments.length;for(i=0;len>i;i++)token=arguments[i],original.call(this,token)}};createMethod("add"),createMethod("remove")}if(testElement.classList.toggle("c3",!1),testElement.classList.contains("c3")){var _toggle=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(token,force){return 1 in arguments&&!this.contains(token)==!force?force:_toggle.call(this,token)}}testElement=null}():!function(view){"use strict";if("Element"in view){var classListProp="classList",protoProp="prototype",elemCtrProto=view.Element[protoProp],objCtr=Object,strTrim=String[protoProp].trim||function(){return this.replace(/^\s+|\s+$/g,"")},arrIndexOf=Array[protoProp].indexOf||function(item){for(var i=0,len=this.length;len>i;i++)if(i in this&&this[i]===item)return i;return-1},DOMEx=function(type,message){this.name=type,this.code=DOMException[type],this.message=message},checkTokenAndGetIndex=function(classList,token){if(""===token)throw new DOMEx("SYNTAX_ERR","An invalid or illegal string was specified");if(/\s/.test(token))throw new DOMEx("INVALID_CHARACTER_ERR","String contains an invalid character");return arrIndexOf.call(classList,token)},ClassList=function(elem){for(var trimmedClasses=strTrim.call(elem.getAttribute("class")||""),classes=trimmedClasses?trimmedClasses.split(/\s+/):[],i=0,len=classes.length;len>i;i++)this.push(classes[i]);this._updateClassName=function(){elem.setAttribute("class",this.toString())}},classListProto=ClassList[protoProp]=[],classListGetter=function(){return new ClassList(this)};if(DOMEx[protoProp]=Error[protoProp],classListProto.item=function(i){return this[i]||null},classListProto.contains=function(token){return token+="",-1!==checkTokenAndGetIndex(this,token)},classListProto.add=function(){var token,tokens=arguments,i=0,l=tokens.length,updated=!1;do token=tokens[i]+"",-1===checkTokenAndGetIndex(this,token)&&(this.push(token),updated=!0);while(++i<l);updated&&this._updateClassName()},classListProto.remove=function(){var token,index,tokens=arguments,i=0,l=tokens.length,updated=!1;do for(token=tokens[i]+"",index=checkTokenAndGetIndex(this,token);-1!==index;)this.splice(index,1),updated=!0,index=checkTokenAndGetIndex(this,token);while(++i<l);updated&&this._updateClassName()},classListProto.toggle=function(token,force){token+="";var result=this.contains(token),method=result?force!==!0&&"remove":force!==!1&&"add";return method&&this[method](token),force===!0||force===!1?force:!result},classListProto.toString=function(){return this.join(" ")},objCtr.defineProperty){var classListPropDesc={get:classListGetter,enumerable:!0,configurable:!0};try{objCtr.defineProperty(elemCtrProto,classListProp,classListPropDesc)}catch(ex){-2146823252===ex.number&&(classListPropDesc.enumerable=!1,objCtr.defineProperty(elemCtrProto,classListProp,classListPropDesc))}}else objCtr[protoProp].__defineGetter__&&elemCtrProto.__defineGetter__(classListProp,classListGetter)}}(self)),function(){"use strict";function FastClick(layer,options){function bind(method,context){return function(){return method.apply(context,arguments)}}var oldOnClick;if(options=options||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=options.touchBoundary||10,this.layer=layer,this.tapDelay=options.tapDelay||200,this.tapTimeout=options.tapTimeout||700,!FastClick.notNeeded(layer)){for(var methods=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],context=this,i=0,l=methods.length;l>i;i++)context[methods[i]]=bind(context[methods[i]],context);deviceIsAndroid&&(layer.addEventListener("mouseover",this.onMouse,!0),layer.addEventListener("mousedown",this.onMouse,!0),layer.addEventListener("mouseup",this.onMouse,!0)),layer.addEventListener("click",this.onClick,!0),layer.addEventListener("touchstart",this.onTouchStart,!1),layer.addEventListener("touchmove",this.onTouchMove,!1),layer.addEventListener("touchend",this.onTouchEnd,!1),layer.addEventListener("touchcancel",this.onTouchCancel,!1),Event.prototype.stopImmediatePropagation||(layer.removeEventListener=function(type,callback,capture){var rmv=Node.prototype.removeEventListener;"click"===type?rmv.call(layer,type,callback.hijacked||callback,capture):rmv.call(layer,type,callback,capture)},layer.addEventListener=function(type,callback,capture){var adv=Node.prototype.addEventListener;"click"===type?adv.call(layer,type,callback.hijacked||(callback.hijacked=function(event){event.propagationStopped||callback(event)}),capture):adv.call(layer,type,callback,capture)}),"function"==typeof layer.onclick&&(oldOnClick=layer.onclick,layer.addEventListener("click",function(event){oldOnClick(event)},!1),layer.onclick=null)}}var deviceIsWindowsPhone=navigator.userAgent.indexOf("Windows Phone")>=0,deviceIsAndroid=navigator.userAgent.indexOf("Android")>0&&!deviceIsWindowsPhone,deviceIsIOS=/iP(ad|hone|od)/.test(navigator.userAgent)&&!deviceIsWindowsPhone,deviceIsIOS4=deviceIsIOS&&/OS 4_\d(_\d)?/.test(navigator.userAgent),deviceIsIOSWithBadTarget=deviceIsIOS&&/OS [6-7]_\d/.test(navigator.userAgent),deviceIsBlackBerry10=navigator.userAgent.indexOf("BB10")>0;FastClick.prototype.needsClick=function(target){switch(target.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(target.disabled)return!0;break;case"input":if(deviceIsIOS&&"file"===target.type||target.disabled)return!0;break;case"label":case"iframe":case"video":return!0}return/\bneedsclick\b/.test(target.className)},FastClick.prototype.needsFocus=function(target){switch(target.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!deviceIsAndroid;case"input":switch(target.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!target.disabled&&!target.readOnly;default:return/\bneedsfocus\b/.test(target.className)}},FastClick.prototype.sendClick=function(targetElement,event){var clickEvent,touch;document.activeElement&&document.activeElement!==targetElement&&document.activeElement.blur(),touch=event.changedTouches[0],clickEvent=document.createEvent("MouseEvents"),clickEvent.initMouseEvent(this.determineEventType(targetElement),!0,!0,window,1,touch.screenX,touch.screenY,touch.clientX,touch.clientY,!1,!1,!1,!1,0,null),clickEvent.forwardedTouchEvent=!0,targetElement.dispatchEvent(clickEvent)},FastClick.prototype.determineEventType=function(targetElement){return deviceIsAndroid&&"select"===targetElement.tagName.toLowerCase()?"mousedown":"click"},FastClick.prototype.focus=function(targetElement){var length;deviceIsIOS&&targetElement.setSelectionRange&&0!==targetElement.type.indexOf("date")&&"time"!==targetElement.type&&"month"!==targetElement.type?(length=targetElement.value.length,targetElement.setSelectionRange(length,length)):targetElement.focus()},FastClick.prototype.updateScrollParent=function(targetElement){var scrollParent,parentElement;if(scrollParent=targetElement.fastClickScrollParent,!scrollParent||!scrollParent.contains(targetElement)){parentElement=targetElement;do{if(parentElement.scrollHeight>parentElement.offsetHeight){scrollParent=parentElement,targetElement.fastClickScrollParent=parentElement;break}parentElement=parentElement.parentElement}while(parentElement)}scrollParent&&(scrollParent.fastClickLastScrollTop=scrollParent.scrollTop)},FastClick.prototype.getTargetElementFromEventTarget=function(eventTarget){return eventTarget.nodeType===Node.TEXT_NODE?eventTarget.parentNode:eventTarget},FastClick.prototype.onTouchStart=function(event){var targetElement,touch,selection;if(event.targetTouches.length>1)return!0;if(targetElement=this.getTargetElementFromEventTarget(event.target),touch=event.targetTouches[0],deviceIsIOS){if(selection=window.getSelection(),selection.rangeCount&&!selection.isCollapsed)return!0;if(!deviceIsIOS4){if(touch.identifier&&touch.identifier===this.lastTouchIdentifier)return event.preventDefault(),!1;this.lastTouchIdentifier=touch.identifier,this.updateScrollParent(targetElement)}}return this.trackingClick=!0,this.trackingClickStart=event.timeStamp,this.targetElement=targetElement,this.touchStartX=touch.pageX,this.touchStartY=touch.pageY,event.timeStamp-this.lastClickTime<this.tapDelay&&event.timeStamp-this.lastClickTime>-1&&event.preventDefault(), !0},FastClick.prototype.touchHasMoved=function(event){var touch=event.changedTouches[0],boundary=this.touchBoundary;return Math.abs(touch.pageX-this.touchStartX)>boundary||Math.abs(touch.pageY-this.touchStartY)>boundary?!0:!1},FastClick.prototype.onTouchMove=function(event){return this.trackingClick?((this.targetElement!==this.getTargetElementFromEventTarget(event.target)||this.touchHasMoved(event))&&(this.trackingClick=!1,this.targetElement=null),!0):!0},FastClick.prototype.findControl=function(labelElement){return void 0!==labelElement.control?labelElement.control:labelElement.htmlFor?document.getElementById(labelElement.htmlFor):labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},FastClick.prototype.onTouchEnd=function(event){var forElement,trackingClickStart,targetTagName,scrollParent,touch,targetElement=this.targetElement;if(!this.trackingClick)return!0;if(event.timeStamp-this.lastClickTime<this.tapDelay&&event.timeStamp-this.lastClickTime>-1)return this.cancelNextClick=!0,!0;if(event.timeStamp-this.trackingClickStart>this.tapTimeout)return!0;if(this.cancelNextClick=!1,this.lastClickTime=event.timeStamp,trackingClickStart=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,deviceIsIOSWithBadTarget&&(touch=event.changedTouches[0],targetElement=document.elementFromPoint(touch.pageX-window.pageXOffset,touch.pageY-window.pageYOffset)||targetElement,targetElement.fastClickScrollParent=this.targetElement.fastClickScrollParent),targetTagName=targetElement.tagName.toLowerCase(),"label"===targetTagName){if(forElement=this.findControl(targetElement)){if(this.focus(targetElement),deviceIsAndroid)return!1;targetElement=forElement}}else if(this.needsFocus(targetElement))return event.timeStamp-trackingClickStart>100||deviceIsIOS&&window.top!==window&&"input"===targetTagName?(this.targetElement=null,!1):(this.focus(targetElement),this.sendClick(targetElement,event),deviceIsIOS&&"select"===targetTagName||(this.targetElement=null,event.preventDefault()),!1);return deviceIsIOS&&!deviceIsIOS4&&(scrollParent=targetElement.fastClickScrollParent,scrollParent&&scrollParent.fastClickLastScrollTop!==scrollParent.scrollTop)?!0:(this.needsClick(targetElement)||(event.preventDefault(),this.sendClick(targetElement,event)),!1)},FastClick.prototype.onTouchCancel=function(){this.trackingClick=!1,this.targetElement=null},FastClick.prototype.onMouse=function(event){return this.targetElement?event.forwardedTouchEvent?!0:event.cancelable&&(!this.needsClick(this.targetElement)||this.cancelNextClick)?(event.stopImmediatePropagation?event.stopImmediatePropagation():event.propagationStopped=!0,event.stopPropagation(),event.preventDefault(),!1):!0:!0},FastClick.prototype.onClick=function(event){var permitted;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===event.target.type&&0===event.detail?!0:(permitted=this.onMouse(event),permitted||(this.targetElement=null),permitted)},FastClick.prototype.destroy=function(){var layer=this.layer;deviceIsAndroid&&(layer.removeEventListener("mouseover",this.onMouse,!0),layer.removeEventListener("mousedown",this.onMouse,!0),layer.removeEventListener("mouseup",this.onMouse,!0)),layer.removeEventListener("click",this.onClick,!0),layer.removeEventListener("touchstart",this.onTouchStart,!1),layer.removeEventListener("touchmove",this.onTouchMove,!1),layer.removeEventListener("touchend",this.onTouchEnd,!1),layer.removeEventListener("touchcancel",this.onTouchCancel,!1)},FastClick.notNeeded=function(layer){var metaViewport,chromeVersion,blackberryVersion,firefoxVersion;if("undefined"==typeof window.ontouchstart)return!0;if(chromeVersion=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!deviceIsAndroid)return!0;if(metaViewport=document.querySelector("meta[name=viewport]")){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(chromeVersion>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(deviceIsBlackBerry10&&(blackberryVersion=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),blackberryVersion[1]>=10&&blackberryVersion[2]>=3&&(metaViewport=document.querySelector("meta[name=viewport]")))){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===layer.style.msTouchAction||"manipulation"===layer.style.touchAction?!0:(firefoxVersion=+(/Firefox\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1],firefoxVersion>=27&&(metaViewport=document.querySelector("meta[name=viewport]"),metaViewport&&(-1!==metaViewport.content.indexOf("user-scalable=no")||document.documentElement.scrollWidth<=window.outerWidth))?!0:"none"===layer.style.touchAction||"manipulation"===layer.style.touchAction?!0:!1)},FastClick.attach=function(layer,options){return new FastClick(layer,options)},window.FastClick=FastClick}();var MicroEvent=function(){};MicroEvent.prototype={on:function(event,fct){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fct)},once:function(event,fct){var self=this,wrapper=function(){return self.off(event,wrapper),fct.apply(null,arguments)};this.on(event,wrapper)},off:function(event,fct){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fct),1)},emit:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},MicroEvent.mixin=function(destObject){for(var props=["on","once","off","emit"],i=0;i<props.length;i++)"function"==typeof destObject?destObject.prototype[props[i]]=MicroEvent.prototype[props[i]]:destObject[props[i]]=MicroEvent.prototype[props[i]]},"undefined"!=typeof module&&"exports"in module&&(module.exports=MicroEvent),!function(e,t,n){function r(e,t){return typeof e===t}function o(){var e,t,n,o,i,s,a;for(var l in S)if(S.hasOwnProperty(l)){if(e=[],t=S[l],t.name&&(e.push(t.name.toLowerCase()),t.options&&t.options.aliases&&t.options.aliases.length))for(n=0;n<t.options.aliases.length;n++)e.push(t.options.aliases[n].toLowerCase());for(o=r(t.fn,"function")?t.fn():t.fn,i=0;i<e.length;i++)s=e[i],a=s.split("."),1===a.length?Modernizr[a[0]]=o:(!Modernizr[a[0]]||Modernizr[a[0]]instanceof Boolean||(Modernizr[a[0]]=new Boolean(Modernizr[a[0]])),Modernizr[a[0]][a[1]]=o),C.push((o?"":"no-")+a.join("-"))}}function i(e){var t=w.className,n=Modernizr._config.classPrefix||"";if(_&&(t=t.baseVal),Modernizr._config.enableJSClass){var r=new RegExp("(^|\\s)"+n+"no-js(\\s|$)");t=t.replace(r,"$1"+n+"js$2")}Modernizr._config.enableClasses&&(t+=" "+n+e.join(" "+n),_?w.className.baseVal=t:w.className=t)}function s(e,t){if("object"==typeof e)for(var n in e)N(e,n)&&s(n,e[n]);else{e=e.toLowerCase();var r=e.split("."),o=Modernizr[r[0]];if(2==r.length&&(o=o[r[1]]),"undefined"!=typeof o)return Modernizr;t="function"==typeof t?t():t,1==r.length?Modernizr[r[0]]=t:(!Modernizr[r[0]]||Modernizr[r[0]]instanceof Boolean||(Modernizr[r[0]]=new Boolean(Modernizr[r[0]])),Modernizr[r[0]][r[1]]=t),i([(t&&0!=t?"":"no-")+r.join("-")]),Modernizr._trigger(e,t)}return Modernizr}function a(){return"function"!=typeof t.createElement?t.createElement(arguments[0]):_?t.createElementNS.call(t,"http://www.w3.org/2000/svg",arguments[0]):t.createElement.apply(t,arguments)}function l(e,t){return!!~(""+e).indexOf(t)}function u(){var e=t.body;return e||(e=a(_?"svg":"body"),e.fake=!0),e}function f(e,n,r,o){var i,s,l,f,c="modernizr",d=a("div"),p=u();if(parseInt(r,10))for(;r--;)l=a("div"),l.id=o?o[r]:c+(r+1),d.appendChild(l);return i=a("style"),i.type="text/css",i.id="s"+c,(p.fake?p:d).appendChild(i),p.appendChild(d),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(t.createTextNode(e)),d.id=c,p.fake&&(p.style.background="",p.style.overflow="hidden",f=w.style.overflow,w.style.overflow="hidden",w.appendChild(p)),s=n(d,e),p.fake?(p.parentNode.removeChild(p),w.style.overflow=f,w.offsetHeight):d.parentNode.removeChild(d),!!s}function c(e){return e.replace(/([a-z])-([a-z])/g,function(e,t,n){return t+n.toUpperCase()}).replace(/^-/,"")}function d(e,t){return function(){return e.apply(t,arguments)}}function p(e,t,n){var o;for(var i in e)if(e[i]in t)return n===!1?e[i]:(o=t[e[i]],r(o,"function")?d(o,n||t):o);return!1}function m(e){return e.replace(/([A-Z])/g,function(e,t){return"-"+t.toLowerCase()}).replace(/^ms-/,"-ms-")}function h(t,r){var o=t.length;if("CSS"in e&&"supports"in e.CSS){for(;o--;)if(e.CSS.supports(m(t[o]),r))return!0;return!1}if("CSSSupportsRule"in e){for(var i=[];o--;)i.push("("+m(t[o])+":"+r+")");return i=i.join(" or "),f("@supports ("+i+") { #modernizr { position: absolute; } }",function(e){return"absolute"==getComputedStyle(e,null).position})}return n}function g(e,t,o,i){function s(){f&&(delete L.style,delete L.modElem)}if(i=r(i,"undefined")?!1:i,!r(o,"undefined")){var u=h(e,o);if(!r(u,"undefined"))return u}for(var f,d,p,m,g,v=["modernizr","tspan"];!L.style;)f=!0,L.modElem=a(v.shift()),L.style=L.modElem.style;for(p=e.length,d=0;p>d;d++)if(m=e[d],g=L.style[m],l(m,"-")&&(m=c(m)),L.style[m]!==n){if(i||r(o,"undefined"))return s(),"pfx"==t?m:!0;try{L.style[m]=o}catch(y){}if(L.style[m]!=g)return s(),"pfx"==t?m:!0}return s(),!1}function v(e,t,n,o,i){var s=e.charAt(0).toUpperCase()+e.slice(1),a=(e+" "+k.join(s+" ")+s).split(" ");return r(t,"string")||r(t,"undefined")?g(a,t,o,i):(a=(e+" "+T.join(s+" ")+s).split(" "),p(a,t,n))}function y(e,t,r){return v(e,n,n,t,r)}var C=[],S=[],x={_version:"3.1.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,t){var n=this;setTimeout(function(){t(n[e])},0)},addTest:function(e,t,n){S.push({name:e,fn:t,options:n})},addAsyncTest:function(e){S.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=x,Modernizr=new Modernizr,Modernizr.addTest("svg",!!t.createElementNS&&!!t.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect);var b=x._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):[];x._prefixes=b;var w=t.documentElement,_="svg"===w.nodeName.toLowerCase();_||!function(e,t){function n(e,t){var n=e.createElement("p"),r=e.getElementsByTagName("head")[0]||e.documentElement;return n.innerHTML="x<style>"+t+"</style>",r.insertBefore(n.lastChild,r.firstChild)}function r(){var e=C.elements;return"string"==typeof e?e.split(" "):e}function o(e,t){var n=C.elements;"string"!=typeof n&&(n=n.join(" ")),"string"!=typeof e&&(e=e.join(" ")),C.elements=n+" "+e,u(t)}function i(e){var t=y[e[g]];return t||(t={},v++,e[g]=v,y[v]=t),t}function s(e,n,r){if(n||(n=t),c)return n.createElement(e);r||(r=i(n));var o;return o=r.cache[e]?r.cache[e].cloneNode():h.test(e)?(r.cache[e]=r.createElem(e)).cloneNode():r.createElem(e),!o.canHaveChildren||m.test(e)||o.tagUrn?o:r.frag.appendChild(o)}function a(e,n){if(e||(e=t),c)return e.createDocumentFragment();n=n||i(e);for(var o=n.frag.cloneNode(),s=0,a=r(),l=a.length;l>s;s++)o.createElement(a[s]);return o}function l(e,t){t.cache||(t.cache={},t.createElem=e.createElement,t.createFrag=e.createDocumentFragment,t.frag=t.createFrag()),e.createElement=function(n){return C.shivMethods?s(n,e,t):t.createElem(n)},e.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+r().join().replace(/[\w\-:]+/g,function(e){return t.createElem(e),t.frag.createElement(e),'c("'+e+'")'})+");return n}")(C,t.frag)}function u(e){e||(e=t);var r=i(e);return!C.shivCSS||f||r.hasCSS||(r.hasCSS=!!n(e,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),c||l(e,r),e}var f,c,d="3.7.3",p=e.html5||{},m=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,h=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,g="_html5shiv",v=0,y={};!function(){try{var e=t.createElement("a");e.innerHTML="<xyz></xyz>",f="hidden"in e,c=1==e.childNodes.length||function(){t.createElement("a");var e=t.createDocumentFragment();return"undefined"==typeof e.cloneNode||"undefined"==typeof e.createDocumentFragment||"undefined"==typeof e.createElement}()}catch(n){f=!0,c=!0}}();var C={elements:p.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:d,shivCSS:p.shivCSS!==!1,supportsUnknownElements:c,shivMethods:p.shivMethods!==!1,type:"default",shivDocument:u,createElement:s,createDocumentFragment:a,addElements:o};e.html5=C,u(t),"object"==typeof module&&module.exports&&(module.exports=C)}("undefined"!=typeof e?e:this,t);var E="Moz O ms Webkit",T=x._config.usePrefixes?E.toLowerCase().split(" "):[];x._domPrefixes=T;var N;!function(){var e={}.hasOwnProperty;N=r(e,"undefined")||r(e.call,"undefined")?function(e,t){return t in e&&r(e.constructor.prototype[t],"undefined")}:function(t,n){return e.call(t,n)}}(),x._l={},x.on=function(e,t){this._l[e]||(this._l[e]=[]),this._l[e].push(t),Modernizr.hasOwnProperty(e)&&setTimeout(function(){Modernizr._trigger(e,Modernizr[e])},0)},x._trigger=function(e,t){if(this._l[e]){var n=this._l[e];setTimeout(function(){var e,r;for(e=0;e<n.length;e++)(r=n[e])(t)},0),delete this._l[e]}},Modernizr._q.push(function(){x.addTest=s}),Modernizr.addTest("canvas",function(){var e=a("canvas");return!(!e.getContext||!e.getContext("2d"))});var P="CSS"in e&&"supports"in e.CSS,j="supportsCSS"in e;Modernizr.addTest("supports",P||j);var k=x._config.usePrefixes?E.split(" "):[];x._cssomPrefixes=k;var z=x.testStyles=f,F={elem:a("modernizr")};Modernizr._q.push(function(){delete F.elem});var L={style:F.elem.style};Modernizr._q.unshift(function(){delete L.style}),x.testProp=function(e,t,r){return g([e],n,t,r)},x.testAllProps=v,x.testAllProps=y,Modernizr.addTest("borderradius",y("borderRadius","0px",!0)),Modernizr.addTest("boxshadow",y("boxShadow","1px 1px",!0)),Modernizr.addTest("cssanimations",y("animationName","a",!0)),Modernizr.addTest("csstransforms",function(){return-1===navigator.userAgent.indexOf("Android 2.")&&y("transform","scale(1)",!0)}),Modernizr.addTest("csstransforms3d",function(){var e=!!y("perspective","1px",!0),t=Modernizr._config.usePrefixes;if(e&&(!t||"webkitPerspective"in w.style)){var n;Modernizr.supports?n="@supports (perspective: 1px)":(n="@media (transform-3d)",t&&(n+=",(-webkit-transform-3d)")),n+="{#modernizr{left:9px;position:absolute;height:5px;margin:0;padding:0;border:0}}",z(n,function(t){e=9===t.offsetLeft&&5===t.offsetHeight})}return e}),Modernizr.addTest("csstransitions",y("transition","all",!0)),o(),i(C),delete x.addTest,delete x.addAsyncTest;for(var A=0;A<Modernizr._q.length;A++)Modernizr._q[A]();e.Modernizr=Modernizr}(window,document),!function n(t,e,r){function o(u,f){if(!e[u]){if(!t[u]){var c="function"==typeof require&&require;if(!f&&c)return c(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var l=e[u]={exports:{}};t[u][0].call(l.exports,function(n){var e=t[u][1][n];return o(e?e:n)},l,l.exports,n,t,e,r)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<r.length;u++)o(r[u]);return o}({1:[function(n,t,e){"use strict";function r(){}function o(n){try{return n.then}catch(t){return d=t,w}}function i(n,t){try{return n(t)}catch(e){return d=e,w}}function u(n,t,e){try{n(t,e)}catch(r){return d=r,w}}function f(n){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof n)throw new TypeError("not a function");this._37=0,this._12=null,this._59=[],n!==r&&v(n,this)}function c(n,t,e){return new n.constructor(function(o,i){var u=new f(r);u.then(o,i),s(n,new p(t,e,u))})}function s(n,t){for(;3===n._37;)n=n._12;return 0===n._37?void n._59.push(t):void y(function(){var e=1===n._37?t.onFulfilled:t.onRejected;if(null===e)return void(1===n._37?l(t.promise,n._12):a(t.promise,n._12));var r=i(e,n._12);r===w?a(t.promise,d):l(t.promise,r)})}function l(n,t){if(t===n)return a(n,new TypeError("A promise cannot be resolved with itself."));if(t&&("object"==typeof t||"function"==typeof t)){var e=o(t);if(e===w)return a(n,d);if(e===n.then&&t instanceof f)return n._37=3,n._12=t,void h(n);if("function"==typeof e)return void v(e.bind(t),n)}n._37=1,n._12=t,h(n)}function a(n,t){n._37=2,n._12=t,h(n)}function h(n){for(var t=0;t<n._59.length;t++)s(n,n._59[t]);n._59=null}function p(n,t,e){this.onFulfilled="function"==typeof n?n:null,this.onRejected="function"==typeof t?t:null,this.promise=e}function v(n,t){var e=!1,r=u(n,function(n){e||(e=!0,l(t,n))},function(n){e||(e=!0,a(t,n))});e||r!==w||(e=!0,a(t,d))}var y=n("asap/raw"),d=null,w={};t.exports=f,f._99=r,f.prototype.then=function(n,t){if(this.constructor!==f)return c(this,n,t);var e=new f(r);return s(this,new p(n,t,e)),e}},{"asap/raw":4}],2:[function(n,t,e){"use strict";function r(n){var t=new o(o._99);return t._37=1,t._12=n,t}var o=n("./core.js");t.exports=o;var i=r(!0),u=r(!1),f=r(null),c=r(void 0),s=r(0),l=r("");o.resolve=function(n){if(n instanceof o)return n;if(null===n)return f;if(void 0===n)return c;if(n===!0)return i;if(n===!1)return u;if(0===n)return s;if(""===n)return l;if("object"==typeof n||"function"==typeof n)try{var t=n.then;if("function"==typeof t)return new o(t.bind(n))}catch(e){return new o(function(n,t){t(e)})}return r(n)},o.all=function(n){var t=Array.prototype.slice.call(n);return new o(function(n,e){function r(u,f){if(f&&("object"==typeof f||"function"==typeof f)){if(f instanceof o&&f.then===o.prototype.then){for(;3===f._37;)f=f._12;return 1===f._37?r(u,f._12):(2===f._37&&e(f._12),void f.then(function(n){r(u,n)},e))}var c=f.then;if("function"==typeof c){var s=new o(c.bind(f));return void s.then(function(n){r(u,n)},e)}}t[u]=f,0===--i&&n(t)}if(0===t.length)return n([]);for(var i=t.length,u=0;u<t.length;u++)r(u,t[u])})},o.reject=function(n){return new o(function(t,e){e(n)})},o.race=function(n){return new o(function(t,e){n.forEach(function(n){o.resolve(n).then(t,e)})})},o.prototype["catch"]=function(n){return this.then(null,n)}},{"./core.js":1}],3:[function(n,t,e){"use strict";function r(){if(c.length)throw c.shift()}function o(n){var t;t=f.length?f.pop():new i,t.task=n,u(t)}function i(){this.task=null}var u=n("./raw"),f=[],c=[],s=u.makeRequestCallFromTimer(r);t.exports=o,i.prototype.call=function(){try{this.task.call()}catch(n){o.onerror?o.onerror(n):(c.push(n),s())}finally{this.task=null,f[f.length]=this}}},{"./raw":4}],4:[function(n,t,e){(function(n){"use strict";function e(n){f.length||(u(),c=!0),f[f.length]=n}function r(){for(;s<f.length;){var n=s;if(s+=1,f[n].call(),s>l){for(var t=0,e=f.length-s;e>t;t++)f[t]=f[t+s];f.length-=s,s=0}}f.length=0,s=0,c=!1}function o(n){var t=1,e=new a(n),r=document.createTextNode("");return e.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}function i(n){return function(){function t(){clearTimeout(e),clearInterval(r),n()}var e=setTimeout(t,0),r=setInterval(t,50)}}t.exports=e;var u,f=[],c=!1,s=0,l=1024,a=n.MutationObserver||n.WebKitMutationObserver;u="function"==typeof a?o(r):i(r),e.requestFlush=u,e.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],5:[function(n,t,e){"function"!=typeof Promise.prototype.done&&(Promise.prototype.done=function(n,t){var e=arguments.length?this.then.apply(this,arguments):this;e.then(null,function(n){setTimeout(function(){throw n},0)})})},{}],6:[function(n,t,e){n("asap"),"undefined"==typeof Promise&&(Promise=n("./lib/core.js"),n("./lib/es6-extensions.js")),n("./polyfill-done.js")},{"./lib/core.js":1,"./lib/es6-extensions.js":2,"./polyfill-done.js":5,asap:3}]},{},[6]),function(global,undefined){"use strict";function addFromSetImmediateArguments(args){return tasksByHandle[nextHandle]=partiallyApplied.apply(undefined,args),nextHandle++}function partiallyApplied(handler){var args=[].slice.call(arguments,1);return function(){"function"==typeof handler?handler.apply(undefined,args):new Function(""+handler)()}}function runIfPresent(handle){if(currentlyRunningATask)setTimeout(partiallyApplied(runIfPresent,handle),0);else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=!0;try{task()}finally{clearImmediate(handle),currentlyRunningATask=!1}}}}function clearImmediate(handle){delete tasksByHandle[handle]}function installNextTickImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return process.nextTick(partiallyApplied(runIfPresent,handle)),handle}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=!0,oldOnMessage=global.onmessage;return global.onmessage=function(){postMessageIsAsynchronous=!1},global.postMessage("","*"),global.onmessage=oldOnMessage,postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix="setImmediate$"+Math.random()+"$",onGlobalMessage=function(event){event.source===global&&"string"==typeof event.data&&0===event.data.indexOf(messagePrefix)&&runIfPresent(+event.data.slice(messagePrefix.length))};global.addEventListener?global.addEventListener("message",onGlobalMessage,!1):global.attachEvent("onmessage",onGlobalMessage),setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return global.postMessage(messagePrefix+handle,"*"),handle}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)},setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return channel.port2.postMessage(handle),handle}}function installReadyStateChangeImplementation(){var html=doc.documentElement;setImmediate=function(){var handle=addFromSetImmediateArguments(arguments),script=doc.createElement("script");return script.onreadystatechange=function(){runIfPresent(handle),script.onreadystatechange=null,html.removeChild(script),script=null},html.appendChild(script),handle}}function installSetTimeoutImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return setTimeout(partiallyApplied(runIfPresent,handle),0),handle}}if(!global.setImmediate){var setImmediate,nextHandle=1,tasksByHandle={},currentlyRunningATask=!1,doc=global.document,attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global);attachTo=attachTo&&attachTo.setTimeout?attachTo:global,"[object process]"==={}.toString.call(global.process)?installNextTickImplementation():canUsePostMessage()?installPostMessageImplementation():global.MessageChannel?installMessageChannelImplementation():doc&&"onreadystatechange"in doc.createElement("script")?installReadyStateChangeImplementation():installSetTimeoutImplementation(),attachTo.setImmediate=setImmediate,attachTo.clearImmediate=clearImmediate}}(function(){return this}()),function(){function Viewport(){return this.PRE_IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.DEFAULT_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.ensureViewportElement(),this.platform={},this.platform.name=this.getPlatformName(),this.platform.version=this.getPlatformVersion(),this}Viewport.prototype.ensureViewportElement=function(){this.viewportElement=document.querySelector("meta[name=viewport]"),this.viewportElement||(this.viewportElement=document.createElement("meta"),this.viewportElement.name="viewport",document.head.appendChild(this.viewportElement))},Viewport.prototype.setup=function(){function isWebView(){return!!(window.cordova||window.phonegap||window.PhoneGap)}this.viewportElement&&"true"!=this.viewportElement.getAttribute("data-no-adjust")&&("ios"==this.platform.name?this.platform.version>=7&&isWebView()?this.viewportElement.setAttribute("content",this.IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.PRE_IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.DEFAULT_VIEWPORT))},Viewport.prototype.getPlatformName=function(){return navigator.userAgent.match(/Android/i)?"android":navigator.userAgent.match(/iPhone|iPad|iPod/i)?"ios":void 0},Viewport.prototype.getPlatformVersion=function(){var start=window.navigator.userAgent.indexOf("OS ");return window.Number(window.navigator.userAgent.substr(start+3,3).replace("_","."))},window.Viewport=Viewport}(),window.animit=function(){"use strict";var TIMEOUT_RATIO=1.4,Animit=function(element){if(!(this instanceof Animit))return new Animit(element);if(element instanceof HTMLElement)this.elements=[element];else{if("[object Array]"!==Object.prototype.toString.call(element))throw new Error("First argument must be an array or an instance of HTMLElement.");this.elements=element}this.transitionQueue=[],this.lastStyleAttributeDict=[]};Animit.prototype={transitionQueue:void 0,elements:void 0,play:function(callback){return"function"==typeof callback&&this.transitionQueue.push(function(done){callback(),done()}),this.startAnimation(),this},queue:function(transition,options){var queue=this.transitionQueue;if(transition&&options&&(options.css=transition,transition=new Animit.Transition(options)),transition instanceof Function||transition instanceof Animit.Transition||(transition=transition.css?new Animit.Transition(transition):new Animit.Transition({css:transition})),transition instanceof Function)queue.push(transition);else{if(!(transition instanceof Animit.Transition))throw new Error("Invalid arguments");queue.push(transition.build())}return this},wait:function(seconds){return seconds>0&&this.transitionQueue.push(function(done){setTimeout(done,1e3*seconds)}),this},saveStyle:function(){return this.transitionQueue.push(function(done){this.elements.forEach(function(element,index){for(var css=this.lastStyleAttributeDict[index]={},i=0;i<element.style.length;i++)css[element.style[i]]=element.style[element.style[i]]}.bind(this)),done()}.bind(this)),this},restoreStyle:function(options){function reset(){self.elements.forEach(function(element,index){element.style[transitionName]="none";var css=self.lastStyleAttributeDict[index];if(!css)throw new Error("restoreStyle(): The style is not saved. Invoke saveStyle() before.");self.lastStyleAttributeDict[index]=void 0;for(var i=0,name="";i<element.style.length;i++)name=element.style[i],"undefined"==typeof css[element.style[i]]&&(css[element.style[i]]="");Object.keys(css).forEach(function(key){element.style[key]=css[key]})})}options=options||{};var self=this;if(options.transition&&!options.duration)throw new Error('"options.duration" is required when "options.transition" is enabled.');var transitionName=util.transitionPropertyName;if(options.transition||options.duration&&options.duration>0){var transitionValue=options.transition||"all "+options.duration+"s "+(options.timing||"linear");this.transitionQueue.push(function(done){var elements=this.elements,removeListeners=util.onceOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),clearTransition(),done()}),timeoutId=setTimeout(function(){removeListeners(),clearTransition(),done()},1e3*options.duration*TIMEOUT_RATIO);elements.forEach(function(element,index){var css=self.lastStyleAttributeDict[index];if(!css)throw new Error("restoreStyle(): The style is not saved. Invoke saveStyle() before.");self.lastStyleAttributeDict[index]=void 0;for(var name,i=0,len=element.style.length;len>i;i++)name=element.style[i],void 0===css[name]&&(css[name]="");element.style[transitionName]=transitionValue,Object.keys(css).forEach(function(key){key!==transitionName&&(element.style[key]=css[key])}),element.style[transitionName]=transitionValue});var clearTransition=function(){elements.forEach(function(element){element.style[transitionName]=""})}})}else this.transitionQueue.push(function(done){reset(),done()});return this},startAnimation:function(){return this._dequeueTransition(),this},_dequeueTransition:function(){var transition=this.transitionQueue.shift();if(this._currentTransition)throw new Error("Current transition exists.");this._currentTransition=transition;var self=this,called=!1,done=function(){if(called)throw new Error("Invalid state: This callback is called twice.");called=!0,self._currentTransition=void 0,self._dequeueTransition()};transition&&transition.call(this,done)}},Animit.runAll=function(){for(var i=0;i<arguments.length;i++)arguments[i].play()},Animit.Transition=function(options){this.options=options||{},this.options.duration=this.options.duration||0,this.options.timing=this.options.timing||"linear",this.options.css=this.options.css||{},this.options.property=this.options.property||"all"},Animit.Transition.prototype={build:function(){function createActualCssProps(css){var result={};return Object.keys(css).forEach(function(name){var value=css[name];if(util.hasCssProperty(name))return void(result[name]=value);var prefixed=util.vendorPrefix+util.capitalize(name);util.hasCssProperty(prefixed)?result[prefixed]=value:(result[prefixed]=value,result[name]=value)}),result}if(0===Object.keys(this.options.css).length)throw new Error("options.css is required.");var css=createActualCssProps(this.options.css);if(this.options.duration>0){var transitionValue=util.buildTransitionValue(this.options),self=this;return function(callback){var elements=this.elements,timeout=1e3*self.options.duration*TIMEOUT_RATIO,removeListeners=util.onceOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),callback()}),timeoutId=setTimeout(function(){removeListeners(),callback()},timeout);elements.forEach(function(element){element.style[util.transitionPropertyName]=transitionValue,Object.keys(css).forEach(function(name){element.style[name]=css[name]})})}}return this.options.duration<=0?function(callback){var elements=this.elements;elements.forEach(function(element){element.style[util.transitionPropertyName]="",Object.keys(css).forEach(function(name){element.style[name]=css[name]})}),elements.length>0?util.forceLayoutAtOnce(elements,function(){util.batchAnimationFrame(callback)}):util.batchAnimationFrame(callback)}:void 0}};var util={};return util.capitalize=function(str){return str.charAt(0).toUpperCase()+str.slice(1)},util.buildTransitionValue=function(params){params.property=params.property||"all",params.duration=params.duration||.4,params.timing=params.timing||"linear";var props=params.property.split(/ +/);return props.map(function(prop){return prop+" "+params.duration+"s "+params.timing}).join(", ")},util.onceOnTransitionEnd=function(element,callback){if(!element)return function(){};var fn=function(event){element==event.target&&(event.stopPropagation(),removeListeners(),callback())},removeListeners=function(){util._transitionEndEvents.forEach(function(eventName){element.removeEventListener(eventName,fn,!1)})};return util._transitionEndEvents.forEach(function(eventName){element.addEventListener(eventName,fn,!1)}),removeListeners},util._transitionEndEvents=function(){return"ontransitionend"in window?["transitionend"]:"onwebkittransitionend"in window?["webkitTransitionEnd"]:"webkit"===util.vendorPrefix||"o"===util.vendorPrefix||"moz"===util.vendorPrefix||"ms"===util.vendorPrefix?[util.vendorPrefix+"TransitionEnd","transitionend"]:[]}(),util._cssPropertyDict=function(){var styles=window.getComputedStyle(document.documentElement,""),dict={},a="A".charCodeAt(0),z="z".charCodeAt(0);for(var key in styles)a<=key.charCodeAt(0)&&z>=key.charCodeAt(0)&&"cssText"!==key&&"parentText"!==key&&"length"!==key&&(dict[key]=!0);return dict}(),util.hasCssProperty=function(name){return name in util._cssPropertyDict},util.vendorPrefix=function(){var styles=window.getComputedStyle(document.documentElement,""),pre=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return pre}(),util.forceLayoutAtOnce=function(elements,callback){this.batchImmediate(function(){elements.forEach(function(element){ element.offsetHeight}),callback()})},util.batchImmediate=function(){var callbacks=[];return function(callback){0===callbacks.length&&setImmediate(function(){var concreateCallbacks=callbacks.slice(0);callbacks=[],concreateCallbacks.forEach(function(callback){callback()})}),callbacks.push(callback)}}(),util.batchAnimationFrame=function(){var callbacks=[],raf=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){setTimeout(callback,1e3/60)};return function(callback){0===callbacks.length&&raf(function(){var concreateCallbacks=callbacks.slice(0);callbacks=[],concreateCallbacks.forEach(function(callback){callback()})}),callbacks.push(callback)}}(),util.transitionPropertyName=function(){if(util.hasCssProperty("transition"))return"transition";if(util.hasCssProperty(util.vendorPrefix+"Transition"))return util.vendorPrefix+"Transition";throw new Error("Invalid state")}(),Animit}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();window.DoorLock=function(){"use strict";var generateId=function(){var i=0;return function(){return i++}}(),DoorLock=function(){function DoorLock(options){_classCallCheck(this,DoorLock),options=options||{},this._lockList=[],this._waitList=[],this._log=options.log||function(){}}return _createClass(DoorLock,[{key:"lock",value:function(){var _this=this,unlock=function unlock(){_this._unlock(unlock)};return unlock.id=generateId(),this._lockList.push(unlock),this._log("lock: "+unlock.id),unlock}},{key:"_unlock",value:function(fn){var index=this._lockList.indexOf(fn);if(-1===index)throw new Error("This function is not registered in the lock list.");this._lockList.splice(index,1),this._log("unlock: "+fn.id),this._tryToFreeWaitList()}},{key:"_tryToFreeWaitList",value:function(){for(;!this.isLocked()&&this._waitList.length>0;)this._waitList.shift()()}},{key:"waitUnlock",value:function(callback){if(!(callback instanceof Function))throw new Error("The callback param must be a function.");this.isLocked()?this._waitList.push(callback):callback()}},{key:"isLocked",value:function(){return this._lockList.length>0}}]),DoorLock}();return DoorLock}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util={_ready:!1,_domContentLoaded:!1,_onDOMContentLoaded:function(){util._domContentLoaded=!0,ons.isWebView()?window.document.addEventListener("deviceready",function(){util._ready=!0},!1):util._ready=!0},addBackButtonListener:function(fn){if(!this._domContentLoaded)throw new Error("This method is available after DOMContentLoaded");this._ready?window.document.addEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.addEventListener("backbutton",fn,!1)})},removeBackButtonListener:function(fn){if(!this._domContentLoaded)throw new Error("This method is available after DOMContentLoaded");this._ready?window.document.removeEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.removeEventListener("backbutton",fn,!1)})}};window.addEventListener("DOMContentLoaded",function(){return util._onDOMContentLoaded()},!1);var HandlerRepository={_store:{},_genId:function(){var i=0;return function(){return i++}}(),set:function(element,handler){element.dataset.deviceBackButtonHandlerId&&this.remove(element);var id=element.dataset.deviceBackButtonHandlerId=HandlerRepository._genId();this._store[id]=handler},remove:function(element){element.dataset.deviceBackButtonHandlerId&&(delete this._store[element.dataset.deviceBackButtonHandlerId],delete element.dataset.deviceBackButtonHandlerId)},get:function(element){if(element.dataset.deviceBackButtonHandlerId){var id=element.dataset.deviceBackButtonHandlerId;if(!this._store[id])throw new Error;return this._store[id]}},has:function(element){var id=element.dataset.deviceBackButtonHandlerId;return!!this._store[id]}},DeviceBackButtonDispatcher=function(){function DeviceBackButtonDispatcher(){_classCallCheck(this,DeviceBackButtonDispatcher),this._isEnabled=!1,this._boundCallback=this._callback.bind(this)}return _createClass(DeviceBackButtonDispatcher,[{key:"enable",value:function(){this._isEnabled||(util.addBackButtonListener(this._boundCallback),this._isEnabled=!0)}},{key:"disable",value:function(){this._isEnabled&&(util.removeBackButtonListener(this._boundCallback),this._isEnabled=!1)}},{key:"fireDeviceBackButtonEvent",value:function(){var event=document.createEvent("Event");event.initEvent("backbutton",!0,!0),document.dispatchEvent(event)}},{key:"_callback",value:function(){this._dispatchDeviceBackButtonEvent()}},{key:"createHandler",value:function(element,callback){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");if(!(callback instanceof Function))throw new Error("callback must be an instance of Function");var handler={_callback:callback,_element:element,disable:function(){HandlerRepository.remove(element)},setListener:function(callback){this._callback=callback},enable:function(){HandlerRepository.set(element,this)},isEnabled:function(){return HandlerRepository.get(element)===this},destroy:function(){HandlerRepository.remove(element),this._callback=this._element=null}};return handler.enable(),handler}},{key:"_dispatchDeviceBackButtonEvent",value:function(){function createEvent(element){return{_element:element,callParentHandler:function(){for(var parent=this._element.parentNode;parent;){if(handler=HandlerRepository.get(parent))return handler._callback(createEvent(parent));parent=parent.parentNode}}}}var tree=this._captureTree(),element=this._findHandlerLeafElement(tree),handler=HandlerRepository.get(element);handler._callback(createEvent(element))}},{key:"_captureTree",value:function(){function createTree(element){return{element:element,children:Array.prototype.concat.apply([],arrayOf(element.children).map(function(childElement){if("none"===childElement.style.display)return[];if(0===childElement.children.length&&!HandlerRepository.has(childElement))return[];var result=createTree(childElement);return 0!==result.children.length||HandlerRepository.has(result.element)?[result]:[]}))}}function arrayOf(target){for(var result=[],i=0;i<target.length;i++)result.push(target[i]);return result}return createTree(document.body)}},{key:"_findHandlerLeafElement",value:function(tree){function find(_x){for(var _again=!0;_again;){var node=_x;if(_again=!1,0===node.children.length)return node.element;if(1!==node.children.length)return node.children.map(function(childNode){return childNode.element}).reduce(function(left,right){if(!left)return right;var leftZ=parseInt(window.getComputedStyle(left,"").zIndex,10),rightZ=parseInt(window.getComputedStyle(right,"").zIndex,10);if(!isNaN(leftZ)&&!isNaN(rightZ))return leftZ>rightZ?left:right;throw new Error("Capturing backbutton-handler is failure.")},null);_x=node.children[0],_again=!0}}return find(tree)}}]),DeviceBackButtonDispatcher}();ons._deviceBackButtonDispatcher=new DeviceBackButtonDispatcher,window.addEventListener("DOMContentLoaded",function(){ons._deviceBackButtonDispatcher.enable()})}(window.ons=window.ons||{}),function(ons){"use strict";function waitDeviceReady(){var unlockDeviceReady=ons._readyLock.lock();window.addEventListener("DOMContentLoaded",function(){ons.isWebView()?window.document.addEventListener("deviceready",unlockDeviceReady,!1):unlockDeviceReady()},!1)}ons._readyLock=new DoorLock,ons._config={autoStatusBarFill:!0,animationsDisabled:!1},waitDeviceReady(),ons.isReady=function(){return!ons._readyLock.isLocked()},ons.isWebView=function(){if("loading"===document.readyState||"uninitialized"==document.readyState)throw new Error("isWebView() method is available after dom contents loaded.");return!!(window.cordova||window.phonegap||window.PhoneGap)},ons.ready=function(callback){ons.isReady()?callback():ons._readyLock.waitUnlock(callback)},ons.setDefaultDeviceBackButtonListener=function(listener){ons._defaultDeviceBackButtonHandler.setListener(listener)},ons.disableDeviceBackButtonHandler=function(){ons._deviceBackButtonDispatcher.disable()},ons.enableDeviceBackButtonHandler=function(){ons._deviceBackButtonDispatcher.enable()},ons.enableAutoStatusBarFill=function(){if(ons.isReady())throw new Error("This method must be called before ons.isReady() is true.");ons._config.autoStatusBarFill=!0},ons.disableAutoStatusBarFill=function(){if(ons.isReady())throw new Error("This method must be called before ons.isReady() is true.");ons._config.autoStatusBarFill=!1},ons.disableAnimations=function(){ons._config.animationsDisabled=!0},ons.enableAnimations=function(){ons._config.animationsDisabled=!1},ons._createPopoverOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-popover/gi)?"<div>"+html+"</div>":"<ons-popover>"+html+"</ons-popover>";var div=ons._util.createElement("<div>"+html+"</div>"),popover=div.querySelector("ons-popover");return CustomElements.upgrade(popover),document.body.appendChild(popover),options.link instanceof Function&&options.link(popover),popover})},ons.createPopover=ons._createPopoverOriginal,ons._createDialogOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-dialog/gi)?"<div>"+html+"</div>":"<ons-dialog>"+html+"</ons-dialog>";var div=ons._util.createElement("<div>"+html+"</div>"),dialog=div.querySelector("ons-dialog");return CustomElements.upgrade(dialog),document.body.appendChild(dialog),options.link instanceof Function&&options.link(dialog),dialog})},ons.createDialog=ons._createDialogOriginal,ons._createAlertDialogOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-alert-dialog/gi)?"<div>"+html+"</div>":"<ons-alert-dialog>"+html+"</ons-alert-dialog>";var div=ons._util.createElement("<div>"+html+"</div>"),alertDialog=div.querySelector("ons-alert-dialog");return CustomElements.upgrade(alertDialog),document.body.appendChild(alertDialog),options.link instanceof Function&&options.link(alertDialog),alertDialog})},ons.createAlertDialog=ons._createAlertDialogOriginal,ons._resolveLoadingPlaceholderOriginal=function(page,link){var elements=ons._util.arrayFrom(window.document.querySelectorAll("[ons-loading-placeholder]"));if(!(elements.length>0))throw new Error("No ons-loading-placeholder exists.");elements.filter(function(element){return!element.getAttribute("page")}).forEach(function(element){element.setAttribute("ons-loading-placeholder",page),ons._resolveLoadingPlaceholder(element,page,link)})},ons.resolveLoadingPlaceholder=ons._resolveLoadingPlaceholderOriginal,ons._setupLoadingPlaceHolders=function(){ons.ready(function(){var elements=ons._util.arrayFrom(window.document.querySelectorAll("[ons-loading-placeholder]"));elements.forEach(function(element){var page=element.getAttribute("ons-loading-placeholder");"string"==typeof page&&ons._resolveLoadingPlaceholder(element,page)})})},ons._resolveLoadingPlaceholder=function(element,page,link){link=link||function(element,done){done()},ons._internal.getPageHTMLAsync(page).then(function(html){for(;element.firstChild;)element.removeChild(element.firstChild);var contentElement=ons._util.createElement("<div>"+html+"</div>");contentElement.style.display="none",element.appendChild(contentElement),link(contentElement,function(){contentElement.style.display=""})})["catch"](function(error){throw new Error("Unabled to resolve placeholder: "+error)})}}(window.ons=window.ons||{}),function(ons){"use strict";var util=ons._util=ons._util||{};util.prepareQuery=function(query){return query instanceof Function?query:"."===query.substr(0,1)?function(node){return node.classList.contains(query.substr(1))}:function(node){return node.nodeName.toLowerCase()===query}},util.findChild=function(element,query){for(var match=util.prepareQuery(query),i=0;i<element.children.length;i++){var node=element.children[i];if(match(node))return node}return null},util.findChildRecursively=function(element,query){for(var match=util.prepareQuery(query),i=0;i<element.children.length;i++){var node=element.children[i];if(match(node))return node;var nodeMatch=util.findChildRecursively(node,match);if(nodeMatch)return nodeMatch}return null},util.findParent=function(element,query){for(var match="."===query.substr(0,1)?function(node){return node.classList.contains(query.substr(1))}:function(node){return node.nodeName.toLowerCase()===query},parent=element.parentNode;;){if(!parent)return null;if(match(parent))return parent;parent=parent.parentNode}},util.isAttached=function(element){for(;document.documentElement!==element;){if(!element)return!1;element=element.parentNode}return!0},util.hasAnyComponentAsParent=function(element){for(;element&&document.documentElement!==element;)if(element=element.parentNode,element&&element.nodeName.toLowerCase().match(/(ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/))return!0;return!1},util.propagateAction=function(element,action){for(var i=0;i<element.childNodes.length;i++){var child=element.childNodes[i];child[action]?child[action]():ons._util.propagateAction(child,action)}},util.createElement=function(html){var wrapper=document.createElement("div");if(wrapper.innerHTML=html,wrapper.children.length>1)throw new Error('"html" must be one wrapper element.');return wrapper.children[0]},util.createFragment=function(html){var wrapper=document.createElement("div");wrapper.innerHTML=html;var fragment=document.createDocumentFragment();return wrapper.firstChild&&fragment.appendChild(wrapper.firstChild),fragment},util.extend=function(dst){for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_len>_key;_key++)args[_key-1]=arguments[_key];for(var i=0;i<args.length;i++)if(args[i])for(var keys=Object.keys(args[i]),j=0;j<keys.length;j++){var key=keys[j];dst[key]=args[i][key]}return dst},util.arrayFrom=function(arrayLike){for(var result=[],i=0;i<arrayLike.length;i++)result.push(arrayLike[i]);return result},util.parseJSONObjectSafely=function(jsonString){var failSafe=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];try{var result=JSON.parse(""+jsonString);if("object"==typeof result&&null!==result)return result}catch(e){return failSafe}return failSafe},util.triggerElementEvent=function(target,eventName){var detail=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],event=new CustomEvent(eventName,{bubbles:!0,cancelable:!0,detail:detail});return Object.keys(detail).forEach(function(key){event[key]=detail[key]}),target.dispatchEvent(event),event},util.hasModifier=function(target,modifierName){if(!target.hasAttribute("modifier"))return!1;for(var modifiers=target.getAttribute("modifier").trim().split(/\s+/),i=0;i<modifiers.length;i++)if(modifiers[i]===modifierName)return!0;return!1}}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var ModalAnimator=function(){function ModalAnimator(options){_classCallCheck(this,ModalAnimator),this.delay=0,this.duration=.2,options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration,this.delay=void 0!==options.delay?options.delay:this.delay}return _createClass(ModalAnimator,[{key:"show",value:function(modal,callback){callback()}},{key:"hide",value:function(modal,callback){callback()}}]),ModalAnimator}();ons._internal=ons._internal||{},ons._internal.ModalAnimator=ModalAnimator}(window.ons=window.ons||{});var _get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var SplitterAnimator=(ons._util,function(){function SplitterAnimator(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];_classCallCheck(this,SplitterAnimator),options=ons._util.extend({timing:"linear",duration:"0.3",delay:"0"},options||{}),this._timing=options.timing,this._duration=options.duration,this._delay=options.delay}return _createClass(SplitterAnimator,[{key:"layoutOnOpen",value:function(){}},{key:"layoutOnClose",value:function(){}},{key:"translate",value:function(distance){}},{key:"open",value:function(done){done()}},{key:"close",value:function(done){done()}},{key:"activate",value:function(contentElement,sideElement,maskElement){}},{key:"inactivate",value:function(){}},{key:"isActivated",value:function(){throw new Error}}]),SplitterAnimator}()),OverlaySplitterAnimator=function(_SplitterAnimator){function OverlaySplitterAnimator(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];_classCallCheck(this,OverlaySplitterAnimator),options=ons._util.extend({timing:"cubic-bezier(.1, .7, .1, 1)",duration:"0.3",delay:"0"},options||{}),_get(Object.getPrototypeOf(OverlaySplitterAnimator.prototype),"constructor",this).call(this,options)}return _inherits(OverlaySplitterAnimator,_SplitterAnimator),_createClass(OverlaySplitterAnimator,[{key:"isActivated",value:function(){return this._isActivated}},{key:"layoutOnClose",value:function(){animit(this._side).queue({transform:"translateX(0%)",width:this._side._getWidth()}).play(),this._mask.style.display="none"}},{key:"layoutOnOpen",value:function(){animit(this._side).queue({transform:"translate3d("+(this._side._isLeftSide()?"":"-")+"100%, 0px, 0px)",width:this._side._getWidth()}).play(),this._mask.style.display="block"}},{key:"activate",value:function(contentElement,sideElement,maskElement){this._isActivated=!0,this._content=contentElement,this._side=sideElement,this._mask=maskElement,this._setupLayout()}},{key:"inactivate",value:function(){this._isActivated=!1,this._clearLayout(),this._content=this._side=this._mask=null}},{key:"translate",value:function(distance){animit(this._side).queue({transform:"translate3d("+(this._side._isLeftSide()?"":"-")+distance+"px, 0px, 0px)"}).play()}},{key:"_clearLayout",value:function(){var side=this._side,mask=this._mask;side.style.zIndex="",side.style.right="",side.style.left="",side.style.transform=side.style.webkitTransform="",side.style.transition=side.style.webkitTransition="",side.style.width="",side.style.display="",mask.style.display="none"}},{key:"_setupLayout",value:function(){var side=this._side;side.style.zIndex=3,side.style.display="block",side._isLeftSide()?(side.style.left="auto",side.style.right="100%"):(side.style.left="100%",side.style.right="auto")}},{key:"open",value:function(done){var transform=this._side._isLeftSide()?"translate3d(100%, 0px, 0px)":"translate3d(-100%, 0px, 0px)";animit.runAll(animit(this._side).wait(this._delay).queue({transform:transform},{duration:this._duration,timing:this._timing}).queue(function(callback){callback(),done()}),animit(this._mask).wait(this._delay).queue({display:"block"}).queue({opacity:"1"},{duration:this._duration,timing:"linear"}))}},{key:"close",value:function(done){var _this=this;animit.runAll(animit(this._side).wait(this._delay).queue({transform:"translate3d(0px, 0px, 0px)"},{duration:this._duration,timing:this._timing}).queue(function(callback){_this._side.style.webkitTransition="",done(),callback()}),animit(this._mask).wait(this._delay).queue({opacity:"0"},{duration:this._duration,timing:"linear"}).queue({display:"none"}))}}]),OverlaySplitterAnimator}(SplitterAnimator);ons._internal=ons._internal||{},ons._internal.SplitterAnimator=SplitterAnimator,ons._internal.OverlaySplitterAnimator=OverlaySplitterAnimator}(window.ons=window.ons||{});var _get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var NavigatorTransitionAnimator=function(){function NavigatorTransitionAnimator(options){_classCallCheck(this,NavigatorTransitionAnimator),options=ons._util.extend({timing:"linear",duration:"0.4",delay:"0"},options||{}),this.timing=options.timing,this.duration=options.duration,this.delay=options.delay}return _createClass(NavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){callback()}},{key:"pop",value:function(enterPage,leavePage,callback){callback()}}]),NavigatorTransitionAnimator}(),NoneNavigatorTransitionAnimator=function(_NavigatorTransitionAnimator){function NoneNavigatorTransitionAnimator(options){_classCallCheck(this,NoneNavigatorTransitionAnimator),_get(Object.getPrototypeOf(NoneNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options)}return _inherits(NoneNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(NoneNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){callback()}},{key:"pop",value:function(enterPage,leavePage,callback){callback()}}]),NoneNavigatorTransitionAnimator}(NavigatorTransitionAnimator);ons._internal=ons._internal||{},ons._internal.NavigatorTransitionAnimator=NavigatorTransitionAnimator,ons._internal.NoneNavigatorTransitionAnimator=NoneNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var PopoverAnimator=function(){function PopoverAnimator(options){_classCallCheck(this,PopoverAnimator),options=ons._util.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,delay:0},options||{}),this.timing=options.timing,this.duration=options.duration,this.delay=options.delay}return _createClass(PopoverAnimator,[{key:"show",value:function(popover,callback){callback()}},{key:"hide",value:function(popover,callback){callback()}}]),PopoverAnimator}();ons._internal=ons._internal||{},ons._internal.PopoverAnimator=PopoverAnimator}(window.ons=window.ons||{}),function(ons){"use strict";ons.platform={_renderPlatform:null,select:function(platform){ons.platform._renderPlatform=platform.trim().toLowerCase()},isWebView:function(){return ons.isWebView()},isIOS:function(){return ons.platform._renderPlatform?"ios"===ons.platform._renderPlatform:"object"==typeof device?/iOS/i.test(device.platform):/iPhone|iPad|iPod/i.test(navigator.userAgent)},isAndroid:function(){return ons.platform._renderPlatform?"android"===ons.platform._renderPlatform:"object"==typeof device?/Android/i.test(device.platform):/Android/i.test(navigator.userAgent)},isAndroidPhone:function(){return/Android/i.test(navigator.userAgent)&&/Mobile/i.test(navigator.userAgent)},isAndroidTablet:function(){return/Android/i.test(navigator.userAgent)&&!/Mobile/i.test(navigator.userAgent)},isWP:function(){return ons.platform._renderPlatform?"wp"===ons.platform._renderPlatform:"object"==typeof device?/Win32NT|WinCE/i.test(device.platform):/Windows Phone|IEMobile|WPDesktop/i.test(navigator.userAgent)},isIPhone:function(){return/iPhone/i.test(navigator.userAgent)},isIPad:function(){return/iPad/i.test(navigator.userAgent)},isIPod:function(){return/iPod/i.test(navigator.userAgent)},isBlackBerry:function(){return ons.platform._renderPlatform?"blackberry"===ons.platform._renderPlatform:"object"==typeof device?/BlackBerry/i.test(device.platform):/BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent)},isOpera:function(){return ons.platform._renderPlatform?"opera"===ons.platform._renderPlatform:!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isFirefox:function(){return ons.platform._renderPlatform?"firefox"===ons.platform._renderPlatform:"undefined"!=typeof InstallTrigger},isSafari:function(){return ons.platform._renderPlatform?"safari"===ons.platform._renderPlatform:Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},isChrome:function(){return ons.platform._renderPlatform?"chrome"===ons.platform._renderPlatform:!(!window.chrome||window.opera||navigator.userAgent.indexOf(" OPR/")>=0||navigator.userAgent.indexOf(" Edge/")>=0)},isIE:function(){return ons.platform._renderPlatform?"ie"===ons.platform._renderPlatform:!!document.documentMode},isEdge:function(){return ons.platform._renderPlatform?"edge"===ons.platform._renderPlatform:navigator.userAgent.indexOf(" Edge/")>=0},isIOS7above:function(){if("object"==typeof device)return/iOS/i.test(device.platform)&&parseInt(device.version.split(".")[0])>=7;if(/iPhone|iPad|iPod/i.test(navigator.userAgent)){var ver=(navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[""])[0].replace(/_/g,".");return parseInt(ver.split(".")[0])>=7}return!1},getMobileOS:function(){return this.isAndroid()?"android":this.isIOS()?"ios":this.isWP()?"wp":"other"},getIOSDevice:function(){return this.isIPhone()?"iphone":this.isIPad()?"ipad":this.isIPod()?"ipod":"na"}}}(window.ons=window.ons||{});var _get=function(_x4,_x5,_x6){for(var _again=!0;_again;){var object=_x4,property=_x5,receiver=_x6;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x4=parent,_x5=property,_x6=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var AlertDialogAnimator=function(){function AlertDialogAnimator(){var _ref=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref$timing=_ref.timing,timing=void 0===_ref$timing?"linear":_ref$timing,_ref$delay=_ref.delay,delay=void 0===_ref$delay?0:_ref$delay,_ref$duration=_ref.duration,duration=void 0===_ref$duration?.2:_ref$duration;_classCallCheck(this,AlertDialogAnimator),this.timing=timing,this.delay=delay,this.duration=duration}return _createClass(AlertDialogAnimator,[{key:"show",value:function(dialog,done){done()}},{key:"hide",value:function(dialog,done){done()}}]),AlertDialogAnimator}(),AndroidAlertDialogAnimator=function(_AlertDialogAnimator){function AndroidAlertDialogAnimator(){var _ref2=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref2$timing=_ref2.timing,timing=void 0===_ref2$timing?"cubic-bezier(.1, .7, .4, 1)":_ref2$timing,_ref2$duration=_ref2.duration,duration=void 0===_ref2$duration?.2:_ref2$duration,_ref2$delay=_ref2.delay,delay=void 0===_ref2$delay?0:_ref2$delay;_classCallCheck(this,AndroidAlertDialogAnimator),_get(Object.getPrototypeOf(AndroidAlertDialogAnimator.prototype),"constructor",this).call(this,{duration:duration,timing:timing,delay:delay})}return _inherits(AndroidAlertDialogAnimator,_AlertDialogAnimator),_createClass(AndroidAlertDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),AndroidAlertDialogAnimator}(AlertDialogAnimator),IOSAlertDialogAnimator=function(_AlertDialogAnimator2){function IOSAlertDialogAnimator(){var _ref3=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref3$timing=_ref3.timing,timing=void 0===_ref3$timing?"cubic-bezier(.1, .7, .4, 1)":_ref3$timing,_ref3$duration=_ref3.duration,duration=void 0===_ref3$duration?.2:_ref3$duration,_ref3$delay=_ref3.delay,delay=void 0===_ref3$delay?0:_ref3$delay; _classCallCheck(this,IOSAlertDialogAnimator),_get(Object.getPrototypeOf(IOSAlertDialogAnimator.prototype),"constructor",this).call(this,{duration:duration,timing:timing,delay:delay})}return _inherits(IOSAlertDialogAnimator,_AlertDialogAnimator2),_createClass(IOSAlertDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{opacity:1},duration:0}).wait(this.delay).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),IOSAlertDialogAnimator}(AlertDialogAnimator);ons._internal=ons._internal||{},ons._internal.AlertDialogAnimator=AlertDialogAnimator,ons._internal.AndroidAlertDialogAnimator=AndroidAlertDialogAnimator,ons._internal.IOSAlertDialogAnimator=IOSAlertDialogAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var AnimatorFactory=function(){function AnimatorFactory(opts){if(_classCallCheck(this,AnimatorFactory),this._animators=opts.animators,this._baseClass=opts.baseClass,this._baseClassName=opts.baseClassName||opts.baseClass.name,this._animation=opts.defaultAnimation||"default",this._animationOptions=opts.defaultAnimationOptions||{},!this._animators[this._animation])throw new Error("No such animation: "+this._animation)}return _createClass(AnimatorFactory,[{key:"setAnimationOptions",value:function(options){this._animationOptions=options}},{key:"newAnimator",value:function(options,defaultAnimator){options=options||{};var animator=null;if(options.animation instanceof this._baseClass)return options.animation;var Animator=null;if("string"==typeof options.animation&&(Animator=this._animators[options.animation]),!Animator&&defaultAnimator)animator=defaultAnimator;else{Animator=Animator||this._animators[this._animation];var animationOpts=ons._util.extend({},this._animationOptions,options.animationOptions||{},ons._config.animationsDisabled?{duration:0,delay:0}:{});animator=new Animator(animationOpts)}if(!(animator instanceof this._baseClass))throw new Error('"animator" is not an instance of '+this._baseClassName+".");return animator}}],[{key:"parseAnimationOptionsString",value:function(jsonString){try{if("string"==typeof jsonString){var result=JSON.parse(jsonString);if("object"==typeof result&&null!==result)return result;console.error('"animation-options" attribute must be a JSON object string: '+jsonString)}return{}}catch(e){return console.error('"animation-options" attribute must be a JSON object string: '+jsonString),{}}}}]),AnimatorFactory}();ons._internal=ons._internal||{},ons._internal.AnimatorFactory=AnimatorFactory}(window.ons=window.ons||{});var _get=function(_x5,_x6,_x7){for(var _again=!0;_again;){var object=_x5,property=_x6,receiver=_x7;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x5=parent,_x6=property,_x7=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var DialogAnimator=function(){function DialogAnimator(){var _ref=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref$timing=_ref.timing,timing=void 0===_ref$timing?"linear":_ref$timing,_ref$delay=_ref.delay,delay=void 0===_ref$delay?0:_ref$delay,_ref$duration=_ref.duration,duration=void 0===_ref$duration?.2:_ref$duration;_classCallCheck(this,DialogAnimator),this.timing=timing,this.delay=delay,this.duration=duration}return _createClass(DialogAnimator,[{key:"show",value:function(dialog,done){done()}},{key:"hide",value:function(dialog,done){done()}}]),DialogAnimator}(),AndroidDialogAnimator=function(_DialogAnimator){function AndroidDialogAnimator(){var _ref2=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref2$timing=_ref2.timing,timing=void 0===_ref2$timing?"ease-in-out":_ref2$timing,_ref2$delay=_ref2.delay,delay=void 0===_ref2$delay?0:_ref2$delay,_ref2$duration=_ref2.duration,duration=void 0===_ref2$duration?.3:_ref2$duration;_classCallCheck(this,AndroidDialogAnimator),_get(Object.getPrototypeOf(AndroidDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(AndroidDialogAnimator,_DialogAnimator),_createClass(AndroidDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),AndroidDialogAnimator}(DialogAnimator),IOSDialogAnimator=function(_DialogAnimator2){function IOSDialogAnimator(){var _ref3=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref3$timing=_ref3.timing,timing=void 0===_ref3$timing?"ease-in-out":_ref3$timing,_ref3$delay=_ref3.delay,delay=void 0===_ref3$delay?0:_ref3$delay,_ref3$duration=_ref3.duration,duration=void 0===_ref3$duration?.3:_ref3$duration;_classCallCheck(this,IOSDialogAnimator),_get(Object.getPrototypeOf(IOSDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(IOSDialogAnimator,_DialogAnimator2),_createClass(IOSDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),IOSDialogAnimator}(DialogAnimator),SlideDialogAnimator=function(_DialogAnimator3){function SlideDialogAnimator(){var _ref4=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref4$timing=_ref4.timing,timing=void 0===_ref4$timing?"cubic-bezier(.1, .7, .4, 1)":_ref4$timing,_ref4$delay=_ref4.delay,delay=void 0===_ref4$delay?0:_ref4$delay,_ref4$duration=_ref4.duration,duration=void 0===_ref4$duration?.2:_ref4$duration;_classCallCheck(this,SlideDialogAnimator),_get(Object.getPrototypeOf(SlideDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(SlideDialogAnimator,_DialogAnimator3),_createClass(SlideDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),SlideDialogAnimator}(DialogAnimator);ons._internal=ons._internal||{},ons._internal.DialogAnimator=DialogAnimator,ons._internal.AndroidDialogAnimator=AndroidDialogAnimator,ons._internal.IOSDialogAnimator=IOSDialogAnimator,ons._internal.SlideDialogAnimator=SlideDialogAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var ModalAnimator=ons._internal.ModalAnimator,FadeModalAnimator=function(_ModalAnimator){function FadeModalAnimator(options){_classCallCheck(this,FadeModalAnimator),options.timing=options.timing||"linear",options.duration=options.duration||"0.3",options.delay=options.delay||0,_get(Object.getPrototypeOf(FadeModalAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadeModalAnimator,_ModalAnimator),_createClass(FadeModalAnimator,[{key:"show",value:function(modal,callback){callback=callback?callback:function(){},animit(modal).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}).play()}},{key:"hide",value:function(modal,callback){callback=callback?callback:function(){},animit(modal).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}).play()}}]),FadeModalAnimator}(ModalAnimator);ons._internal=ons._internal||{},ons._internal.FadeModalAnimator=FadeModalAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,FadeNavigatorTransitionAnimator=function(_NavigatorTransitionAnimator){function FadeNavigatorTransitionAnimator(options){_classCallCheck(this,FadeNavigatorTransitionAnimator),options=ons._util.extend({timing:"linear",duration:"0.4",delay:"0"},options||{}),_get(Object.getPrototypeOf(FadeNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadeNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(FadeNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){animit.runAll(animit([enterPage.element._getContentElement(),enterPage.element._getBackgroundElement()]).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}),animit(enterPage.element._getToolbarElement()).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle())}},{key:"pop",value:function(enterPage,leavePage,callback){animit.runAll(animit([leavePage.element._getContentElement(),leavePage.element._getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}),animit(leavePage.element._getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}))}}]),FadeNavigatorTransitionAnimator}(NavigatorTransitionAnimator);ons._internal=ons._internal||{},ons._internal.FadeNavigatorTransitionAnimator=FadeNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var PopoverAnimator=ons._internal.PopoverAnimator,FadePopoverAnimator=function(_PopoverAnimator){function FadePopoverAnimator(options){_classCallCheck(this,FadePopoverAnimator),_get(Object.getPrototypeOf(FadePopoverAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadePopoverAnimator,_PopoverAnimator),_createClass(FadePopoverAnimator,[{key:"show",value:function(popover,callback){var pop=popover.querySelector(".popover"),mask=popover.querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(pop).saveStyle().queue({transform:"scale3d(1.3, 1.3, 1.0)",opacity:0}).wait(this.delay).queue({transform:"scale3d(1.0, 1.0, 1.0)",opacity:1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(popover,callback){var pop=popover.querySelector(".popover"),mask=popover.querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(pop).saveStyle().queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),FadePopoverAnimator}(PopoverAnimator);ons._internal=ons._internal||{},ons._internal.FadePopoverAnimator=FadePopoverAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,IOSSlideNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function IOSSlideNavigatorTransitionAnimator(options){_classCallCheck(this,IOSSlideNavigatorTransitionAnimator),options=ons._util.extend({duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(IOSSlideNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%;\n background-color: black; opacity: 0;"></div>\n ')}return _inherits(IOSSlideNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(IOSSlideNavigatorTransitionAnimator,[{key:"_decompose",value:function(page){CustomElements.upgrade(page.element);var toolbar=page.element._getToolbarElement();CustomElements.upgrade(toolbar);var left=toolbar._getToolbarLeftItemsElement(),right=toolbar._getToolbarRightItemsElement(),excludeBackButtonLabel=function(elements){for(var result=[],i=0;i<elements.length;i++)if("ons-back-button"===elements[i].nodeName.toLowerCase()){var iconElement=elements[i].querySelector(".ons-back-button__icon");iconElement&&result.push(iconElement)}else result.push(elements[i]);return result},other=[].concat(0===left.children.length?left:excludeBackButtonLabel(left.children)).concat(0===right.children.length?right:excludeBackButtonLabel(right.children)),pageLabels=[toolbar._getToolbarCenterItemsElement(),toolbar._getToolbarBackButtonLabelElement()];return{pageLabels:pageLabels,other:other,content:page.element._getContentElement(),background:page.element._getBackgroundElement(),toolbar:toolbar,bottomToolbar:page.element._getBottomToolbarElement()}}},{key:"_shouldAnimateToolbar",value:function(enterPage,leavePage){var bothPageHasToolbar=enterPage.element._canAnimateToolbar()&&leavePage.element._canAnimateToolbar(),noMaterialToolbar=!enterPage.element._getToolbarElement().classList.contains("navigation-bar--material")&&!leavePage.element._getToolbarElement().classList.contains("navigation-bar--material");return bothPageHasToolbar&&noMaterialToolbar}},{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentNode.insertBefore(this.backgroundMask,leavePage.element.nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element.getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(this.backgroundMask).saveStyle().queue({opacity:0,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:.1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this.backgroundMask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.toolbar).saveStyle().queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}).wait(this.delay+.3).restoreStyle({duration:.1,transition:"background-color 0.1s linear, border-color 0.1s linear"}),animit(enterPageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.other).saveStyle().queue({css:{opacity:0},duration:0}).wait(this.delay).queue({css:{opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",callback(),done()}),animit(leavePageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePageDecomposition.other).saveStyle().queue({css:{opacity:1},duration:0}).wait(this.delay).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).restoreStyle())):(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",callback(),done()})))}},{key:"pop",value:function(enterPage,leavePage,done){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element.nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element.getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(this.backgroundMask).saveStyle().queue({opacity:.1,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this2.backgroundMask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.toolbar).saveStyle().queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.other).saveStyle().queue({css:{opacity:0},duration:0}).wait(this.delay).queue({css:{opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(0).queue(function(finish){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",done(),finish()}),animit(leavePageDecomposition.other).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}),animit(leavePageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}))):(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).queue(function(finish){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",done(),finish()})))}}]),IOSSlideNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.IOSSlideNavigatorTransitionAnimator=IOSSlideNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util=ons._util,LazyRepeatDelegate=function(){function LazyRepeatDelegate(){_classCallCheck(this,LazyRepeatDelegate)}return _createClass(LazyRepeatDelegate,[{key:"prepareItem",value:function(index,done){throw new Error("This is an abstract method.")}},{key:"countItems",value:function(){throw new Error("This is an abstract method.")}},{key:"updateItem",value:function(index,item){throw new Error("This is an abstract method.")}},{key:"calculateItemHeight",value:function(index){throw new Error("This is an abstract method.")}},{key:"destroyItem",value:function(index,item){throw new Error("This is an abstract method.")}},{key:"destroy",value:function(){throw new Error("This is an abstract method.")}}]),LazyRepeatDelegate}(),LazyRepeatProvider=function(){function LazyRepeatProvider(wrapperElement,templateElement,delegate){if(_classCallCheck(this,LazyRepeatProvider),!(delegate instanceof LazyRepeatDelegate))throw new Error('"delegate" parameter must be an instance of ons._internal.LazyRepeatDelegate.');if(!(templateElement instanceof Element))throw new Error('"templateElement" parameter must be an instance of Element.');if(!(wrapperElement instanceof Element))throw new Error('"wrapperElement" parameter must be an instance of Element.');if(this._templateElement=templateElement,this._wrapperElement=wrapperElement,this._delegate=delegate,this._pageContent=util.findParent(wrapperElement,".page__content"),this._pageContent||(this._pageContent=util.findParent(wrapperElement,".ons-scroller__content")),!this._pageContent)throw new Error("ons-lazy-repeat must be a descendant of an <ons-page> or an <ons-scroller> element.");this._itemHeightSum=[],this._maxIndex=0,this._renderedItems={},this._addEventListeners(),this._onChange()}return _createClass(LazyRepeatProvider,[{key:"_countItems",value:function(){return this._delegate.countItems()}},{key:"_getItemHeight",value:function(i){return this._delegate.calculateItemHeight(i)}},{key:"_getTopOffset",value:function(){return"undefined"!=typeof this._wrapperElement&&null!==this._wrapperElement?this._wrapperElement.getBoundingClientRect().top:0}},{key:"_onChange",value:function(){this._render()}},{key:"_render",value:function(){for(var items=this._getItemsInView(),keep={},i=0,l=items.length;l>i;i++){var _item=items[i];this._renderElement(_item),keep[_item.index]=!0}for(var key in this._renderedItems)this._renderedItems.hasOwnProperty(key)&&!keep.hasOwnProperty(key)&&this._removeElement(key);this._wrapperElement.style.height=this._calculateListHeight()+"px"}},{key:"_calculateListHeight",value:function(){var indices=Object.keys(this._renderedItems).map(function(n){return parseInt(n)});return this._itemHeightSum[indices.pop()]||0; }},{key:"_isRendered",value:function(index){return this._renderedItems.hasOwnProperty(index)}},{key:"_renderElement",value:function(_ref){var _this=this,index=_ref.index,top=_ref.top;if(this._isRendered(index)){var currentItem=this._renderedItems[index];this._delegate.updateItem(index,currentItem);var element=this._renderedItems[index].element;return void(element.style.top=this._wrapperElement.offsetTop+top+"px")}this._delegate.prepareItem(index,function(item){var element=item.element;element.style.position="absolute",element.style.top=top+"px",element.style.left="0px",element.style.right="0px",_this._wrapperElement.appendChild(element),_this._renderedItems[index]=item})}},{key:"_removeElement",value:function(index){if(this._isRendered(index)){var item=this._renderedItems[index];this._delegate.destroyItem(index,item),item.element.parentElement&&item.element.parentElement.removeChild(item.element),item=null,delete this._renderedItems[index]}}},{key:"_removeAllElements",value:function(){for(var key in this._renderedItems)this._renderedItems.hasOwnProperty(key)&&this._removeElement(key)}},{key:"_calculateStartIndex",value:function(current){for(var start=0,end=this._maxIndex;;){var middle=Math.floor((start+end)/2),value=current+this._itemHeightSum[middle];if(start>end)return 0;if(value>=0&&value-this._getItemHeight(middle)<0)return middle;isNaN(value)||value>=0?end=middle-1:start=middle+1}}},{key:"_recalculateItemHeightSum",value:function(){for(var sums=this._itemHeightSum,i=0,sum=0;i<Math.min(sums.length,this._countItems());i++)sum+=this._getItemHeight(i),sums[i]=sum}},{key:"_getItemsInView",value:function(){var topOffset=this._getTopOffset(),topPosition=topOffset,cnt=this._countItems();cnt!==this._itemCount&&(this._recalculateItemHeightSum(),this._maxIndex=cnt-1),this._itemCount=cnt;var startIndex=this._calculateStartIndex(topPosition);startIndex=Math.max(startIndex-30,0),startIndex>0&&(topPosition+=this._itemHeightSum[startIndex-1]);for(var items=[],i=startIndex;cnt>i&&topPosition<4*window.innerHeight;i++){var h=this._getItemHeight(i);i>=this._itemHeightSum.length&&(this._itemHeightSum=this._itemHeightSum.concat(new Array(100))),i>0?this._itemHeightSum[i]=this._itemHeightSum[i-1]+h:this._itemHeightSum[i]=h,this._maxIndex=Math.max(i,this._maxIndex),items.push({index:i,top:topPosition-topOffset}),topPosition+=h}return items}},{key:"_debounce",value:function(func,wait,immediate){var timeout;return function(){var context=this,args=arguments,later=function(){timeout=null,immediate||func.apply(context,args)},callNow=immediate&&!timeout;clearTimeout(timeout),timeout=setTimeout(later,wait),callNow&&func.apply(context,args)}}},{key:"_doubleFireOnTouchend",value:function(){this._render(),this._debounce(this._render.bind(this),100)}},{key:"_addEventListeners",value:function(){ons.platform.isIOS()?this._boundOnChange=this._debounce(this._onChange.bind(this),30):this._boundOnChange=this._onChange.bind(this),this._pageContent.addEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.addEventListener("touchmove",this._boundOnChange,!0),this._pageContent.addEventListener("touchend",this._doubleFireOnTouchend,!0)),window.document.addEventListener("resize",this._boundOnChange,!0)}},{key:"_removeEventListeners",value:function(){this._pageContent.removeEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.removeEventListener("touchmove",this._boundOnChange,!0),this._pageContent.removeEventListener("touchend",this._doubleFireOnTouchend,!0)),window.document.removeEventListener("resize",this._boundOnChange,!0)}},{key:"destroy",value:function(){this._delegate.destroy(),this._parentElement=this._templateElement=this._delegate=this._renderedItems=null,this._removeEventListeners()}}]),LazyRepeatProvider}();ons._internal=ons._internal||{},ons._internal.LazyRepeatProvider=LazyRepeatProvider,ons._internal.LazyRepeatDelegate=LazyRepeatDelegate}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,LiftNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function LiftNavigatorTransitionAnimator(options){_classCallCheck(this,LiftNavigatorTransitionAnimator),options=ons._util.extend({duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(LiftNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%;\n background-color: black;"></div>\n ')}return _inherits(LiftNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(LiftNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentNode.insertBefore(this.backgroundMask,leavePage.element);var maskClear=animit(this.backgroundMask).wait(.6).queue(function(done){_this.backgroundMask.remove(),done()});animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(0, 100%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).wait(.2).restoreStyle().queue(function(done){callback(),done()}),animit(leavePage.element).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:this.duration,timing:this.timing}))}},{key:"pop",value:function(enterPage,leavePage,callback){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element),animit.runAll(animit(this.backgroundMask).wait(.4).queue(function(done){_this2.backgroundMask.remove(),done()}),animit(enterPage.element).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).wait(.4).queue(function(done){callback(),done()}),animit(leavePage.element).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:this.duration,timing:this.timing}))}}]),LiftNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.LiftNavigatorTransitionAnimator=LiftNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var ModifierUtil=function(){function ModifierUtil(){_classCallCheck(this,ModifierUtil)}return _createClass(ModifierUtil,null,[{key:"diff",value:function(last,current){function makeDict(modifier){var dict={};return ModifierUtil.split(modifier).forEach(function(token){return dict[token]=token}),dict}last=makeDict((""+last).trim()),current=makeDict((""+current).trim());var removed=Object.keys(last).reduce(function(result,token){return current[token]||result.push(token),result},[]),added=Object.keys(current).reduce(function(result,token){return last[token]||result.push(token),result},[]);return{added:added,removed:removed}}},{key:"applyDiffToClassList",value:function(diff,classList,template){diff.added.map(function(modifier){return template.replace(/\*/g,modifier)}).forEach(function(klass){return classList.add(klass)}),diff.removed.map(function(modifier){return template.replace(/\*/g,modifier)}).forEach(function(klass){return classList.remove(klass)})}},{key:"applyDiffToElement",value:function(diff,element,scheme){for(var selector in scheme)if(scheme.hasOwnProperty(selector))for(var targetElements=""===selector?[element]:element.querySelectorAll(selector),i=0;i<targetElements.length;i++)ModifierUtil.applyDiffToClassList(diff,targetElements[i].classList,scheme[selector])}},{key:"onModifierChanged",value:function(last,current,element,scheme){return ModifierUtil.applyDiffToElement(ModifierUtil.diff(last,current),element,scheme)}},{key:"initModifier",value:function(element,scheme){var modifier=element.getAttribute("modifier");"string"==typeof modifier&&ModifierUtil.applyDiffToElement({removed:[],added:ModifierUtil.split(modifier)},element,scheme)}},{key:"split",value:function(modifier){return"string"!=typeof modifier?[]:modifier.trim().split(/ +/).filter(function(token){return""!==token})}}]),ModifierUtil}();ons._internal=ons._internal||{},ons._internal.ModifierUtil=ModifierUtil}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util=ons._util,NavigatorPage=function(){function NavigatorPage(params){var _this=this;_classCallCheck(this,NavigatorPage),this.page=params.page,this.name=params.page,this.element=params.element,this.options=params.options,this.navigator=params.navigator,this.initialContent=params.initialContent,this.backButton=util.findChildRecursively(this.element,"ons-back-button"),this._blockEvents=function(event){(_this.navigator._isPopping||_this.navigator._isPushing)&&(event.preventDefault(),event.stopPropagation())},this._pointerEvents.forEach(function(event){return _this.element.addEventListener(event,_this._blockEvents)},!1)}return _createClass(NavigatorPage,[{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"getPageView",value:function(){if(!this._page&&(this._page=util.findParent("ons-page"),!this._page))throw new Error("Fail to fetch ons-page element.");return this._page}},{key:"updateBackButton",value:function(){this.backButton&&(this.navigator._pages.length>1?this.backButton.style.display="block":this.backButton.style.display="none")}},{key:"destroy",value:function(){var _this2=this;this._pointerEvents.forEach(function(event){return _this2.element.removeEventListener(event,_this2._blockEvents)},!1),this.element._destroy();var index=this.navigator._pages.indexOf(this);-1!==index&&this.navigator._pages.splice(index,1),this.element=this._page=this.options=this.navigator=null}},{key:"_pointerEvents",get:function(){return["touchmove"]}}]),NavigatorPage}();window.ons._internal.NavigatorPage=NavigatorPage}(window.ons=window.ons||{}),function(ons){"use strict";ons._internal=ons._internal||{},ons._internal.nullElement=document.createElement("div"),ons._internal.isEnabledAutoStatusBarFill=function(){return!!ons._config.autoStatusBarFill},ons._internal.normalizePageHTML=function(html){return html=(""+html).trim(),html.match(/^<ons-page/)||(html="<ons-page _muted>"+html+"</ons-page>"),html},ons._internal.waitDOMContentLoaded=function(callback){"loading"===document.readyState||"uninitialized"==document.readyState?window.document.addEventListener("DOMContentLoaded",callback):setImmediate(callback)},ons._internal.shouldFillStatusBar=function(element){var checkStatusBar=function(){if(ons._internal.isEnabledAutoStatusBarFill()&&ons.platform.isWebView()&&ons.platform.isIOS7above()){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");for(;;){if(element.hasAttribute("no-status-bar-fill"))return!1;if(element=element.parentNode,!element||!element.hasAttribute)return!0}}return!1};return new Promise(function(resolve,reject){"object"==typeof device?document.addEventListener("deviceready",function(){checkStatusBar()&&resolve()}):checkStatusBar()&&resolve(),reject()})},ons._internal.templateStore={_storage:{},get:function(key){return ons._internal.templateStore._storage[key]||null},set:function(key,template){ons._internal.templateStore._storage[key]=template}},document.addEventListener("_templateloaded",function(e){"ons-template"===e.target.nodeName.toLowerCase()&&ons._internal.templateStore.set(e.templateId,e.template)},!1),document.addEventListener("DOMContentLoaded",function(){function register(query){for(var templates=document.querySelectorAll(query),i=0;i<templates.length;i++)ons._internal.templateStore.set(templates[i].getAttribute("id"),templates[i].textContent)}register('script[type="text/ons-template"]'),register('script[type="text/template"]'),register('script[type="text/ng-template"]')},!1),ons._internal.getTemplateHTMLAsync=function(page){return new Promise(function(resolve,reject){setImmediate(function(){var cache=ons._internal.templateStore.get(page);if(cache){var html="string"==typeof cache?cache:cache[1];resolve(html)}else!function(){var xhr=new XMLHttpRequest;xhr.open("GET",page,!0),xhr.onload=function(response){var html=xhr.responseText;xhr.status>=400&&xhr.status<600?reject(html):resolve(html)},xhr.onerror=function(){throw new Error("The page is not found: "+page)},xhr.send(null)}()})})},ons._internal.getPageHTMLAsync=function(page){var pages=ons.pageAttributeExpression.evaluate(page),getPage=function getPage(page){return"string"!=typeof page?Promise.reject("Must specify a page."):ons._internal.getTemplateHTMLAsync(page).then(function(html){return ons._internal.normalizePageHTML(html)},function(error){return 0===pages.length?Promise.reject(error):getPage(pages.shift())}).then(function(html){return ons._internal.normalizePageHTML(html)})};return getPage(pages.shift())}}(window.ons=window.ons||{}),function(ons){"use strict";var util=ons._util;ons.notification={},ons.notification._createAlertDialog=function(title,message,buttonLabels,primaryButtonIndex,modifier,animation,_callback,messageIsHTML,cancelable,promptDialog,autofocus,placeholder,defaultValue,submitOnEnter,compile){compile=compile||function(object){return object};var titleElementHTML="string"==typeof title?'<div class="alert-dialog-title"></div>':"",dialogElement=util.createElement("\n <ons-alert-dialog>\n "+titleElementHTML+'\n <div class="alert-dialog-content"></div>\n <div class="alert-dialog-footer"></div>\n </ons-alert-dialog>'),titleElement=dialogElement.querySelector(".alert-dialog-title"),messageElement=dialogElement.querySelector(".alert-dialog-content"),footerElement=dialogElement.querySelector(".alert-dialog-footer"),inputElement=void 0;"string"==typeof title&&(titleElement.textContent=title),titleElement=null,dialogElement.setAttribute("animation",animation),messageIsHTML?messageElement.innerHTML=message:messageElement.textContent=message,promptDialog&&(inputElement=util.createElement('<input class="text-input" type="text"></input>'),modifier&&inputElement.classList.add("text-input--"+modifier),inputElement.setAttribute("placeholder",placeholder),inputElement.value=defaultValue,inputElement.style.width="100%",inputElement.style.marginTop="10px",messageElement.appendChild(inputElement),submitOnEnter&&inputElement.addEventListener("keypress",function(event){13===event.keyCode&&dialogElement.hide({callback:function(){_callback(inputElement.value),dialogElement.destroy(),dialogElement=null}})},!1)),document.body.appendChild(dialogElement),compile(dialogElement),buttonLabels.length<=2&&footerElement.classList.add("alert-dialog-footer--one");for(var createButton=function(i){var buttonElement=util.createElement('<button class="alert-dialog-button"></button>');buttonElement.textContent=buttonLabels[i],i==primaryButtonIndex&&buttonElement.classList.add("alert-dialog-button--primal"),buttonLabels.length<=2&&buttonElement.classList.add("alert-dialog-button--one");var onClick=function onClick(){buttonElement.removeEventListener("click",onClick,!1),dialogElement.hide({callback:function(){_callback(promptDialog?inputElement.value:i),dialogElement.destroy(),dialogElement=inputElement=buttonElement=null}})};buttonElement.addEventListener("click",onClick,!1),footerElement.appendChild(buttonElement)},i=0;i<buttonLabels.length;i++)createButton(i);return cancelable&&(dialogElement.setCancelable(cancelable),dialogElement.addEventListener("cancel",function(){_callback(promptDialog?null:-1),setTimeout(function(){dialogElement.destroy(),dialogElement=null,inputElement=null})},!1)),dialogElement.show({callback:function(){inputElement&&promptDialog&&autofocus&&inputElement.focus()}}),messageElement=footerElement=null,modifier&&dialogElement.setAttribute("modifier",modifier),Promise.resolve(dialogElement)},ons.notification._alertOriginal=function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",callback:function(){}};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Alert dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,!1,!1,!1,"","",!1,options.compile)},ons.notification.alert=ons.notification._alertOriginal,ons.notification._confirmOriginal=function(options){var defaults={buttonLabels:["Cancel","OK"],primaryButtonIndex:1,animation:"default",title:"Confirm",callback:function(){},cancelable:!1};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Confirm dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,options.buttonLabels,options.primaryButtonIndex,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!1,!1,"","",!1,options.compile)},ons.notification.confirm=ons.notification._confirmOriginal,ons.notification._promptOriginal=function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",defaultValue:"",placeholder:"",callback:function(){},cancelable:!1,autofocus:!0,submitOnEnter:!0};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Prompt dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!0,options.autofocus,options.placeholder,options.defaultValue,options.submitOnEnter,options.compile)},ons.notification.prompt=ons.notification._promptOriginal}(window.ons=window.ons||{}),function(ons){var create=function(){var obj={_isPortrait:!1,isPortrait:function(){return this._isPortrait()},isLandscape:function(){return!this.isPortrait()},_init:function(){return document.addEventListener("DOMContentLoaded",this._onDOMContentLoaded.bind(this),!1),"orientation"in window?window.addEventListener("orientationchange",this._onOrientationChange.bind(this),!1):window.addEventListener("resize",this._onResize.bind(this),!1),this._isPortrait=function(){return window.innerHeight>window.innerWidth},this},_onDOMContentLoaded:function(){this._installIsPortraitImplementation(),this.emit("change",{isPortrait:this.isPortrait()})},_installIsPortraitImplementation:function(){var isPortrait=window.innerWidth<window.innerHeight;"orientation"in window?window.orientation%180===0?this._isPortrait=function(){return 0===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return 90===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return window.innerHeight>window.innerWidth}},_onOrientationChange:function(){var _this=this,isPortrait=this._isPortrait(),nIter=0,interval=setInterval(function(){nIter++;var w=window.innerWidth,h=window.innerHeight;isPortrait&&h>=w||!isPortrait&&w>=h?(_this.emit("change",{isPortrait:isPortrait}),clearInterval(interval)):50===nIter&&(_this.emit("change",{isPortrait:isPortrait}),clearInterval(interval))},20)},_onResize:function(){this.emit("change",{isPortrait:this.isPortrait()})}};return MicroEvent.mixin(obj),obj};ons.orientation=create()._init()}(window.ons=window.ons||{}),function(ons){ons.pageAttributeExpression={_variables:{},defineVariable:function(name,value){var overwrite=arguments.length<=2||void 0===arguments[2]?!1:arguments[2];if("string"!=typeof name)throw new Error("Variable name must be a string.");if("string"!=typeof value&&"function"!=typeof value)throw new Error("Variable value must be a string or a function.");if(this._variables.hasOwnProperty(name)&&!overwrite)throw new Error('"'+name+'" is already defined.');this._variables[name]=value},getVariable:function(name){return this._variables.hasOwnProperty(name)?this._variables[name]:null},removeVariable:function(name){delete this._variables[name]},getAllVariables:function(){return this._variables},_parsePart:function(part){var c=void 0,inInterpolation=!1,currentIndex=0,tokens=[];if(0===part.length)throw new Error("Unable to parse empty string.");for(var i=0;i<part.length;i++)if(c=part.charAt(i),"$"===c&&"{"===part.charAt(i+1)){if(inInterpolation)throw new Error("Nested interpolation not supported.");var token=part.substring(currentIndex,i);token.length>0&&tokens.push(part.substring(currentIndex,i)),currentIndex=i,inInterpolation=!0}else if("}"===c){if(!inInterpolation)throw new Error("} must be preceeded by ${");var token=part.substring(currentIndex,i+1);token.length>0&&tokens.push(part.substring(currentIndex,i+1)),currentIndex=i+1,inInterpolation=!1}if(inInterpolation)throw new Error("Unterminated interpolation.");return tokens.push(part.substring(currentIndex,part.length)),tokens},_replaceToken:function(token){var re=/^\${(.*?)}$/,match=token.match(re);if(match){var _name=match[1].trim(),variable=this.getVariable(_name);if(null===variable)throw new Error('Variable "'+_name+'" does not exist.');if("string"==typeof variable)return variable;var rv=variable();if("string"!=typeof rv)throw new Error("Must return a string.");return rv}return token},_replaceTokens:function(tokens){return tokens.map(this._replaceToken.bind(this))},_parseExpression:function(expression){return expression.split(",").map(function(part){return part.trim()}).map(this._parsePart.bind(this)).map(this._replaceTokens.bind(this)).map(function(part){return part.join("")})},evaluate:function(expression){return expression?this._parseExpression(expression):[]}},ons.pageAttributeExpression.defineVariable("mobileOS",ons.platform.getMobileOS()),ons.pageAttributeExpression.defineVariable("iOSDevice",ons.platform.getIOSDevice()),ons.pageAttributeExpression.defineVariable("runtime",function(){return ons.platform.isWebView()?"cordova":"browser"})}(window.ons=window.ons||{}),function(ons){"use strict";ons.softwareKeyboard=new MicroEvent,ons.softwareKeyboard._visible=!1;var onShow=function(){ons.softwareKeyboard._visible=!0,ons.softwareKeyboard.emit("show")},onHide=function(){ons.softwareKeyboard._visible=!1,ons.softwareKeyboard.emit("hide")},bindEvents=function(){return"undefined"!=typeof Keyboard?(Keyboard.onshow=onShow,Keyboard.onhide=onHide,ons.softwareKeyboard.emit("init",{visible:Keyboard.isVisible}),!0):"undefined"!=typeof cordova.plugins&&"undefined"!=typeof cordova.plugins.Keyboard?(window.addEventListener("native.keyboardshow",onShow),window.addEventListener("native.keyboardhide",onHide),ons.softwareKeyboard.emit("init",{visible:cordova.plugins.Keyboard.isVisible}),!0):!1},noPluginError=function(){console.warn("ons-keyboard: Cordova Keyboard plugin is not present.")};document.addEventListener("deviceready",function(){bindEvents()||((document.querySelector("[ons-keyboard-active]")||document.querySelector("[ons-keyboard-inactive]"))&&noPluginError(),ons.softwareKeyboard.on=noPluginError)})}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,SimpleSlideNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function SimpleSlideNavigatorTransitionAnimator(options){_classCallCheck(this,SimpleSlideNavigatorTransitionAnimator),options=ons._util.extend({duration:.3,timing:"cubic-bezier(.1, .7, .4, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(SimpleSlideNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%; z-index: 2;\n background-color: black; opacity: 0;"></div>\n '),this.blackMaskOpacity=.4}return _inherits(SimpleSlideNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(SimpleSlideNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentElement.insertBefore(this.backgroundMask,leavePage.element.nextSibling),animit.runAll(animit(this.backgroundMask).saveStyle().queue({opacity:0,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:this.blackMaskOpacity},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(100%, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-45%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().wait(.2).queue(function(done){callback(),done()}))}},{key:"pop",value:function(enterPage,leavePage,done){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element.nextSibling),animit.runAll(animit(this.backgroundMask).saveStyle().queue({opacity:this.blackMaskOpacity,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this2.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(-45%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(.2).queue(function(finish){done(),finish()}))}}]),SimpleSlideNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.SimpleSlideNavigatorTransitionAnimator=SimpleSlideNavigatorTransitionAnimator}(window.ons=window.ons||{});var _get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var TabbarAnimator=function(){function TabbarAnimator(options){_classCallCheck(this,TabbarAnimator),options=options||{},this.timing=options.timing||"linear",this.duration=void 0!==options.duration?options.duration:"0.4",this.delay=void 0!==options.delay?options.delay:"0"}return _createClass(TabbarAnimator,[{key:"apply",value:function(enterPage,leavePage,enterPageIndex,leavePageIndex,done){throw new Error("This method must be implemented.")}}]),TabbarAnimator}(),TabbarNoneAnimator=function(_TabbarAnimator){function TabbarNoneAnimator(){_classCallCheck(this,TabbarNoneAnimator),_get(Object.getPrototypeOf(TabbarNoneAnimator.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabbarNoneAnimator,_TabbarAnimator),_createClass(TabbarNoneAnimator,[{key:"apply",value:function(enterPage,leavePage,enterIndex,leaveIndex,done){done()}}]),TabbarNoneAnimator}(TabbarAnimator),TabbarFadeAnimator=function(_TabbarAnimator2){function TabbarFadeAnimator(options){_classCallCheck(this,TabbarFadeAnimator),options.timing=void 0!==options.timing?options.timing:"linear",options.duration=void 0!==options.duration?options.duration:"0.4",options.delay=void 0!==options.delay?options.delay:"0",_get(Object.getPrototypeOf(TabbarFadeAnimator.prototype),"constructor",this).call(this,options)}return _inherits(TabbarFadeAnimator,_TabbarAnimator2),_createClass(TabbarFadeAnimator,[{key:"apply",value:function(enterPage,leavePage,enterPageIndex,leavePageIndex,done){animit.runAll(animit(enterPage).saveStyle().queue({transform:"translate3D(0, 0, 0)",opacity:0}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)",opacity:1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(callback){done(),callback()}),animit(leavePage).queue({transform:"translate3D(0, 0, 0)",opacity:1}).wait(this.delay).queue({ transform:"translate3D(0, 0, 0)",opacity:0},{duration:this.duration,timing:this.timing}))}}]),TabbarFadeAnimator}(TabbarAnimator),TabbarSlideAnimator=function(_TabbarAnimator3){function TabbarSlideAnimator(options){_classCallCheck(this,TabbarSlideAnimator),options.timing=void 0!==options.timing?options.timing:"ease-in",options.duration=void 0!==options.duration?options.duration:"0.15",options.delay=void 0!==options.delay?options.delay:"0",_get(Object.getPrototypeOf(TabbarSlideAnimator.prototype),"constructor",this).call(this,options)}return _inherits(TabbarSlideAnimator,_TabbarAnimator3),_createClass(TabbarSlideAnimator,[{key:"apply",value:function(enterPage,leavePage,enterIndex,leaveIndex,done){var sgn=enterIndex>leaveIndex;animit.runAll(animit(enterPage).saveStyle().queue({transform:"translate3D("+(sgn?"":"-")+"100%, 0, 0)"}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)"},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(callback){done(),callback()}),animit(leavePage).queue({transform:"translate3D(0, 0, 0)"}).wait(this.delay).queue({transform:"translate3D("+(sgn?"-":"")+"100%, 0, 0)"},{duration:this.duration,timing:this.timing}))}}]),TabbarSlideAnimator}(TabbarAnimator);ons._internal=ons._internal||{},ons._internal.TabbarAnimator=TabbarAnimator,ons._internal.TabbarFadeAnimator=TabbarFadeAnimator,ons._internal.TabbarNoneAnimator=TabbarNoneAnimator,ons._internal.TabbarSlideAnimator=TabbarSlideAnimator}(window.ons=window.ons||{}),function(window){"use strict";function setup(){GestureDetector.READY||(Event.determineEventTypes(),Utils.each(GestureDetector.gestures,function(gesture){Detection.register(gesture)}),Event.onTouch(GestureDetector.DOCUMENT,EVENT_MOVE,Detection.detect),Event.onTouch(GestureDetector.DOCUMENT,EVENT_END,Detection.detect),GestureDetector.READY=!0)}var GestureDetector=function GestureDetector(element,options){return new GestureDetector.Instance(element,options||{})};GestureDetector.defaults={behavior:{userSelect:"none",touchAction:"pan-y",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},GestureDetector.DOCUMENT=document,GestureDetector.HAS_POINTEREVENTS=navigator.pointerEnabled||navigator.msPointerEnabled,GestureDetector.HAS_TOUCHEVENTS="ontouchstart"in window,GestureDetector.IS_MOBILE=/mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent),GestureDetector.NO_MOUSEEVENTS=GestureDetector.HAS_TOUCHEVENTS&&GestureDetector.IS_MOBILE||GestureDetector.HAS_POINTEREVENTS,GestureDetector.CALCULATE_INTERVAL=25;var EVENT_TYPES={},DIRECTION_DOWN=GestureDetector.DIRECTION_DOWN="down",DIRECTION_LEFT=GestureDetector.DIRECTION_LEFT="left",DIRECTION_UP=GestureDetector.DIRECTION_UP="up",DIRECTION_RIGHT=GestureDetector.DIRECTION_RIGHT="right",POINTER_MOUSE=GestureDetector.POINTER_MOUSE="mouse",POINTER_TOUCH=GestureDetector.POINTER_TOUCH="touch",POINTER_PEN=GestureDetector.POINTER_PEN="pen",EVENT_START=GestureDetector.EVENT_START="start",EVENT_MOVE=GestureDetector.EVENT_MOVE="move",EVENT_END=GestureDetector.EVENT_END="end",EVENT_RELEASE=GestureDetector.EVENT_RELEASE="release",EVENT_TOUCH=GestureDetector.EVENT_TOUCH="touch";GestureDetector.READY=!1,GestureDetector.plugins=GestureDetector.plugins||{},GestureDetector.gestures=GestureDetector.gestures||{};var Utils=GestureDetector.utils={extend:function(dest,src,merge){for(var key in src)!src.hasOwnProperty(key)||void 0!==dest[key]&&merge||(dest[key]=src[key]);return dest},on:function(element,type,handler){element.addEventListener(type,handler,!1)},off:function(element,type,handler){element.removeEventListener(type,handler,!1)},each:function(obj,iterator,context){var i,len;if("forEach"in obj)obj.forEach(iterator,context);else if(void 0!==obj.length){for(i=0,len=obj.length;len>i;i++)if(iterator.call(context,obj[i],i,obj)===!1)return}else for(i in obj)if(obj.hasOwnProperty(i)&&iterator.call(context,obj[i],i,obj)===!1)return},inStr:function(src,find){return src.indexOf(find)>-1},inArray:function(src,find){if(src.indexOf){var index=src.indexOf(find);return-1===index?!1:index}for(var i=0,len=src.length;len>i;i++)if(src[i]===find)return i;return!1},toArray:function(obj){return Array.prototype.slice.call(obj,0)},hasParent:function(node,parent){for(;node;){if(node==parent)return!0;node=node.parentNode}return!1},getCenter:function(touches){var pageX=[],pageY=[],clientX=[],clientY=[],min=Math.min,max=Math.max;return 1===touches.length?{pageX:touches[0].pageX,pageY:touches[0].pageY,clientX:touches[0].clientX,clientY:touches[0].clientY}:(Utils.each(touches,function(touch){pageX.push(touch.pageX),pageY.push(touch.pageY),clientX.push(touch.clientX),clientY.push(touch.clientY)}),{pageX:(min.apply(Math,pageX)+max.apply(Math,pageX))/2,pageY:(min.apply(Math,pageY)+max.apply(Math,pageY))/2,clientX:(min.apply(Math,clientX)+max.apply(Math,clientX))/2,clientY:(min.apply(Math,clientY)+max.apply(Math,clientY))/2})},getVelocity:function(deltaTime,deltaX,deltaY){return{x:Math.abs(deltaX/deltaTime)||0,y:Math.abs(deltaY/deltaTime)||0}},getAngle:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return 180*Math.atan2(y,x)/Math.PI},getDirection:function(touch1,touch2){var x=Math.abs(touch1.clientX-touch2.clientX),y=Math.abs(touch1.clientY-touch2.clientY);return x>=y?touch1.clientX-touch2.clientX>0?DIRECTION_LEFT:DIRECTION_RIGHT:touch1.clientY-touch2.clientY>0?DIRECTION_UP:DIRECTION_DOWN},getDistance:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return Math.sqrt(x*x+y*y)},getScale:function(start,end){return start.length>=2&&end.length>=2?this.getDistance(end[0],end[1])/this.getDistance(start[0],start[1]):1},getRotation:function(start,end){return start.length>=2&&end.length>=2?this.getAngle(end[1],end[0])-this.getAngle(start[1],start[0]):0},isVertical:function(direction){return direction==DIRECTION_UP||direction==DIRECTION_DOWN},setPrefixedCss:function(element,prop,value,toggle){var prefixes=["","Webkit","Moz","O","ms"];prop=Utils.toCamelCase(prop);for(var i=0;i<prefixes.length;i++){var p=prop;if(prefixes[i]&&(p=prefixes[i]+p.slice(0,1).toUpperCase()+p.slice(1)),p in element.style){element.style[p]=(null===toggle||toggle)&&value||"";break}}},toggleBehavior:function(element,props,toggle){if(props&&element&&element.style){Utils.each(props,function(value,prop){Utils.setPrefixedCss(element,prop,value,toggle)});var falseFn=toggle&&function(){return!1};"none"==props.userSelect&&(element.onselectstart=falseFn),"none"==props.userDrag&&(element.ondragstart=falseFn)}},toCamelCase:function(str){return str.replace(/[_-]([a-z])/g,function(s){return s[1].toUpperCase()})}},Event=GestureDetector.event={preventMouseEvents:!1,started:!1,shouldDetect:!1,on:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.on(element,type,handler),hook&&hook(type)})},off:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.off(element,type,handler),hook&&hook(type)})},onTouch:function(element,eventType,handler){var self=this,onTouchHandler=function(ev){var triggerType,srcType=ev.type.toLowerCase(),isPointer=GestureDetector.HAS_POINTEREVENTS,isMouse=Utils.inStr(srcType,"mouse");isMouse&&self.preventMouseEvents||(isMouse&&eventType==EVENT_START&&0===ev.button?(self.preventMouseEvents=!1,self.shouldDetect=!0):isPointer&&eventType==EVENT_START?self.shouldDetect=1===ev.buttons||PointerEvent.matchType(POINTER_TOUCH,ev):isMouse||eventType!=EVENT_START||(self.preventMouseEvents=!0,self.shouldDetect=!0),isPointer&&eventType!=EVENT_END&&PointerEvent.updatePointer(eventType,ev),self.shouldDetect&&(triggerType=self.doDetect.call(self,ev,eventType,element,handler)),triggerType==EVENT_END&&(self.preventMouseEvents=!1,self.shouldDetect=!1,PointerEvent.reset()),isPointer&&eventType==EVENT_END&&PointerEvent.updatePointer(eventType,ev))};return this.on(element,EVENT_TYPES[eventType],onTouchHandler),onTouchHandler},doDetect:function(ev,eventType,element,handler){var touchList=this.getTouchList(ev,eventType),touchListLength=touchList.length,triggerType=eventType,triggerChange=touchList.trigger,changedLength=touchListLength;eventType==EVENT_START?triggerChange=EVENT_TOUCH:eventType==EVENT_END&&(triggerChange=EVENT_RELEASE,changedLength=touchList.length-(ev.changedTouches?ev.changedTouches.length:1)),changedLength>0&&this.started&&(triggerType=EVENT_MOVE),this.started=!0;var evData=this.collectEventData(element,triggerType,touchList,ev);return eventType!=EVENT_END&&handler.call(Detection,evData),triggerChange&&(evData.changedLength=changedLength,evData.eventType=triggerChange,handler.call(Detection,evData),evData.eventType=triggerType,delete evData.changedLength),triggerType==EVENT_END&&(handler.call(Detection,evData),this.started=!1),triggerType},determineEventTypes:function(){var types;return types=GestureDetector.HAS_POINTEREVENTS?window.PointerEvent?["pointerdown","pointermove","pointerup pointercancel lostpointercapture"]:["MSPointerDown","MSPointerMove","MSPointerUp MSPointerCancel MSLostPointerCapture"]:GestureDetector.NO_MOUSEEVENTS?["touchstart","touchmove","touchend touchcancel"]:["touchstart mousedown","touchmove mousemove","touchend touchcancel mouseup"],EVENT_TYPES[EVENT_START]=types[0],EVENT_TYPES[EVENT_MOVE]=types[1],EVENT_TYPES[EVENT_END]=types[2],EVENT_TYPES},getTouchList:function(ev,eventType){if(GestureDetector.HAS_POINTEREVENTS)return PointerEvent.getTouchList();if(ev.touches){if(eventType==EVENT_MOVE)return ev.touches;var identifiers=[],concat=[].concat(Utils.toArray(ev.touches),Utils.toArray(ev.changedTouches)),touchList=[];return Utils.each(concat,function(touch){Utils.inArray(identifiers,touch.identifier)===!1&&touchList.push(touch),identifiers.push(touch.identifier)}),touchList}return ev.identifier=1,[ev]},collectEventData:function(element,eventType,touches,ev){var pointerType=POINTER_TOUCH;return Utils.inStr(ev.type,"mouse")||PointerEvent.matchType(POINTER_MOUSE,ev)?pointerType=POINTER_MOUSE:PointerEvent.matchType(POINTER_PEN,ev)&&(pointerType=POINTER_PEN),{center:Utils.getCenter(touches),timeStamp:Date.now(),target:ev.target,touches:touches,eventType:eventType,pointerType:pointerType,srcEvent:ev,preventDefault:function(){var srcEvent=this.srcEvent;srcEvent.preventManipulation&&srcEvent.preventManipulation(),srcEvent.preventDefault&&srcEvent.preventDefault()},stopPropagation:function(){this.srcEvent.stopPropagation()},stopDetect:function(){return Detection.stopDetect()}}}},PointerEvent=GestureDetector.PointerEvent={pointers:{},getTouchList:function(){var touchlist=[];return Utils.each(this.pointers,function(pointer){touchlist.push(pointer)}),touchlist},updatePointer:function(eventType,pointerEvent){eventType==EVENT_END||eventType!=EVENT_END&&1!==pointerEvent.buttons?delete this.pointers[pointerEvent.pointerId]:(pointerEvent.identifier=pointerEvent.pointerId,this.pointers[pointerEvent.pointerId]=pointerEvent)},matchType:function(pointerType,ev){if(!ev.pointerType)return!1;var pt=ev.pointerType,types={};return types[POINTER_MOUSE]=pt===(ev.MSPOINTER_TYPE_MOUSE||POINTER_MOUSE),types[POINTER_TOUCH]=pt===(ev.MSPOINTER_TYPE_TOUCH||POINTER_TOUCH),types[POINTER_PEN]=pt===(ev.MSPOINTER_TYPE_PEN||POINTER_PEN),types[pointerType]},reset:function(){this.pointers={}}},Detection=GestureDetector.detection={gestures:[],current:null,previous:null,stopped:!1,startDetect:function(inst,eventData){this.current||(this.stopped=!1,this.current={inst:inst,startEvent:Utils.extend({},eventData),lastEvent:!1,lastCalcEvent:!1,futureCalcEvent:!1,lastCalcData:{},name:""},this.detect(eventData))},detect:function(eventData){if(this.current&&!this.stopped){eventData=this.extendEventData(eventData);var inst=this.current.inst,instOptions=inst.options;return Utils.each(this.gestures,function(gesture){!this.stopped&&inst.enabled&&instOptions[gesture.name]&&gesture.handler.call(gesture,eventData,inst)},this),this.current&&(this.current.lastEvent=eventData),eventData.eventType==EVENT_END&&this.stopDetect(),eventData}},stopDetect:function(){this.previous=Utils.extend({},this.current),this.current=null,this.stopped=!0},getCalculatedData:function(ev,center,deltaTime,deltaX,deltaY){var cur=this.current,recalc=!1,calcEv=cur.lastCalcEvent,calcData=cur.lastCalcData;calcEv&&ev.timeStamp-calcEv.timeStamp>GestureDetector.CALCULATE_INTERVAL&&(center=calcEv.center,deltaTime=ev.timeStamp-calcEv.timeStamp,deltaX=ev.center.clientX-calcEv.center.clientX,deltaY=ev.center.clientY-calcEv.center.clientY,recalc=!0),(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(cur.futureCalcEvent=ev),(!cur.lastCalcEvent||recalc)&&(calcData.velocity=Utils.getVelocity(deltaTime,deltaX,deltaY),calcData.angle=Utils.getAngle(center,ev.center),calcData.direction=Utils.getDirection(center,ev.center),cur.lastCalcEvent=cur.futureCalcEvent||ev,cur.futureCalcEvent=ev),ev.velocityX=calcData.velocity.x,ev.velocityY=calcData.velocity.y,ev.interimAngle=calcData.angle,ev.interimDirection=calcData.direction},extendEventData:function(ev){var cur=this.current,startEv=cur.startEvent,lastEv=cur.lastEvent||startEv;(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(startEv.touches=[],Utils.each(ev.touches,function(touch){startEv.touches.push({clientX:touch.clientX,clientY:touch.clientY})}));var deltaTime=ev.timeStamp-startEv.timeStamp,deltaX=ev.center.clientX-startEv.center.clientX,deltaY=ev.center.clientY-startEv.center.clientY;return this.getCalculatedData(ev,lastEv.center,deltaTime,deltaX,deltaY),Utils.extend(ev,{startEvent:startEv,deltaTime:deltaTime,deltaX:deltaX,deltaY:deltaY,distance:Utils.getDistance(startEv.center,ev.center),angle:Utils.getAngle(startEv.center,ev.center),direction:Utils.getDirection(startEv.center,ev.center),scale:Utils.getScale(startEv.touches,ev.touches),rotation:Utils.getRotation(startEv.touches,ev.touches)}),ev},register:function(gesture){var options=gesture.defaults||{};return void 0===options[gesture.name]&&(options[gesture.name]=!0),Utils.extend(GestureDetector.defaults,options,!0),gesture.index=gesture.index||1e3,this.gestures.push(gesture),this.gestures.sort(function(a,b){return a.index<b.index?-1:a.index>b.index?1:0}),this.gestures}};GestureDetector.Instance=function(element,options){var self=this;setup(),this.element=element,this.enabled=!0,Utils.each(options,function(value,name){delete options[name],options[Utils.toCamelCase(name)]=value}),this.options=Utils.extend(Utils.extend({},GestureDetector.defaults),options||{}),this.options.behavior&&Utils.toggleBehavior(this.element,this.options.behavior,!0),this.eventStartHandler=Event.onTouch(element,EVENT_START,function(ev){self.enabled&&ev.eventType==EVENT_START?Detection.startDetect(self,ev):ev.eventType==EVENT_TOUCH&&Detection.detect(ev)}),this.eventHandlers=[]},GestureDetector.Instance.prototype={on:function(gestures,handler){var self=this;return Event.on(self.element,gestures,handler,function(type){self.eventHandlers.push({gesture:type,handler:handler})}),self},off:function(gestures,handler){var self=this;return Event.off(self.element,gestures,handler,function(type){var index=Utils.inArray({gesture:type,handler:handler});index!==!1&&self.eventHandlers.splice(index,1)}),self},trigger:function(gesture,eventData){eventData||(eventData={});var event=GestureDetector.DOCUMENT.createEvent("Event");event.initEvent(gesture,!0,!0),event.gesture=eventData;var element=this.element;return Utils.hasParent(eventData.target,element)&&(element=eventData.target),element.dispatchEvent(event),this},enable:function(state){return this.enabled=state,this},dispose:function(){var i,eh;for(Utils.toggleBehavior(this.element,this.options.behavior,!1),i=-1;eh=this.eventHandlers[++i];)Utils.off(this.element,eh.gesture,eh.handler);return this.eventHandlers=[],Event.off(this.element,EVENT_TYPES[EVENT_START],this.eventStartHandler),null}},function(name){function dragGesture(ev,inst){var cur=Detection.current;if(!(inst.options.dragMaxTouches>0&&ev.touches.length>inst.options.dragMaxTouches))switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.distance<inst.options.dragMinDistance&&cur.name!=name)return;var startCenter=cur.startEvent.center;if(cur.name!=name&&(cur.name=name,inst.options.dragDistanceCorrection&&ev.distance>0)){var factor=Math.abs(inst.options.dragMinDistance/ev.distance);startCenter.pageX+=ev.deltaX*factor,startCenter.pageY+=ev.deltaY*factor,startCenter.clientX+=ev.deltaX*factor,startCenter.clientY+=ev.deltaY*factor,ev=Detection.extendEventData(ev)}(cur.lastEvent.dragLockToAxis||inst.options.dragLockToAxis&&inst.options.dragLockMinDistance<=ev.distance)&&(ev.dragLockToAxis=!0);var lastDirection=cur.lastEvent.direction;ev.dragLockToAxis&&lastDirection!==ev.direction&&(Utils.isVertical(lastDirection)?ev.direction=ev.deltaY<0?DIRECTION_UP:DIRECTION_DOWN:ev.direction=ev.deltaX<0?DIRECTION_LEFT:DIRECTION_RIGHT),triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),inst.trigger(name+ev.direction,ev);var isVertical=Utils.isVertical(ev.direction);(inst.options.dragBlockVertical&&isVertical||inst.options.dragBlockHorizontal&&!isVertical)&&ev.preventDefault();break;case EVENT_RELEASE:triggered&&ev.changedLength<=inst.options.dragMaxTouches&&(inst.trigger(name+"end",ev),triggered=!1);break;case EVENT_END:triggered=!1}}var triggered=!1;GestureDetector.gestures.Drag={name:name,index:50,handler:dragGesture,defaults:{dragMinDistance:10,dragDistanceCorrection:!0,dragMaxTouches:1,dragBlockHorizontal:!1,dragBlockVertical:!1,dragLockToAxis:!1,dragLockMinDistance:25}}}("drag"),GestureDetector.gestures.Gesture={name:"gesture",index:1337,handler:function(ev,inst){inst.trigger(this.name,ev)}},function(name){function holdGesture(ev,inst){var options=inst.options,current=Detection.current;switch(ev.eventType){case EVENT_START:clearTimeout(timer),current.name=name,timer=setTimeout(function(){current&&current.name==name&&inst.trigger(name,ev)},options.holdTimeout);break;case EVENT_MOVE:ev.distance>options.holdThreshold&&clearTimeout(timer);break;case EVENT_RELEASE:clearTimeout(timer)}}var timer;GestureDetector.gestures.Hold={name:name,index:10,defaults:{holdTimeout:500,holdThreshold:2},handler:holdGesture}}("hold"),GestureDetector.gestures.Release={name:"release",index:1/0,handler:function(ev,inst){ev.eventType==EVENT_RELEASE&&inst.trigger(this.name,ev)}},GestureDetector.gestures.Swipe={name:"swipe",index:40,defaults:{swipeMinTouches:1,swipeMaxTouches:1,swipeVelocityX:.6,swipeVelocityY:.6},handler:function(ev,inst){if(ev.eventType==EVENT_RELEASE){var touches=ev.touches.length,options=inst.options;if(touches<options.swipeMinTouches||touches>options.swipeMaxTouches)return;(ev.velocityX>options.swipeVelocityX||ev.velocityY>options.swipeVelocityY)&&(inst.trigger(this.name,ev),inst.trigger(this.name+ev.direction,ev))}}},function(name){function tapGesture(ev,inst){var sincePrev,didDoubleTap,options=inst.options,current=Detection.current,prev=Detection.previous;switch(ev.eventType){case EVENT_START:hasMoved=!1;break;case EVENT_MOVE:hasMoved=hasMoved||ev.distance>options.tapMaxDistance;break;case EVENT_END:!Utils.inStr(ev.srcEvent.type,"cancel")&&ev.deltaTime<options.tapMaxTime&&!hasMoved&&(sincePrev=prev&&prev.lastEvent&&ev.timeStamp-prev.lastEvent.timeStamp,didDoubleTap=!1,prev&&prev.name==name&&sincePrev&&sincePrev<options.doubleTapInterval&&ev.distance<options.doubleTapDistance&&(inst.trigger("doubletap",ev),didDoubleTap=!0),(!didDoubleTap||options.tapAlways)&&(current.name=name,inst.trigger(current.name,ev)))}}var hasMoved=!1;GestureDetector.gestures.Tap={name:name,index:100,handler:tapGesture,defaults:{tapMaxTime:250,tapMaxDistance:10,tapAlways:!0,doubleTapDistance:20,doubleTapInterval:300}}}("tap"),GestureDetector.gestures.Touch={name:"touch",index:-(1/0),defaults:{preventDefault:!1,preventMouse:!1},handler:function(ev,inst){return inst.options.preventMouse&&ev.pointerType==POINTER_MOUSE?void ev.stopDetect():(inst.options.preventDefault&&ev.preventDefault(),void(ev.eventType==EVENT_TOUCH&&inst.trigger("touch",ev)))}},function(name){function transformGesture(ev,inst){switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.touches.length<2)return;var scaleThreshold=Math.abs(1-ev.scale),rotationThreshold=Math.abs(ev.rotation);if(scaleThreshold<inst.options.transformMinScale&&rotationThreshold<inst.options.transformMinRotation)return;Detection.current.name=name,triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),rotationThreshold>inst.options.transformMinRotation&&inst.trigger("rotate",ev),scaleThreshold>inst.options.transformMinScale&&(inst.trigger("pinch",ev),inst.trigger("pinch"+(ev.scale<1?"in":"out"),ev));break;case EVENT_RELEASE:triggered&&ev.changedLength<2&&(inst.trigger(name+"end",ev),triggered=!1)}}var triggered=!1;GestureDetector.gestures.Transform={name:name,index:45,defaults:{transformMinScale:.01,transformMinRotation:1},handler:transformGesture}}("transform"),window.ons=window.ons||{},window.ons.GestureDetector=GestureDetector}(window),window.styler=function(){"use strict";var styler=function(element,style){return styler.css.apply(styler,arguments)};return styler.css=function(element,styles){var keys=Object.keys(styles);return keys.forEach(function(key){key in element.style?element.style[key]=styles[key]:styler._prefix(key)in element.style?element.style[styler._prefix(key)]=styles[key]:console.warn("No such style property: "+key)}),element},styler._prefix=function(){var styles=window.getComputedStyle(document.documentElement,""),prefix=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return function(name){return prefix+name.substr(0,1).toUpperCase()+name.substr(1)}}(),styler.clear=function(element){styler._clear(element)},styler._clear=function(element){for(var len=element.style.length,style=element.style,keys=[],i=0;len>i;i++)keys.push(style[i]);keys.forEach(function(key){style[key]=""})},styler}(),function(ons){window.addEventListener("load",function(){return FastClick.attach(document.body)},!1),window.addEventListener("DOMContentLoaded",function(){ons._defaultDeviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(window.document.body,function(){navigator.app.exitApp()})},!1),ons.ready(function(){ons._setupLoadingPlaceHolders()}),(new Viewport).setup(),Modernizr.testStyles("#modernizr { -webkit-overflow-scrolling:touch }",function(elem,rule){Modernizr.addTest("overflowtouch",window.getComputedStyle&&"touch"==window.getComputedStyle(elem).getPropertyValue("-webkit-overflow-scrolling"))}),"function"!=typeof HTMLElement?(ons._BaseElement=function(){},ons._BaseElement.prototype=document.createElement("div")):ons._BaseElement=HTMLElement,"undefined"!=typeof module&&module.exports&&(module.exports=ons)}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var TemplateElement=function(_ons$_BaseElement){function TemplateElement(){_classCallCheck(this,TemplateElement),_get(Object.getPrototypeOf(TemplateElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TemplateElement,_ons$_BaseElement),_createClass(TemplateElement,[{key:"createdCallback",value:function(){for(this.template=this.innerHTML;this.firstChild;)this.removeChild(this.firstChild)}},{key:"attachedCallback",value:function(){var event=new CustomEvent("_templateloaded",{bubbles:!0,cancelable:!0});event.template=this.template,event.templateId=this.getAttribute("id"),this.dispatchEvent(event)}}]),TemplateElement}(ons._BaseElement);window.OnsTemplateElement||(window.OnsTemplateElement=document.registerElement("ons-template",{prototype:TemplateElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x11,_x12,_x13){for(var _again=!0;_again;){var object=_x11,property=_x12,receiver=_x13;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x11=parent,_x12=property,_x13=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,SplitterElement=function(_ons$_BaseElement){function SplitterElement(){_classCallCheck(this,SplitterElement),_get(Object.getPrototypeOf(SplitterElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterElement,_ons$_BaseElement),_createClass(SplitterElement,[{key:"createdCallback",value:function(){this._boundOnDeviceBackButton=this._onDeviceBackButton.bind(this),this._boundOnModeChange=this._onModeChange.bind(this)}},{key:"_onModeChange",value:function(event){event.target.parentElement===this&&this._layout()}},{key:"_getSideElement",value:function(side){var result=util.findChild(this,function(element){return"ons-splitter-side"===element.nodeName.toLowerCase()&&element.getAttribute("side")===side});return result&&CustomElements.upgrade(result),result}},{key:"_layout",value:function(){var content=this._getContentElement(),left=this._getSideElement("left"),right=this._getSideElement("right");content&&(left&&left.getCurrentMode&&"split"===left.getCurrentMode()?content.style.left=left._getWidth():content.style.left="0px",right&&right.getCurrentMode&&"split"===right.getCurrentMode()?content.style.right=right._getWidth():content.style.right="0px")}},{key:"_getContentElement",value:function(){return util.findChild(this,"ons-splitter-content")}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"openRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._open("right",options)}},{key:"_getMaskElement",value:function(){var mask=util.findChild(this,"ons-splitter-mask");return mask||this.appendChild(document.createElement("ons-splitter-mask"))}},{key:"openLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._open("left",options)}},{key:"_open",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.open(options):!1}},{key:"closeRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._close("right",options)}},{key:"closeLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._close("left",options)}},{key:"_close",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.close(options):!1}},{key:"toggleLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._toggle("left",options)}},{key:"toggleRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._toggle("right",options)}},{key:"_toggle",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.toggle(options):!1}},{key:"leftIsOpened",value:function(){return this._isOpened("left")}},{key:"rightIsOpened",value:function(){return this._isOpened("right")}},{key:"_isOpened",value:function(side){var menu=this._getSideElement(side);return menu?menu.isOpened():!1}},{key:"loadContentPage",value:function(page){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],content=this._getContentElement();if(content)return content.load(page,options);throw new Error('child "ons-splitter-content" element is not found in this element.')}},{key:"_onDeviceBackButton",value:function(handler){var left=this._getSideElement("left"),right=this._getSideElement("right");return left.isOpened()?void left.close():right.isOpened()?void right.close():void handler.callParentHandler()}},{key:"attachedCallback",value:function(){var _this=this;this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._boundOnDeviceBackButton),this._assertChildren(),this.addEventListener("modechange",this._boundOnModeChange,!1),setImmediate(function(){return _this._layout()})}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"_assertChildren",value:function(){var names=["ons-splitter-content","ons-splitter-side","ons-splitter-mask"],contentCount=0,sideCount=0,maskCount=0;if(util.arrayFrom(this.children).forEach(function(element){var name=element.nodeName.toLowerCase();if(-1===names.indexOf(name))throw new Error('"'+name+'" element is not allowed in "ons-splitter" element.');"ons-splitter-content"===name?contentCount++:"ons-splitter-content"===name?sideCount++:"ons-splitter-mask"===name&&maskCount++}),contentCount>1)throw new Error("too many <ons-splitter-content> elements.");if(sideCount>2)throw new Error("too many <ons-splitter-side> elements.");if(maskCount>1)throw new Error("too many <ons-splitter-mask> elements.");0===maskCount&&this.appendChild(document.createElement("ons-splitter-mask"))}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this.removeEventListener("modechange",this._boundOnModeChange,!1)}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}}]),SplitterElement}(ons._BaseElement);window.OnsSplitterElement||(window.OnsSplitterElement=document.registerElement("ons-splitter",{prototype:SplitterElement.prototype}),window.OnsSplitterElement._animatorDict={"default":ons._internal.OverlaySplitterAnimator,overlay:ons._internal.OverlaySplitterAnimator},window.OnsSplitterElement.registerAnimator=function(name,Animator){if(!(Animator instanceof ons._internal.SplitterAnimator))throw new Error("Animator parameter must be an instance of SplitterAnimator.");window.OnsSplitterElement._animatorDict[name]=Animator},window.OnsSplitterElement.SplitterAnimator=ons._internal.SplitterAnimator)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0), Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"tab-bar--*__item",".tab-bar__button":"tab-bar--*__button",".tab-bar__icon":"tab-bar--*__icon",".tab-bar__label":"tab-bar--*__label"},ModifierUtil=ons._internal.ModifierUtil,util=ons._util,templateSource=util.createElement('\n <div>\n <input type="radio" style="display: none">\n <button class="tab-bar__button tab-bar-inner"></button>\n </div>\n '),defaultInnerTemplateSource=util.createElement('\n <div>\n <div class="tab-bar__icon">\n <ons-icon icon="ion-cloud"></ons-icon>\n </div>\n <div class="tab-bar__label">label</div>\n </div>\n '),TabElement=function(_ons$_BaseElement){function TabElement(){_classCallCheck(this,TabElement),_get(Object.getPrototypeOf(TabElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabElement,_ons$_BaseElement),_createClass(TabElement,[{key:"createdCallback",value:function(){this._compile(),this._boundOnClick=this._onClick.bind(this),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){for(var fragment=document.createDocumentFragment(),hasChildren=!1;this.childNodes[0];){var node=this.childNodes[0];this.removeChild(node),fragment.appendChild(node),node.nodeType==Node.ELEMENT_NODE&&(hasChildren=!0)}for(var template=templateSource.cloneNode(!0);template.children[0];)this.appendChild(template.children[0]);this.classList.add("tab-bar__item");var button=util.findChild(this,".tab-bar__button");hasChildren?(button.appendChild(fragment),this._hasDefaultTemplate=!1):(this._hasDefaultTemplate=!0,this._updateDefaultTemplate())}},{key:"_updateDefaultTemplate",value:function(){function getLabelElement(){return self.querySelector(".tab-bar__label")}function getIconElement(){return self.querySelector("ons-icon")}if(this._hasDefaultTemplate){for(var button=util.findChild(this,".tab-bar__button"),template=defaultInnerTemplateSource.cloneNode(!0);template.children[0];)button.appendChild(template.children[0]);var self=this,icon=this.getAttribute("icon"),label=this.getAttribute("label");if("string"==typeof icon)getIconElement().setAttribute("icon",icon);else{var wrapper=button.querySelector(".tab-bar__icon");wrapper.parentNode.removeChild(wrapper)}"string"==typeof label?getLabelElement().textContent=label:getLabelElement().parentNode.removeChild(getLabelElement())}}},{key:"_onClick",value:function(){var tabbar=this._findTabbarElement();tabbar&&tabbar.setActiveTab(this._findTabIndex())}},{key:"isPersistent",value:function(){return this.hasAttribute("persistent")}},{key:"setActive",value:function(){var radio=util.findChild(this,"input");radio.checked=!0,this.classList.add("active"),util.arrayFrom(this.querySelectorAll("[ons-tab-inactive]")).forEach(function(element){return element.style.display="none"}),util.arrayFrom(this.querySelectorAll("[ons-tab-active]")).forEach(function(element){return element.style.display="inherit"})}},{key:"setInactive",value:function(){var radio=util.findChild(this,"input");radio.checked=!1,this.classList.remove("active"),util.arrayFrom(this.querySelectorAll("[ons-tab-inactive]")).forEach(function(element){return element.style.display="inherit"}),util.arrayFrom(this.querySelectorAll("[ons-tab-active]")).forEach(function(element){return element.style.display="none"})}},{key:"isLoaded",value:function(){return!1}},{key:"_loadPageElement",value:function(callback,link){var _this=this;this.isPersistent()?this._pageElement?callback(this._pageElement):this._createPageElement(this.getAttribute("page"),function(element){link(element,function(element){_this._pageElement=element,callback(element)})}):(this._pageElement=null,this._createPageElement(this.getAttribute("page"),callback))}},{key:"_createPageElement",value:function(page,callback){ons._internal.getPageHTMLAsync(page).then(function(html){callback(util.createElement(html.trim()))})}},{key:"isActive",value:function(){return this.classList.contains("active")}},{key:"canReload",value:function(){return!this.hasAttribute("no-reload")}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"attachedCallback",value:function(){var _this2=this;this._ensureElementPosition();var tabbar=this._findTabbarElement();if(tabbar.hasAttribute("modifier")){var prefix=this.hasAttribute("modifier")?this.getAttribute("modifier")+" ":"";this.setAttribute("modifier",prefix+tabbar.getAttribute("modifier"))}this.hasAttribute("active")&&!function(){var tabIndex=_this2._findTabIndex();window.OnsTabbarElement.rewritables.ready(tabbar,function(){setImmediate(function(){return tabbar.setActiveTab(tabIndex,{animation:"none"})})})}(),this.addEventListener("click",this._boundOnClick,!1)}},{key:"_findTabbarElement",value:function(){return this.parentNode&&"ons-tabbar"===this.parentNode.nodeName.toLowerCase()?this.parentNode:this.parentNode.parentNode&&"ons-tabbar"===this.parentNode.parentNode.nodeName.toLowerCase()?this.parentNode.parentNode:null}},{key:"_findTabIndex",value:function(){for(var elements=this.parentNode.children,i=0;i<elements.length;i++)if(this===elements[i])return i}},{key:"_ensureElementPosition",value:function(){if(!this._findTabbarElement())throw new Error("This ons-tab element is must be child of ons-tabbar element.")}},{key:"attributeChangedCallback",value:function(name,last,current){return this._hasDefaultTemplate&&("icon"===name||"label"===name)&&this._updateDefaultTemplate(),"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),TabElement}(ons._BaseElement);window.OnsTabElement||(window.OnsTabElement=document.registerElement("ons-tab",{prototype:TabElement.prototype}),document.registerElement("ons-tabbar-item",{prototype:Object.create(TabElement.prototype)}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={"":"alert-dialog--*",".alert-dialog-title":"alert-dialog-title--*",".alert-dialog-content":"alert-dialog-content--*",".alert-dialog-footer":"alert-dialog-footer--*",".alert-dialog-button":"alert-dialog-button--*",".alert-dialog-footer--one":"alert-dialog-footer--one--*",".alert-dialog-button--one":"alert-dialog-button--one--*",".alert-dialog-button--primal":"alert-dialog-button--primal--*"},AnimatorFactory=ons._internal.AnimatorFactory,AndroidAlertDialogAnimator=ons._internal.AndroidAlertDialogAnimator,IOSAlertDialogAnimator=ons._internal.IOSAlertDialogAnimator,SlideDialogAnimator=ons._internal.SlideDialogAnimator,AlertDialogAnimator=ons._internal.AlertDialogAnimator,_animatorDict={"default":ons.platform.isAndroid()?AndroidAlertDialogAnimator:IOSAlertDialogAnimator,fade:ons.platform.isAndroid()?AndroidAlertDialogAnimator:IOSAlertDialogAnimator,slide:SlideDialogAnimator,none:AlertDialogAnimator},AlertDialogElement=function(_ons$_BaseElement){function AlertDialogElement(){_classCallCheck(this,AlertDialogElement),_get(Object.getPrototypeOf(AlertDialogElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(AlertDialogElement,_ons$_BaseElement),_createClass(AlertDialogElement,[{key:"createdCallback",value:function(){this._compile(),this._mask=this._createMask(this.getAttribute("mask-color")),ModifierUtil.initModifier(this,scheme),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:AlertDialogAnimator,baseClassName:"AlertDialogAnimator",defaultAnimation:this.getAttribute("animation")}),this._visible=!1,this._doorLock=new DoorLock,this._boundCancel=this._cancel.bind(this)}},{key:"_compile",value:function(){this.style.display="none",this.style.zIndex="20001",this.classList.add("alert-dialog")}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"show",value:function(){var _this=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel2=!1,callback=options.callback||function(){};options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),util.triggerElementEvent(this,"preshow",{alertDialog:this,cancel:function(){_cancel2=!0}}),_cancel2||this._doorLock.waitUnlock(function(){var unlock=_this._doorLock.lock();_this._mask.style.display="block",_this._mask.style.opacity=1,_this.style.display="block";var animator=_this._animatorFactory.newAnimator(options);animator.show(_this,function(){_this._visible=!0,unlock(),util.triggerElementEvent(_this,"postshow",{alertDialog:_this}),callback()})})}},{key:"hide",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel3=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"prehide",{alertDialog:this,cancel:function(){_cancel3=!0}}),_cancel3||this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock(),animator=_this2._animatorFactory.newAnimator(options);animator.hide(_this2,function(){_this2.style.display="none",_this2._mask.style.display="none",_this2._visible=!1,unlock(),util.triggerElementEvent(_this2,"posthide",{alertDialog:_this2}),callback()})})}},{key:"isShown",value:function(){return this._visible}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this),this._mask.parentElement&&this._mask.parentElement.removeChild(this._mask)}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_cancel",value:function(){var _this3=this;this.isCancelable()&&this.hide({callback:function(){util.triggerElementEvent(_this3,"cancel")}})}},{key:"_createMask",value:function(color){return this._mask=util.createElement("<div></div>"),this._mask.classList.add("alert-dialog-mask"),this._mask.style.zIndex=2e4,this._mask.style.display="none",color&&(this._mask.style.backgroundColor=color),document.body.appendChild(this._mask),this._mask}},{key:"attachedCallback",value:function(){this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._mask.addEventListener("click",this._boundCancel,!1)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._mask.removeEventListener("click",this._boundCancel.bind(this),!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"_titleElement",get:function(){return util.findChild(this,".alert-dialog-title")}},{key:"_contentElement",get:function(){return util.findChild(this,".alert-dialog-content")}},{key:"_dialog",get:function(){return this}}]),AlertDialogElement}(ons._BaseElement);window.OnsAlertDialogElement||(window.OnsAlertDialogElement=document.registerElement("ons-alert-dialog",{prototype:AlertDialogElement.prototype}),window.OnsAlertDialogElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof AlertDialogAnimator))throw new Error('"Animator" param must inherit DialogAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,iOSTemplateElement=util.createElement('\n <span\n class="toolbar-button--quiet"\n style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n\n <i class="ion-ios-arrow-back ons-back-button__icon"\n style="\n vertical-align: top;\n background-color: transparent;\n height: 44px;\n line-height: 44px;\n font-size: 36px;\n margin-left: 8px;\n margin-right: 2px;\n width: 16px;\n display: inline-block;\n padding-top: 1px;"></i>\n\n <span\n style="vertical-align: top; display: inline-block; line-height: 44px; height: 44px;"\n class="back-button__label"></span>\n </span>\n '),MaterialTemplateElement=util.createElement('\n <span class="toolbar-button toolbar-button--material">\n <i class="zmdi zmdi-arrow-left"></i>\n\n <span class="back-button__label"></span>\n </span>\n '),scheme={".toolbar-button--quiet":"toolbar-button--*"},BackButtonElement=function(_ons$_BaseElement){function BackButtonElement(){_classCallCheck(this,BackButtonElement),_get(Object.getPrototypeOf(BackButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(BackButtonElement,_ons$_BaseElement),_createClass(BackButtonElement,[{key:"createdCallback",value:function(){this._compile(),this._boundOnClick=this._onClick.bind(this),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){var toolbar=ons._util.findParent(this,"ons-toolbar"),template=void 0;template=toolbar&&ons._util.hasModifier(toolbar,"material")?MaterialTemplateElement.cloneNode(!0):iOSTemplateElement.cloneNode(!0);for(var inner=template.querySelector(".back-button__label");this.childNodes[0];)inner.appendChild(this.childNodes[0]);this.appendChild(template)}},{key:"_onClick",value:function(){var navigator=util.findParent(this,"ons-navigator");navigator&&navigator.popPage({cancelIfRunning:!0})}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}}]),BackButtonElement}(ons._BaseElement);window.OnsBackButtonElement||(window.OnsBackButtonElement=document.registerElement("ons-back-button",{prototype:BackButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"bottom-bar--*"},ModifierUtil=ons._internal.ModifierUtil,BottomToolbarElement=function(_ons$_BaseElement){function BottomToolbarElement(){_classCallCheck(this,BottomToolbarElement),_get(Object.getPrototypeOf(BottomToolbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(BottomToolbarElement,_ons$_BaseElement),_createClass(BottomToolbarElement,[{key:"createdCallback",value:function(){this.classList.add("bottom-bar"),this.style.zIndex="0",this._update(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){if("inline"===name)this._update();else if("modifier"===name)return ModifierUtil.onModifierChanged(last,current,this,scheme)}},{key:"_update",value:function(){var inline="string"==typeof this.getAttribute("inline");this.style.position=inline?"static":"absolute"}}]),BottomToolbarElement}(ons._BaseElement);window.OnsBottomToolbarElement||(window.OnsBottomToolbarElement=document.registerElement("ons-bottom-toolbar",{prototype:BottomToolbarElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"button--*"},ModifierUtil=ons._internal.ModifierUtil,ButtonElement=function(_ons$_BaseElement){function ButtonElement(){_classCallCheck(this,ButtonElement),_get(Object.getPrototypeOf(ButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ButtonElement,_ons$_BaseElement),_createClass(ButtonElement,[{key:"createdCallback",value:function(){this.classList.add("button"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ButtonElement}(ons._BaseElement);window.OnsButtonElement||(window.OnsButtonElement=document.registerElement("ons-button",{prototype:ButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ModifierUtil=ons._internal.ModifierUtil,scheme={"":"carousel-item--*"},CarouselItemElement=function(_ons$_BaseElement){function CarouselItemElement(){_classCallCheck(this,CarouselItemElement),_get(Object.getPrototypeOf(CarouselItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(CarouselItemElement,_ons$_BaseElement),_createClass(CarouselItemElement,[{key:"createdCallback",value:function(){this.style.width="100%",ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),CarouselItemElement}(ons._BaseElement);window.OnsCarouselItemElement||(window.OnsCarouselItemElement=document.registerElement("ons-carousel-item",{prototype:CarouselItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ModifierUtil=ons._internal.ModifierUtil,util=ons._util,scheme={"":"carousel--*"},VerticalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaY},_getScrollVelocity:function(event){return event.gesture.velocityY},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this.getBoundingClientRect().height),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d(0px, "+-scroll+"px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),computedStyle=window.getComputedStyle(this),totalWidth=this.getBoundingClientRect().width||0,finalWidth=totalWidth-parseInt(computedStyle.paddingLeft,10)-parseInt(computedStyle.paddingRight,10),i=0;i<children.length;i++)children[i].style.position="absolute",children[i].style.height=sizeAttr,children[i].style.width=finalWidth+"px",children[i].style.visibility="visible",children[i].style.top=i*sizeInfo.number+sizeInfo.unit}},HorizontalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaX},_getScrollVelocity:function(event){return event.gesture.velocityX},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this.getBoundingClientRect().width),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d("+-scroll+"px, 0px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),computedStyle=window.getComputedStyle(this),totalHeight=this.getBoundingClientRect().height||0,finalHeight=totalHeight-parseInt(computedStyle.paddingTop,10)-parseInt(computedStyle.paddingBottom,10),i=0;i<children.length;i++)children[i].style.position="absolute",children[i].style.height=finalHeight+"px",children[i].style.width=sizeAttr,children[i].style.visibility="visible",children[i].style.left=i*sizeInfo.number+sizeInfo.unit}},CarouselElement=function(_ons$_BaseElement){function CarouselElement(){_classCallCheck(this,CarouselElement),_get(Object.getPrototypeOf(CarouselElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(CarouselElement,_ons$_BaseElement),_createClass(CarouselElement,[{key:"createdCallback",value:function(){ModifierUtil.initModifier(this,scheme),this._doorLock=new DoorLock,this._scroll=0,this._lastActiveIndex=0,this._boundOnDrag=this._onDrag.bind(this),this._boundOnDragEnd=this._onDragEnd.bind(this),this._boundOnResize=this._onResize.bind(this),this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._setupInitialIndex(),this._saveLastState()}},{key:"_onResize",value:function(){this.refresh()}},{key:"_onDirectionChange",value:function(){this._isVertical()?(this.style.overflowX="auto",this.style.overflowY=""):(this.style.overflowX="",this.style.overflowY="auto"),this.refresh()}},{key:"_saveLastState",value:function(){this._lastState={elementSize:this._getCarouselItemSize(),carouselElementCount:this.getCarouselItemCount(),width:this._getCarouselItemSize()*this.getCarouselItemCount()}}},{key:"_getCarouselItemSize",value:function(){var sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),elementSize=this._getElementSize();if("%"===sizeInfo.unit)return Math.round(sizeInfo.number/100*elementSize);if("px"===sizeInfo.unit)return sizeInfo.number;throw new Error("Invalid state")}},{key:"_getInitialIndex",value:function(){var index=parseInt(this.getAttribute("initial-index"),10);return"number"!=typeof index||isNaN(index)?0:Math.max(Math.min(index,this.getCarouselItemCount()-1),0)}},{key:"_getCarouselItemSizeAttr",value:function(){var attrName="item-"+(this._isVertical()?"height":"width"),itemSizeAttr=(""+this.getAttribute(attrName)).trim();return itemSizeAttr.match(/^\d+(px|%)$/)?itemSizeAttr:"100%"}},{key:"_decomposeSizeString",value:function(size){var matches=size.match(/^(\d+)(px|%)/);return{number:parseInt(matches[1],10),unit:matches[2]}}},{key:"_setupInitialIndex",value:function(){this._scroll=this._getCarouselItemSize()*this._getInitialIndex(),this._lastActiveIndex=this._getInitialIndex(),this._scrollTo(this._scroll)}},{key:"setSwipeable",value:function(swipeable){swipeable?this.setAttribute("swipeable",""):this.removeAttribute("swipeable")}},{key:"isSwipeable",value:function(){return this.hasAttribute("swipeable")}},{key:"setAutoScrollRatio",value:function(ratio){if(0>ratio||ratio>1)throw new Error("Invalid ratio.");this.setAttribute("auto-scroll-ratio",ratio)}},{key:"getAutoScrollRatio",value:function(){var attr=this.getAttribute("auto-scroll-ratio");if(!attr)return.5;var scrollRatio=parseFloat(attr);if(0>scrollRatio||scrollRatio>1)throw new Error("Invalid ratio.");return isNaN(scrollRatio)?.5:scrollRatio}},{key:"setActiveCarouselItemIndex",value:function(index,options){options=options||{},index=Math.max(0,Math.min(index,this.getCarouselItemCount()-1));var scroll=this._getCarouselItemSize()*index,max=this._calculateMaxScroll();this._scroll=Math.max(0,Math.min(max,scroll)),this._scrollTo(this._scroll,{animate:"none"!==options.animation,callback:options.callback}),this._tryFirePostChangeEvent()}},{key:"getActiveCarouselItemIndex",value:function(){var scroll=this._scroll,count=this.getCarouselItemCount(),size=this._getCarouselItemSize();if(0>scroll)return 0;var i=void 0;for(i=0;count>i;i++)if(scroll>=size*i&&size*(i+1)>scroll)return i;return i}},{key:"next",value:function(options){return this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()+1,options)}},{key:"prev",value:function(options){return this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()-1,options)}},{key:"setAutoScrollEnabled",value:function(enabled){enabled?this.setAttribute("auto-scroll",""):this.removeAttribute("auto-scroll")}},{key:"isAutoScrollEnabled",value:function(){return this.hasAttribute("auto-scroll")}},{key:"setDisabled",value:function(disabled){disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setOverscrollable",value:function(scrollable){scrollable?this.setAttribute("overscrollable",""):this.removeAttribute("overscrollable")}},{key:"isOverscrollable",value:function(){return this.hasAttribute("overscrollable")}},{key:"_isEnabledChangeEvent",value:function(){var elementSize=this._getElementSize(),carouselItemSize=this._getCarouselItemSize();return this.isAutoScrollEnabled()&&elementSize===carouselItemSize}},{key:"_isVertical",value:function(){return"vertical"===this.getAttribute("direction")}},{key:"_prepareEventListeners",value:function(){this._gestureDetector=new ons.GestureDetector(this,{dragMinDistance:1}),this._gestureDetector.on("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._boundOnDrag),this._gestureDetector.on("dragend",this._boundOnDragEnd),window.addEventListener("resize",this._boundOnResize,!0)}},{key:"_removeEventListeners",value:function(){this._gestureDetector.off("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._boundOnDrag),this._gestureDetector.off("dragend",this._boundOnDragEnd),this._gestureDetector.dispose(),window.removeEventListener("resize",this._boundOnResize,!0)}},{key:"_tryFirePostChangeEvent",value:function(){var currentIndex=this.getActiveCarouselItemIndex();if(this._lastActiveIndex!==currentIndex){var lastActiveIndex=this._lastActiveIndex;this._lastActiveIndex=currentIndex,util.triggerElementEvent(this,"postchange",{carousel:this,activeIndex:currentIndex,lastActiveIndex:lastActiveIndex})}}},{key:"_onDrag",value:function(event){if(this.isSwipeable()){var direction=event.gesture.direction;if((!this._isVertical()||"left"!==direction&&"right"!==direction)&&(this._isVertical()||"up"!==direction&&"down"!==direction)){event.stopPropagation(),this._lastDragEvent=event;var scroll=this._scroll-this._getScrollDelta(event);this._scrollTo(scroll),event.gesture.preventDefault(),this._tryFirePostChangeEvent()}}}},{key:"_onDragEnd",value:function(event){var _this=this;if(this._currentElementSize=void 0,this.isSwipeable()){if(this._scroll=this._scroll-this._getScrollDelta(event),0!==this._getScrollDelta(event)&&event.stopPropagation(),this._isOverScroll(this._scroll)){var waitForAction=!1;util.triggerElementEvent(this,"overscroll",{carousel:this,activeIndex:this.getActiveCarouselItemIndex(),direction:this._getOverScrollDirection(),waitToReturn:function(promise){waitForAction=!0,promise.then(function(){ return _this._scrollToKillOverScroll()})}}),waitForAction||this._scrollToKillOverScroll()}else this._startMomentumScroll();this._lastDragEvent=null,event.gesture.preventDefault()}}},{key:"_mixin",value:function(trait){Object.keys(trait).forEach(function(key){this[key]=trait[key]}.bind(this))}},{key:"_startMomentumScroll",value:function(){if(this._lastDragEvent){var velocity=this._getScrollVelocity(this._lastDragEvent),duration=.3,scrollDelta=100*duration*velocity,_scroll=this._normalizeScrollPosition(this._scroll+(this._getScrollDelta(this._lastDragEvent)>0?-scrollDelta:scrollDelta));this._scroll=_scroll,animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(this._scroll)},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play()}}},{key:"_normalizeScrollPosition",value:function(scroll){var _this2=this,max=this._calculateMaxScroll();if(!this.isAutoScrollEnabled())return Math.max(0,Math.min(max,scroll));var _ret=function(){for(var arr=[],size=_this2._getCarouselItemSize(),i=0;i<_this2.getCarouselItemCount();i++)max>=i*size&&arr.push(i*size);arr.push(max),arr.sort(function(left,right){return left=Math.abs(left-scroll),right=Math.abs(right-scroll),left-right}),arr=arr.filter(function(item,pos){return!pos||item!=arr[pos-1]});var lastScroll=_this2._lastActiveIndex*size,scrollRatio=Math.abs(scroll-lastScroll)/size;return scrollRatio<=_this2.getAutoScrollRatio()?{v:lastScroll}:scrollRatio>_this2.getAutoScrollRatio()&&1>scrollRatio&&arr[0]===lastScroll&&arr.length>1?{v:arr[1]}:{v:arr[0]}}();return"object"==typeof _ret?_ret.v:void 0}},{key:"_getCarouselItemElements",value:function(){return ons._util.arrayFrom(this.children).filter(function(child){return"ons-carousel-item"===child.nodeName.toLowerCase()})}},{key:"_scrollTo",value:function(scroll,options){var _this3=this;options=options||{};var isOverscrollable=this.isOverscrollable(),normalizeScroll=function(scroll){var ratio=.35;if(0>scroll)return isOverscrollable?Math.round(scroll*ratio):0;var maxScroll=_this3._calculateMaxScroll();return scroll>maxScroll?isOverscrollable?maxScroll+Math.round((scroll-maxScroll)*ratio):maxScroll:scroll};options.animate?animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(options.callback):animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))}).play(options.callback)}},{key:"_calculateMaxScroll",value:function(){var max=this.getCarouselItemCount()*this._getCarouselItemSize()-this._getElementSize();return Math.ceil(0>max?0:max)}},{key:"_isOverScroll",value:function(scroll){return 0>scroll||scroll>this._calculateMaxScroll()?!0:!1}},{key:"_getOverScrollDirection",value:function(){return this._isVertical()?this._scroll<=0?"up":"down":this._scroll<=0?"left":"right"}},{key:"_scrollToKillOverScroll",value:function(){var duration=.4;if(this._scroll<0)return animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(0)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=0);var maxScroll=this._calculateMaxScroll();return maxScroll<this._scroll?(animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(maxScroll)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=maxScroll)):void 0}},{key:"getCarouselItemCount",value:function(){return this._getCarouselItemElements().length}},{key:"refresh",value:function(){if(0!==this._getCarouselItemSize()){if(this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._lastState&&this._lastState.width>0){var _scroll2=this._scroll;this._isOverScroll(_scroll2)?this._scrollToKillOverScroll():(this.isAutoScrollEnabled()&&(_scroll2=this._normalizeScrollPosition(_scroll2)),this._scrollTo(_scroll2))}this._saveLastState(),util.triggerElementEvent(this,"refresh",{carousel:this})}}},{key:"first",value:function(){this.setActiveCarouselItemIndex(0)}},{key:"last",value:function(){this.setActiveCarouselItemIndex(Math.max(this.getCarouselItemCount()-1,0))}},{key:"attachedCallback",value:function(){this._prepareEventListeners(),this._layoutCarouselItems(),this._setupInitialIndex(),this._saveLastState()}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name&&this._onDirectionChange())}},{key:"detachedCallback",value:function(){this._removeEventListeners()}}]),CarouselElement}(ons._BaseElement);window.OnsCarouselElement||(window.OnsCarouselElement=document.registerElement("ons-carousel",{prototype:CarouselElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var ColumnElement=function(_ons$_BaseElement){function ColumnElement(){_classCallCheck(this,ColumnElement),_get(Object.getPrototypeOf(ColumnElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ColumnElement,_ons$_BaseElement),_createClass(ColumnElement,[{key:"createdCallback",value:function(){this.getAttribute("width")&&this._updateWidth()}},{key:"attributeChangedCallback",value:function(name,last,current){"width"===name&&this._updateWidth()}},{key:"_updateWidth",value:function(){var width=this.getAttribute("width");"string"==typeof width&&(width=(""+width).trim(),width=width.match(/^\d+$/)?width+"%":width,this.style.webkitBoxFlex="0",this.style.webkitFlex="0 0 "+width,this.style.mozBoxFlex="0",this.style.mozFlex="0 0 "+width,this.style.msFlex="0 0 "+width,this.style.flex="0 0 "+width,this.style.maxWidth=width)}}]),ColumnElement}(ons._BaseElement);window.OnsColElement||(window.OnsColElement=document.registerElement("ons-col",{prototype:ColumnElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".dialog":"dialog--*"},AnimatorFactory=ons._internal.AnimatorFactory,AndroidDialogAnimator=ons._internal.AndroidDialogAnimator,IOSDialogAnimator=ons._internal.IOSDialogAnimator,SlideDialogAnimator=ons._internal.SlideDialogAnimator,DialogAnimator=ons._internal.DialogAnimator,templateSource=util.createElement('\n <div>\n <div class="dialog-mask"></div>\n <div class="dialog"></div>\n </div>\n '),_animatorDict={"default":ons.platform.isAndroid()?AndroidDialogAnimator:IOSDialogAnimator,fade:ons.platform.isAndroid()?AndroidDialogAnimator:IOSDialogAnimator,slide:SlideDialogAnimator,none:DialogAnimator},DialogElement=function(_ons$_BaseElement){function DialogElement(){_classCallCheck(this,DialogElement),_get(Object.getPrototypeOf(DialogElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(DialogElement,_ons$_BaseElement),_createClass(DialogElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._visible=!1,this._doorLock=new DoorLock,this._boundCancel=this._cancel.bind(this),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:DialogAnimator,baseClassName:"DialogAnimator",defaultAnimation:this.getAttribute("animation")})}},{key:"_compile",value:function(){var style=this.getAttribute("style");this.style.display="none";var template=templateSource.cloneNode(!0),dialog=template.children[1];for(style&&dialog.setAttribute("style",style);this.firstChild;)dialog.appendChild(this.firstChild);for(;template.firstChild;)this.appendChild(template.firstChild);this._dialog.style.zIndex=20001,this._mask.style.zIndex=2e4,this.setAttribute("no-status-bar-fill","")}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_cancel",value:function(){var _this=this;this.isCancelable()&&this.hide({callback:function(){util.triggerElementEvent(_this,"cancel")}})}},{key:"show",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel2=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"preshow",{dialog:this,cancel:function(){_cancel2=!0}}),options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),_cancel2||this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock();_this2.style.display="block",_this2._mask.style.opacity="1";var animator=_this2._animatorFactory.newAnimator(options);animator.show(_this2,function(){_this2._visible=!0,unlock(),util.triggerElementEvent(_this2,"postshow",{dialog:_this2}),callback()})})}},{key:"hide",value:function(){var _this3=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel3=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"prehide",{dialog:this,cancel:function(){_cancel3=!0}}),options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),_cancel3||this._doorLock.waitUnlock(function(){var unlock=_this3._doorLock.lock(),animator=_this3._animatorFactory.newAnimator(options);animator.hide(_this3,function(){_this3.style.display="none",_this3._visible=!1,unlock(),util.triggerElementEvent(_this3,"posthide",{dialog:_this3}),callback()})})}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this)}},{key:"isShown",value:function(){return this._visible}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"attachedCallback",value:function(){this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._mask.addEventListener("click",this._boundCancel,!1)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._mask.removeEventListener("click",this._boundCancel.bind(this),!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"_mask",get:function(){return util.findChild(this,".dialog-mask")}},{key:"_dialog",get:function(){return util.findChild(this,".dialog")}}]),DialogElement}(ons._BaseElement);window.OnsDialogElement||(window.OnsDialogElement=document.registerElement("ons-dialog",{prototype:DialogElement.prototype}),window.OnsDialogElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof DialogAnimator))throw new Error('"Animator" param must inherit DialogAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"fab--*"},ModifierUtil=ons._internal.ModifierUtil,FabElement=function(_ons$_BaseElement){function FabElement(){_classCallCheck(this,FabElement),_get(Object.getPrototypeOf(FabElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(FabElement,_ons$_BaseElement),_createClass(FabElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this.classList.add("fab"),this._updatePosition(),this.show()}},{key:"_compile",value:function(){var content=document.createElement("span");content.classList.add("fab__icon");ons._util.arrayFrom(this.childNodes).forEach(function(element){return content.appendChild(element)});this.insertBefore(content,this.firstChild)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("position"===name&&this._updatePosition())}},{key:"_show",value:function(){this.isInline()||this.show()}},{key:"_hide",value:function(){this.isInline()||this.hide()}},{key:"_updatePosition",value:function(){var position=this.getAttribute("position");switch(this.classList.remove("fab--top__left","fab--bottom__right","fab--bottom__left","fab--top__right","fab--top__center","fab--bottom__center"),position){case"top right":case"right top":this.classList.add("fab--top__right");break;case"top left":case"left top":this.classList.add("fab--top__left");break;case"bottom right":case"right bottom":this.classList.add("fab--bottom__right");break;case"bottom left":case"left bottom":this.classList.add("fab--bottom__left");break;case"center top":case"top center":this.classList.add("fab--top__center");break;case"center bottom":case"bottom center":this.classList.add("fab--bottom__center")}}},{key:"show",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.style.transform="scale(1)",this.style.webkitTransform="scale(1)"}},{key:"hide",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.style.transform="scale(0)",this.style.webkitTransform="scale(0)"}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"isInline",value:function(){return this.hasAttribute("inline")}},{key:"isShown",value:function(){return"scale(1)"===this.style.transform&&"none"!==this.style.display}},{key:"toggle",value:function(){this.isShown()?this.hide():this.show()}}]),FabElement}(ons._BaseElement);window.OnsFabElement||(window.OnsFabElement=document.registerElement("ons-fab",{prototype:FabElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var GestureDetectorElement=function(_ons$_BaseElement){function GestureDetectorElement(){_classCallCheck(this,GestureDetectorElement),_get(Object.getPrototypeOf(GestureDetectorElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(GestureDetectorElement,_ons$_BaseElement),_createClass(GestureDetectorElement,[{key:"createdCallback",value:function(){this._gestureDetector=new ons.GestureDetector(this)}}]),GestureDetectorElement}(ons._BaseElement);window.OnsGestureDetectorElement||(window.OnsGestureDetectorElement=document.registerElement("ons-gesture-detector",{prototype:GestureDetectorElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var IconElement=function(_ons$_BaseElement){function IconElement(){_classCallCheck(this,IconElement),_get(Object.getPrototypeOf(IconElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(IconElement,_ons$_BaseElement),_createClass(IconElement,[{key:"createdCallback",value:function(){this._update()}},{key:"attributeChangedCallback",value:function(name,last,current){-1!==["icon","size"].indexOf(name)&&this._update()}},{key:"_update",value:function(){var _this=this;this._cleanClassAttribute();var builded=this._buildClassAndStyle(this);for(var key in builded.style)builded.style.hasOwnProperty(key)&&(this.style[key]=builded.style[key]);builded.classList.forEach(function(className){return _this.classList.add(className)})}},{key:"_cleanClassAttribute",value:function(){var classList=this.classList;Array.apply(null,this.classList).filter(function(klass){return"fa"===klass||0===klass.indexOf("fa-")||0===klass.indexOf("ion-")||0===klass.indexOf("zmdi-")}).forEach(function(className){classList.remove(className)}),classList.remove("zmdi")}},{key:"_buildClassAndStyle",value:function(){var classList=["ons-icon"],style={},iconName=this._iconName;0===iconName.indexOf("ion-")?classList.push(iconName):0===iconName.indexOf("fa-")?(classList.push(iconName),classList.push("fa")):0===iconName.indexOf("md-")?(classList.push("zmdi"),classList.push("zmdi-"+iconName.split(/\-(.+)?/)[1])):(classList.push("fa"),classList.push("fa-"+iconName));var size=""+this.getAttribute("size");return size.match(/^[1-5]x|lg$/)?(classList.push("fa-"+size),this.style.removeProperty("font-size")):style.fontSize=size,{classList:classList,style:style}}},{key:"_iconName",get:function(){return""+this.getAttribute("icon")}}]),IconElement}(ons._BaseElement);window.OnsIconElement||(window.OnsIconElement=document.registerElement("ons-icon",{prototype:IconElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list__header--*"},ModifierUtil=ons._internal.ModifierUtil,ListHeaderElement=function(_ons$_BaseElement){function ListHeaderElement(){_classCallCheck(this,ListHeaderElement),_get(Object.getPrototypeOf(ListHeaderElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListHeaderElement,_ons$_BaseElement),_createClass(ListHeaderElement,[{key:"createdCallback",value:function(){this.classList.add("list__header"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ListHeaderElement}(ons._BaseElement);window.OnsListHeaderElement||(window.OnsListHeaderElement=document.registerElement("ons-list-header",{prototype:ListHeaderElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list__item--*"},ModifierUtil=ons._internal.ModifierUtil,ListItemElement=function(_ons$_BaseElement){function ListItemElement(){_classCallCheck(this,ListItemElement),_get(Object.getPrototypeOf(ListItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListItemElement,_ons$_BaseElement),_createClass(ListItemElement,[{key:"createdCallback",value:function(){this.classList.add("list__item"),ModifierUtil.initModifier(this,scheme),this._gestureDetector=new ons.GestureDetector(this),this._boundOnDrag=this._onDrag.bind(this)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){this.addEventListener("drag",this._boundOnDrag)}},{key:"detachedCallback",value:function(){this.removeEventListener("drag",this._boundOnDrag)}},{key:"_onDrag",value:function(event){var g=event.gesture;this._shouldLockOnDrag()&&["left","right"].indexOf(g.direction)>-1&&g.preventDefault()}},{key:"_shouldLockOnDrag",value:function(){return this.hasAttribute("lock-on-drag")}}]),ListItemElement}(ons._BaseElement);window.OnsListItemElement||(window.OnsListItemElement=document.registerElement("ons-list-item",{prototype:ListItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"list--*"},ModifierUtil=ons._internal.ModifierUtil,ListElement=function(_ons$_BaseElement){function ListElement(){_classCallCheck(this,ListElement),_get(Object.getPrototypeOf(ListElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListElement,_ons$_BaseElement),_createClass(ListElement,[{key:"createdCallback",value:function(){this.classList.add("list"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ListElement}(ons._BaseElement);window.OnsListElement||(window.OnsListElement=document.registerElement("ons-list",{prototype:ListElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={".text-input--material":"text-input--material--*",".text-input--material__label":"text-input--material__label--*"},ModifierUtil=ons._internal.ModifierUtil,INPUT_ATTRIBUTES=["autocapitalize","autocomplete","autocorrect","autofocus","disabled","inputmode","max","maxlength","min","minlength","name","pattern","placeholder","readonly","size","step","type","validator","value"],MaterialInputElement=function(_ons$_BaseElement){function MaterialInputElement(){_classCallCheck(this,MaterialInputElement),_get(Object.getPrototypeOf(MaterialInputElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(MaterialInputElement,_ons$_BaseElement),_createClass(MaterialInputElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._updateLabel(),this._updateLabelColor(),this._updateBoundAttributes(),this._updateLabelClass(),this._boundOnInput=this._onInput.bind(this),this._boundOnFocusin=this._onFocusin.bind(this),this._boundOnFocusout=this._onFocusout.bind(this),this._boundDelegateEvent=this._delegateEvent.bind(this)}},{key:"_compile",value:function(){this._input||(this.appendChild(document.createElement("input")),this._input.classList.add("text-input--material"),this.appendChild(document.createElement("span")),this._label.classList.add("text-input--material__label"))}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):"label"===name?this._updateLabel():INPUT_ATTRIBUTES.indexOf(name)>=0?this._updateBoundAttributes():void 0}},{key:"attachedCallback",value:function(){this._input.addEventListener("input",this._boundOnInput),this._input.addEventListener("focusin",this._boundOnFocusin),this._input.addEventListener("focusout",this._boundOnFocusout),this._input.addEventListener("focus",this._boundDelegateEvent),this._input.addEventListener("blur",this._boundDelegateEvent)}},{key:"detachedCallback",value:function(){this._input.removeEventListener("input",this._boundOnInput),this._input.removeEventListener("focusin",this._boundOnFocusin),this._input.removeEventListener("focusout",this._boundOnFocusout),this._input.addEventListener("focus",this._boundDelegateEvent),this._input.addEventListener("blur",this._boundDelegateEvent)}},{key:"_setLabel",value:function(value){"undefined"!=typeof this._label.textContent?this._label.textContent=value:this._label.innerText=value}},{key:"_updateLabel",value:function(){this._setLabel(this.hasAttribute("label")?this.getAttribute("label"):"")}},{key:"_updateBoundAttributes",value:function(){var _this=this;INPUT_ATTRIBUTES.forEach(function(attr){_this.hasAttribute(attr)?_this._input.setAttribute(attr,_this.getAttribute(attr)):_this._input.removeAttribute(attr)})}},{key:"_updateLabelColor",value:function(){this.value.length>0&&this._input===document.activeElement?this._label.style.color="":this._label.style.color="rgba(0, 0, 0, 0.5)"}},{key:"_updateLabelClass",value:function(){""===this.value?this._label.classList.remove("text-input--material__label--active"):this._label.classList.add("text-input--material__label--active")}},{key:"_delegateEvent",value:function(event){var e=new CustomEvent(event.type,{bubbles:!1,cancelable:!0});return this.dispatchEvent(e)}},{key:"_onInput",value:function(event){this._updateLabelClass(),this._updateLabelColor()}},{key:"_onFocusin",value:function(event){this._updateLabelClass(),this._updateLabelColor()}},{key:"_onFocusout",value:function(event){this._updateLabelColor()}},{key:"_input",get:function(){return this.querySelector("input")}},{key:"_label", get:function(){return this.querySelector("span")}},{key:"value",get:function(){return this._input.value},set:function(val){return this._input.value=val,this._onInput(),this._input.val}}]),MaterialInputElement}(ons._BaseElement);window.OnsMaterialInputElement||(window.OnsMaterialInputElement=document.registerElement("ons-material-input",{prototype:MaterialInputElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"modal--*",modal__content:"modal--*__content"},AnimatorFactory=ons._internal.AnimatorFactory,ModalAnimator=ons._internal.ModalAnimator,FadeModalAnimator=ons._internal.FadeModalAnimator,ModifierUtil=ons._internal.ModifierUtil,util=ons._util,_animatorDict={"default":ModalAnimator,fade:FadeModalAnimator,none:ModalAnimator},ModalElement=function(_ons$_BaseElement){function ModalElement(){_classCallCheck(this,ModalElement),_get(Object.getPrototypeOf(ModalElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ModalElement,_ons$_BaseElement),_createClass(ModalElement,[{key:"createdCallback",value:function(){this._doorLock=new DoorLock,this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:ModalAnimator,baseClassName:"ModalAnimator",defaultAnimation:this.getAttribute("animation")}),this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"setDeviceBackButtonHandler",value:function(callback){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,callback),this._onDeviceBackButton=callback}},{key:"_onDeviceBackButton",value:function(){}},{key:"_compile",value:function(){this.style.display="none",this.classList.add("modal");var wrapper=document.createElement("div");for(wrapper.classList.add("modal__content");this.childNodes[0];){var node=this.childNodes[0];this.removeChild(node),wrapper.insertBefore(node,null)}this.appendChild(wrapper)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy()}},{key:"attachedCallback",value:function(){setImmediate(this._ensureNodePosition.bind(this)),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this))}},{key:"_ensureNodePosition",value:function(){if(this.parentNode&&!this.hasAttribute("inline")&&"ons-page"!==this.parentNode.nodeName.toLowerCase()){for(var page=this;;){if(page=page.parentNode,!page)return;if("ons-page"===page.nodeName.toLowerCase())break}page._registerExtraElement(this)}}},{key:"isShown",value:function(){return"none"!==this.style.display}},{key:"show",value:function(){var _this=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var callback=options.callback||function(){};this._doorLock.waitUnlock(function(){var unlock=_this._doorLock.lock(),animator=_this._animatorFactory.newAnimator(options);_this.style.display="table",animator.show(_this,function(){unlock(),callback()})})}},{key:"toggle",value:function(){return this.isShown()?this.hide.apply(this,arguments):this.show.apply(this,arguments)}},{key:"hide",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var callback=options.callback||function(){};this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock(),animator=_this2._animatorFactory.newAnimator(options);animator.hide(_this2,function(){_this2.style.display="none",unlock(),callback()})})}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ModalElement}(ons._BaseElement);window.OnsModalElement||(window.OnsModalElement=document.registerElement("ons-modal",{prototype:ModalElement.prototype}),window.OnsModalElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof ModalAnimator))throw new Error('"Animator" param must inherit ModalAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var AnimatorFactory=ons._internal.AnimatorFactory,NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,IOSSlideNavigatorTransitionAnimator=ons._internal.IOSSlideNavigatorTransitionAnimator,SimpleSlideNavigatorTransitionAnimator=ons._internal.SimpleSlideNavigatorTransitionAnimator,LiftNavigatorTransitionAnimator=ons._internal.LiftNavigatorTransitionAnimator,FadeNavigatorTransitionAnimator=ons._internal.FadeNavigatorTransitionAnimator,NoneNavigatorTransitionAnimator=ons._internal.NoneNavigatorTransitionAnimator,util=ons._util,NavigatorPage=ons._internal.NavigatorPage,_animatorDict={"default":ons.platform.isAndroid()?SimpleSlideNavigatorTransitionAnimator:IOSSlideNavigatorTransitionAnimator,slide:ons.platform.isAndroid()?SimpleSlideNavigatorTransitionAnimator:IOSSlideNavigatorTransitionAnimator,simpleslide:SimpleSlideNavigatorTransitionAnimator,lift:LiftNavigatorTransitionAnimator,fade:FadeNavigatorTransitionAnimator,none:NoneNavigatorTransitionAnimator},rewritables={ready:function(navigatorElement,callback){callback()},link:function(navigatorElement,target,callback){callback(target)}},NavigatorElement=function(_ons$_BaseElement){function NavigatorElement(){_classCallCheck(this,NavigatorElement),_get(Object.getPrototypeOf(NavigatorElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(NavigatorElement,_ons$_BaseElement),_createClass(NavigatorElement,[{key:"createdCallback",value:function(){this._doorLock=new DoorLock,this._pages=[],this._boundOnDeviceBackButton=this._onDeviceBackButton.bind(this),this._isPushing=this._isPopping=!1,this._initialHTML=this.innerHTML,this.innerHTML="",this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:NavigatorTransitionAnimator,baseClassName:"NavigatorTransitionAnimator",defaultAnimation:this.getAttribute("animation")})}},{key:"canPopPage",value:function(){return this._pages.length>1}},{key:"replacePage",value:function(page,options){var _this=this;options=options||{};var onTransitionEnd=options.onTransitionEnd||function(){};return options.onTransitionEnd=function(){_this._pages.length>1&&_this._pages[_this._pages.length-2].destroy(),onTransitionEnd()},this.pushPage(page,options)}},{key:"popPage",value:function(options){var _this2=this;options=options||{},options.cancelIfRunning&&this._isPopping||(options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),this._doorLock.waitUnlock(function(){if(_this2._pages.length<=1)throw new Error("ons-navigator's page stack is empty.");if(!_this2._emitPrePopEvent()){var unlock=_this2._doorLock.lock();options.refresh?!function(){var index=_this2._pages.length-2;if(!_this2._pages[index].page)throw new Error("Refresh option cannot be used with pages directly inside the Navigator. Use ons-template instead.");ons._internal.getPageHTMLAsync(_this2._pages[index].page).then(function(templateHTML){var element=_this2._createPageElement(templateHTML),pageObject=_this2._createPageObject(_this2._pages[index].page,element,options);rewritables.link(_this2,element,function(element){_this2.insertBefore(element,_this2._pages[index]?_this2._pages[index].element:null),_this2._pages.splice(index,0,pageObject),_this2._pages[index+1].destroy(),_this2._popPage(options,unlock)})})}():_this2._popPage(options,unlock)}}))}},{key:"_popPage",value:function(options,unlock){var _this3=this;options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var leavePage=this._pages.pop(),enterPage=this._pages[this._pages.length-1];enterPage.updateBackButton(),leavePage.element._hide(),enterPage&&(enterPage.element.style.display="block",enterPage.element._show());var eventDetail={leavePage:leavePage,enterPage:this._pages[this._pages.length-1],navigator:this},callback=function(){leavePage.destroy(),_this3._isPopping=!1,unlock();var event=util.triggerElementEvent(_this3,"postpop",eventDetail);event.leavePage=null,"function"==typeof options.onTransitionEnd&&options.onTransitionEnd()};this._isPopping=!0;var animator=this._animatorFactory.newAnimator(options,leavePage.options.animator);animator.pop(enterPage,leavePage,callback)}},{key:"insertPage",value:function(index,page,options){var _this4=this;if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);return index=this._normalizeIndex(index),index>=this._pages.length?this.pushPage.apply(this,[].slice.call(arguments,1)):void this._doorLock.waitUnlock(function(){var unlock=_this4._doorLock.lock();ons._internal.getPageHTMLAsync(page).then(function(templateHTML){var element=_this4._createPageElement(templateHTML),pageObject=_this4._createPageObject(page,element,options);rewritables.link(_this4,element,function(element){element.style.display="none",_this4.insertBefore(element,_this4._pages[index].element),_this4._pages.splice(index,0,pageObject),_this4.getCurrentPage().updateBackButton(),setTimeout(function(){unlock(),element=null},1e3/60)})})})}},{key:"_normalizeIndex",value:function(index){return 0>index&&(index=Math.abs(this._pages.length+index)%this._pages.length),index}},{key:"getCurrentPage",value:function(){if(this._pages.length<=0)throw new Error("Invalid state");return this._pages[this._pages.length-1]}},{key:"_show",value:function(){this._pages[this._pages.length-1]&&this._pages[this._pages.length-1].element._show()}},{key:"_hide",value:function(){this._pages[this._pages.length-1]&&this._pages[this._pages.length-1].element._hide()}},{key:"_destroy",value:function(){for(var i=this._pages.length-1;i>=0;i--)this._pages[i].destroy();this.remove()}},{key:"_onDeviceBackButton",value:function(event){this._pages.length>1?this.popPage():event.callParentHandler()}},{key:"resetToPage",value:function(page,options){var _this5=this;options=options||{},options.animator||options.animation||(options.animation="none");var onTransitionEnd=options.onTransitionEnd||function(){};options.onTransitionEnd=function(){for(;_this5._pages.length>1;)_this5._pages.shift().destroy();_this5._pages[0].updateBackButton(),onTransitionEnd()},(void 0===page||""===page)&&(this.hasAttribute("page")?page=this.getAttribute("page"):(options.pageHTML=this._initialHTML,page="")),this.pushPage(page,options)}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"attachedCallback",value:function(){var _this6=this;this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._boundOnDeviceBackButton),rewritables.ready(this,function(){if(0===_this6._pages.length)if(_this6.getAttribute("page"))_this6.pushPage(_this6.getAttribute("page"),{animation:"none"});else{var element=_this6._createPageElement(_this6._initialHTML||"");_this6._pushPageDOM(_this6._createPageObject("",element,{}),function(){})}})}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null}},{key:"pushPage",value:function(page,options){var _this7=this;if(options=options||{},options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),!options.cancelIfRunning||!this._isPushing){if(options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);this._emitPrePushEvent()||this._doorLock.waitUnlock(function(){return _this7._pushPage(page,options)})}}},{key:"_pushPage",value:function(page,options){var _this8=this,unlock=this._doorLock.lock(),done=function(){unlock()},run=function(templateHTML){var element=_this8._createPageElement(templateHTML);_this8._pushPageDOM(_this8._createPageObject(page,element,options),done)};options.pageHTML?run(options.pageHTML):ons._internal.getPageHTMLAsync(page).then(run)}},{key:"_pushPageDOM",value:function(pageObject,unlock){var _this9=this;unlock=unlock||function(){};var element=pageObject.element,options=pageObject.options,eventDetail={enterPage:pageObject,leavePage:this._pages[this._pages.length-1],navigator:this};this._pages.push(pageObject),pageObject.updateBackButton();var done=function(){_this9._pages[_this9._pages.length-2]&&(_this9._pages[_this9._pages.length-2].element.style.display="none"),_this9._isPushing=!1,unlock(),util.triggerElementEvent(_this9,"postpush",eventDetail),"function"==typeof options.onTransitionEnd&&options.onTransitionEnd(),element=null};this._isPushing=!0,rewritables.link(this,element,function(element){CustomElements.upgrade(element),setTimeout(function(){if(_this9._pages.length>1){var leavePage=_this9._pages.slice(-2)[0],enterPage=_this9._pages.slice(-1)[0];_this9.appendChild(element),leavePage.element._hide(),enterPage.element._show(),options.animator.push(enterPage,leavePage,done)}else _this9.appendChild(element),element._show(),done()},1e3/60)})}},{key:"bringPageTop",value:function(item,options){var _this10=this;if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);if(!(options.cancelIfRunning&&this._isPushing||this._emitPrePushEvent())){var index=void 0,page=void 0;if("string"==typeof item)page=item,index=this._lastIndexOfPage(page);else{if("number"!=typeof item)throw new Error("First argument must be a page name or the index of an existing page. You supplied "+item);if(index=this._normalizeIndex(item),item>=this._pages.length)throw new Error("The provided index does not match an existing page.");page=this._pages[index].page}0>index?this._doorLock.waitUnlock(function(){return _this10._pushPage(page,options)}):index<this._pages.length-1&&this._doorLock.waitUnlock(function(){var unlock=_this10._doorLock.lock(),done=function(){unlock()},pageObject=_this10._pages.splice(index,1)[0];pageObject.element.style.display="block",pageObject.element.setAttribute("_skipinit",""),options.animator=_this10._animatorFactory.newAnimator(options),pageObject.options=options,_this10._pushPageDOM(pageObject,done)})}}},{key:"_lastIndexOfPage",value:function(page){var index=void 0;for(index=this._pages.length-1;index>=0&&this._pages[index].page!==page;index--);return index}},{key:"_emitPrePushEvent",value:function(){var isCanceled=!1;return util.triggerElementEvent(this,"prepush",{navigator:this,currentPage:this._pages.length>0?this.getCurrentPage():void 0,cancel:function(){isCanceled=!0}}),isCanceled}},{key:"_emitPrePopEvent",value:function(){var isCanceled=!1,leavePage=this.getCurrentPage();return util.triggerElementEvent(this,"prepop",{navigator:this,currentPage:leavePage,leavePage:leavePage,enterPage:this._pages[this._pages.length-2],cancel:function(){isCanceled=!0}}),isCanceled}},{key:"_createPageObject",value:function(page,element,options){return options.animator=this._animatorFactory.newAnimator(options),new NavigatorPage({page:page,element:element,options:options,navigator:this})}},{key:"_createPageElement",value:function(templateHTML){var pageElement=util.createElement(ons._internal.normalizePageHTML(templateHTML));if("ons-page"!==pageElement.nodeName.toLowerCase())throw new Error('You must supply an "ons-page" element to "ons-navigator".');return pageElement}},{key:"pages",get:function(){return this._pages.slice(0)}}]),NavigatorElement}(ons._BaseElement);window.OnsNavigatorElement||(window.OnsNavigatorElement=document.registerElement("ons-navigator",{prototype:NavigatorElement.prototype}),window.OnsNavigatorElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof NavigatorTransitionAnimator))throw new Error('"Animator" param must inherit NavigatorTransitionAnimator');_animatorDict[name]=Animator},window.OnsNavigatorElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"page--*",".page__content":"page--*__content",".page__background":"page--*__background"},ModifierUtil=ons._internal.ModifierUtil,nullToolbarElement=document.createElement("ons-toolbar"),util=ons._util,PageElement=function(_ons$_BaseElement){function PageElement(){_classCallCheck(this,PageElement),_get(Object.getPrototypeOf(PageElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PageElement,_ons$_BaseElement),_createClass(PageElement,[{key:"createdCallback",value:function(){this.classList.add("page"),this._compile(),ModifierUtil.initModifier(this,scheme),this._isShown=!1,this._isMuted=this.hasAttribute("_muted"),this._skipInit=this.hasAttribute("_skipinit"),this.eventDetail={page:this}}},{key:"attachedCallback",value:function(){this._isMuted||(this._skipInit?this.removeAttribute("_skipinit"):util.triggerElementEvent(this,"init",this.eventDetail)),util.hasAnyComponentAsParent(this)||this._show(),this._tryToFillStatusBar()}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler||null}},{key:"setDeviceBackButtonHandler",value:function(callback){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,callback)}},{key:"_getContentElement",value:function(){var result=ons._util.findChild(this,".page__content");if(result)return result;throw Error('fail to get ".page__content" element.')}},{key:"_hasToolbarElement",value:function(){return!!ons._util.findChild(this,"ons-toolbar")}},{key:"_canAnimateToolbar",value:function(){var toolbar=ons._util.findChild(this,"ons-toolbar");if(toolbar)return!0;for(var elements=this._getContentElement().children,i=0;i<elements.length;i++)if("ons-toolbar"===elements[i].nodeName.toLowerCase()&&!elements[i].hasAttribute("inline"))return!0;return!1}},{key:"_getBackgroundElement",value:function(){var result=ons._util.findChild(this,".page__background");if(result)return result;throw Error('fail to get ".page__background" element.')}},{key:"_getBottomToolbarElement",value:function(){return ons._util.findChild(this,"ons-bottom-toolbar")||ons._internal.nullElement}},{key:"_getToolbarElement",value:function(){return ons._util.findChild(this,"ons-toolbar")||nullToolbarElement}},{key:"_registerToolbar",value:function(element){this._getContentElement().setAttribute("no-status-bar-fill",""),ons._util.findChild(this,".page__status-bar-fill")?this.insertBefore(element,this.children[1]):this.insertBefore(element,this.children[0])}},{key:"_registerBottomToolbar",value:function(element){if(!ons._util.findChild(this,".page__status-bar-fill")){var fill=document.createElement("div");fill.classList.add("page__bottom-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0]),this.insertBefore(element,null)}}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("_muted"===name?this._isMuted=this.hasAttribute("_muted"):"_skipinit"===name&&(this._skipInit=this.hasAttribute("_skipinit")))}},{key:"_compile",value:function(){if(!ons._util.findChild(this,".page__background")||!ons._util.findChild(this,".page__content")){var background=document.createElement("div");background.classList.add("page__background");var content=document.createElement("div");for(content.classList.add("page__content");this.childNodes[0];)content.appendChild(this.childNodes[0]);this.hasAttribute("style")&&(background.setAttribute("style",this.getAttribute("style")),this.removeAttribute("style",null));var fragment=document.createDocumentFragment();fragment.appendChild(background),fragment.appendChild(content),this.appendChild(fragment)}}},{key:"_registerExtraElement",value:function(element){var extra=ons._util.findChild(this,".page__extra");extra||(extra=document.createElement("div"),extra.classList.add("page__extra"),extra.style.zIndex="10001",this.insertBefore(extra,null)),extra.insertBefore(element,null)}},{key:"_tryToFillStatusBar",value:function(){var _this=this;return ons._internal.shouldFillStatusBar(this).then(function(){var fill=_this.querySelector(".page__status-bar-fill");if(fill instanceof HTMLElement)return fill;fill=document.createElement("div"),fill.classList.add("page__status-bar-fill"),fill.style.width="0px",fill.style.height="0px";for(var bottomBarFill=void 0,i=0;i<_this.children.length;i++)if(_this.children[i].classList.contains("page__bottom-bar-fill")){bottomBarFill=_this.children[i];break}return bottomBarFill?_this.insertBefore(fill,bottomBarFill.nextSibling):_this.insertBefore(fill,_this.children[0]),fill})["catch"](function(){var el=_this.querySelector(".page__status-bar-fill");el instanceof HTMLElement&&el.remove()})}},{key:"_show",value:function(){!this.isShown&&ons._util.isAttached(this)&&(this.isShown=!0,this._isMuted||util.triggerElementEvent(this,"show",this.eventDetail),ons._util.propagateAction(this._getContentElement(),"_show"))}},{key:"_hide",value:function(){this.isShown&&(this.isShown=!1,this._isMuted||util.triggerElementEvent(this,"hide",this.eventDetail),ons._util.propagateAction(this._getContentElement(),"_hide"))}},{key:"_destroy",value:function(){this._hide(),this._isMuted||util.triggerElementEvent(this,"destroy",this.eventDetail),this.getDeviceBackButtonHandler()&&this.getDeviceBackButtonHandler().destroy(),ons._util.propagateAction(this._getContentElement(),"_destroy"),this.remove()}},{key:"isShown",get:function(){return this._isShown},set:function(value){this._isShown=value}}]),PageElement}(ons._BaseElement);window.OnsPageElement||(window.OnsPageElement=document.registerElement("ons-page",{prototype:PageElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".popover":"popover--*",".popover__content":"popover__content--*"},PopoverAnimator=ons._internal.PopoverAnimator,FadePopoverAnimator=ons._internal.FadePopoverAnimator,templateSource=util.createElement('\n <div>\n <div class="popover-mask"></div>\n <div class="popover">\n <div class="popover__content"></div>\n <div class="popover__arrow"></div>\n </div>\n </div>\n '),AnimatorFactory=ons._internal.AnimatorFactory,_animatorDict={fade:FadePopoverAnimator,none:PopoverAnimator},PopoverElement=function(_ons$_BaseElement){function PopoverElement(){_classCallCheck(this,PopoverElement),_get(Object.getPrototypeOf(PopoverElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PopoverElement,_ons$_BaseElement),_createClass(PopoverElement,[{key:"createdCallback",value:function(){this._compile(),this.style.display="none",ModifierUtil.initModifier(this,scheme),this._mask.style.zIndex="20000",this._popover.style.zIndex="20001",this.hasAttribute("mask-color")&&(this._mask.style.backgroundColor=this.getAttribute("mask-color")),this._visible=!1,this._doorLock=new DoorLock,this._boundOnChange=this._onChange.bind(this),this._boundCancel=this._cancel.bind(this),this._animatorFactory=this._createAnimatorFactory()}},{key:"_createAnimatorFactory",value:function(){return new AnimatorFactory({animators:_animatorDict,baseClass:PopoverAnimator,baseClassName:"PopoverAnimator",defaultAnimation:this.getAttribute("animation")||"fade"})}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_setDirection",value:function(direction){var arrowPosition=void 0;if("up"===direction)arrowPosition="bottom";else if("left"===direction)arrowPosition="right";else if("down"===direction)arrowPosition="top";else{if("right"!=direction)throw new Error("Invalid direction.");arrowPosition="left"}var popoverClassList=this._popover.classList;popoverClassList.remove("popover--up"),popoverClassList.remove("popover--down"),popoverClassList.remove("popover--left"),popoverClassList.remove("popover--right"),popoverClassList.add("popover--"+direction);var arrowClassList=this._arrow.classList;arrowClassList.remove("popover__top-arrow"),arrowClassList.remove("popover__bottom-arrow"),arrowClassList.remove("popover__left-arrow"),arrowClassList.remove("popover__right-arrow"),arrowClassList.add("popover__"+arrowPosition+"-arrow")}},{key:"_positionPopoverByDirection",value:function(target,direction){var el=this._popover,pos=target.getBoundingClientRect(),own=el.getBoundingClientRect(),arrow=el.children[1],offset=14,margin=6,radius=parseInt(window.getComputedStyle(el.querySelector(".popover__content")).borderRadius);arrow.style.top="",arrow.style.left="",this._setDirection(direction),["left","right"].indexOf(direction)>-1?("left"==direction?el.style.left=pos.right-pos.width-own.width-offset+"px":el.style.left=pos.right+offset+"px",el.style.top=pos.bottom-pos.height/2-own.height/2+"px"):("up"==direction?el.style.top=pos.bottom-pos.height-own.height-offset+"px":el.style.top=pos.bottom+offset+"px",el.style.left=pos.right-pos.width/2-own.width/2+"px"),own=el.getBoundingClientRect();var diff=function(x){return x/2*Math.sqrt(2)-x/2}(parseInt(window.getComputedStyle(arrow).width)),limit=margin+radius+diff+2;["left","right"].indexOf(direction)>-1?own.top<margin?(arrow.style.top=Math.max(own.height/2+own.top-margin,limit)+"px",el.style.top=margin+"px"):own.bottom>window.innerHeight-margin&&(arrow.style.top=Math.min(own.height/2-(window.innerHeight-own.bottom)+margin,own.height-limit)+"px",el.style.top=window.innerHeight-own.height-margin+"px"):own.left<margin?(arrow.style.left=Math.max(own.width/2+own.left-margin,limit)+"px",el.style.left=margin+"px"):own.right>window.innerWidth-margin&&(arrow.style.left=Math.min(own.width/2-(window.innerWidth-own.right)+margin,own.width-limit)+"px",el.style.left=window.innerWidth-own.width-margin+"px"),el.removeAttribute("data-animit-orig-style")}},{key:"_positionPopover",value:function(target){for(var _this=this,directions=function(){return _this.hasAttribute("direction")?_this.getAttribute("direction").split(/\s+/):["up","down","left","right"]}(),position=target.getBoundingClientRect(),scores={left:position.left,right:window.innerWidth-position.right,up:position.top,down:window.innerHeight-position.bottom},orderedDirections=Object.keys(scores).sort(function(a,b){return-(scores[a]-scores[b])}),i=0,l=orderedDirections.length;l>i;i++){var direction=orderedDirections[i];if(directions.indexOf(direction)>-1)return void this._positionPopoverByDirection(target,direction)}}},{key:"_onChange",value:function(){var _this2=this;setImmediate(function(){_this2._currentTarget&&_this2._positionPopover(_this2._currentTarget)})}},{key:"_compile",value:function(){var templateElement=templateSource.cloneNode(!0),content=templateElement.querySelector(".popover__content"),style=this.getAttribute("style");for(style&&this.removeAttribute("style");this.childNodes[0];)content.appendChild(this.childNodes[0]);for(;templateElement.children[0];)this.appendChild(templateElement.children[0]);style&&this._popover.setAttribute("style",style)}},{key:"show",value:function(target,options){var _this3=this;if("string"==typeof target?target=document.querySelector(target):target instanceof Event&&(target=target.target),!target)throw new Error("Target undefined");if(options=options||{},options.animation&&!(options.animation in _animatorDict))throw new Error("Animator "+options.animation+" is not registered.");options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var canceled=!1;util.triggerElementEvent(this,"preshow",{popover:this,cancel:function(){canceled=!0}}),canceled||this._doorLock.waitUnlock(function(){var unlock=_this3._doorLock.lock();_this3.style.display="block",_this3._currentTarget=target,_this3._positionPopover(target);var animator=_this3._animatorFactory.newAnimator(options);animator.show(_this3,function(){_this3._visible=!0,unlock(),util.triggerElementEvent(_this3,"postshow",{popover:_this3 })})})}},{key:"hide",value:function(options){var _this4=this;options=options||{};var canceled=!1;util.triggerElementEvent(this,"prehide",{popover:this,cancel:function(){canceled=!0}}),canceled||this._doorLock.waitUnlock(function(){var unlock=_this4._doorLock.lock(),animator=_this4._animatorFactory.newAnimator(options);animator.hide(_this4,function(){_this4.style.display="none",_this4._visible=!1,unlock(),util.triggerElementEvent(_this4,"posthide",{popover:_this4})})})}},{key:"isShown",value:function(){return this._visible}},{key:"attachedCallback",value:function(){this._mask.addEventListener("click",this._boundCancel,!1),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._popover.addEventListener("DOMNodeInserted",this._boundOnChange,!1),this._popover.addEventListener("DOMNodeRemoved",this._boundOnChange,!1),window.addEventListener("resize",this._boundOnChange,!1)}},{key:"detachedCallback",value:function(){this._mask.removeEventListener("click",this._boundCancel,!1),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._popover.removeEventListener("DOMNodeInserted",this._boundOnChange,!1),this._popover.removeEventListener("DOMNodeRemoved",this._boundOnChange,!1),window.removeEventListener("resize",this._boundOnChange,!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name?this._boundOnChange():("animation"===name||"animation-options"===name)&&(this._animatorFactory=this._createAnimatorFactory()))}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this)}},{key:"_cancel",value:function(){this.isCancelable()&&this.hide()}},{key:"_mask",get:function(){return this.children[0]}},{key:"_popover",get:function(){return this.children[1]}},{key:"_content",get:function(){return this._popover.children[0]}},{key:"_arrow",get:function(){return this._popover.children[1]}}]),PopoverElement}(ons._BaseElement);window.OnsPopoverElement||(window.OnsPopoverElement=document.registerElement("ons-popover",{prototype:PopoverElement.prototype}),window.OnsPopoverElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof PopoverAnimator))throw new Error('"Animator" param must inherit PopoverAnimator');_animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".progress-bar":"progress-bar--*",".progress-bar__primary":"progress-bar__primary--*",".progress-bar__secondary":"progress-bar__secondary--*"},template=util.createElement('\n <div class="progress-bar">\n <div class="progress-bar__secondary"></div>\n <div class="progress-bar__primary"></div>\n </div>\n '),ProgressBarElement=function(_ons$_BaseElement){function ProgressBarElement(){_classCallCheck(this,ProgressBarElement),_get(Object.getPrototypeOf(ProgressBarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ProgressBarElement,_ons$_BaseElement),_createClass(ProgressBarElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("value"===name||"secondary-value"===name?this._updateValue():"indeterminate"===name&&this._updateDeterminate())}},{key:"_updateDeterminate",value:function(){this.hasAttribute("indeterminate")?(this._template.classList.add("progress-bar--indeterminate"),this._template.classList.remove("progress-bar--determinate")):(this._template.classList.add("progress-bar--determinate"),this._template.classList.remove("progress-bar--indeterminate"))}},{key:"_updateValue",value:function(){this._primary.style.width=this.hasAttribute("value")?this.getAttribute("value")+"%":"0%",this._secondary.style.width=this.hasAttribute("secondary-value")?this.getAttribute("secondary-value")+"%":"0%"}},{key:"_compile",value:function(){this._template=template.cloneNode(!0),this._primary=this._template.childNodes[3],this._secondary=this._template.childNodes[1],this._updateDeterminate(),this._updateValue(),this.appendChild(this._template)}}]),ProgressBarElement}(ons._BaseElement);window.OnsProgressBarElement||(window.OnsProgressBarElement=document.registerElement("ons-progress-bar",{prototype:ProgressBarElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".progress-circular":"progress-circular--*",".progress-circular__primary":"progress-circular__primary--*",".progress-circular__secondary":"progress-circular__secondary--*"},template=util.createElement('\n <svg class="progress-circular">\n <circle class="progress-circular__secondary" cx="50%" cy="50%" r="40%" fill="none" stroke-width="10%" stroke-miterlimit="10"/>\n <circle class="progress-circular__primary" cx="50%" cy="50%" r="40%" fill="none" stroke-width="10%" stroke-miterlimit="10"/>\n </svg>\n '),ProgressCircularElement=function(_ons$_BaseElement){function ProgressCircularElement(){_classCallCheck(this,ProgressCircularElement),_get(Object.getPrototypeOf(ProgressCircularElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ProgressCircularElement,_ons$_BaseElement),_createClass(ProgressCircularElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("value"===name||"secondary-value"===name?this._updateValue():"indeterminate"===name&&this._updateDeterminate())}},{key:"_updateDeterminate",value:function(){this.hasAttribute("indeterminate")?(this._template.classList.add("progress-circular--indeterminate"),this._template.classList.remove("progress-circular--determinate")):(this._template.classList.add("progress-circular--determinate"),this._template.classList.remove("progress-circular--indeterminate"))}},{key:"_updateValue",value:function(){if(this.hasAttribute("value")){var per=Math.ceil(251.32*this.getAttribute("value")*.01);this._primary.style["stroke-dasharray"]=per+"%, 251.32%"}if(this.hasAttribute("secondary-value")){var per=Math.ceil(251.32*this.getAttribute("secondary-value")*.01);this._secondary.style["stroke-dasharray"]=per+"%, 251.32%"}}},{key:"_compile",value:function(){this._template=template.cloneNode(!0),this._primary=this._template.childNodes[3],this._secondary=this._template.childNodes[1],this._updateDeterminate(),this._updateValue(),this.appendChild(this._template)}}]),ProgressCircularElement}(ons._BaseElement);window.OnsProgressCircularElement||(window.OnsProgressCircularElement=document.registerElement("ons-progress-circular",{prototype:ProgressCircularElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x2,_x3,_x4){for(var _again=!0;_again;){var object=_x2,property=_x3,receiver=_x4;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x2=parent,_x3=property,_x4=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var STATE_INITIAL="initial",STATE_PREACTION="preaction",STATE_ACTION="action",util=ons._util,PullHookElement=function(_ons$_BaseElement){function PullHookElement(){_classCallCheck(this,PullHookElement),_get(Object.getPrototypeOf(PullHookElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PullHookElement,_ons$_BaseElement),_createClass(PullHookElement,[{key:"createdCallback",value:function(){if(this._scrollElement=this._createScrollElement(),this._pageElement=this._scrollElement.parentElement,!this._pageElement.classList.contains("page__content")&&!this._pageElement.classList.contains("ons-scroller__content"))throw new Error("<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.");this._boundOnDrag=this._onDrag.bind(this),this._boundOnDragStart=this._onDragStart.bind(this),this._boundOnDragEnd=this._onDragEnd.bind(this),this._boundOnScroll=this._onScroll.bind(this),this._currentTranslation=0,this._setState(STATE_INITIAL,!0),this._setStyle()}},{key:"_createScrollElement",value:function(){var scrollElement=util.createElement('<div class="scroll"><div>'),pageElement=this.parentElement;for(scrollElement.appendChild(this);pageElement.firstChild;)scrollElement.appendChild(pageElement.firstChild);return pageElement.appendChild(scrollElement),scrollElement}},{key:"_setStyle",value:function(){var height=this.getHeight();this.style.top="-"+height+"px",this.style.height=height+"px",this.style.lineHeight=height+"px"}},{key:"_onScroll",value:function(event){var element=this._pageElement;element.scrollTop<0&&(element.scrollTop=0)}},{key:"_generateTranslationTransform",value:function(scroll){return"translate3d(0px, "+scroll+"px, 0px)"}},{key:"_onDrag",value:function(event){var _this=this;if(!this.isDisabled()&&"left"!==event.gesture.direction&&"right"!==event.gesture.direction){var element=this._pageElement;if(element.scrollTop=this._startScroll-event.gesture.deltaY,element.scrollTop<window.innerHeight&&"up"!==event.gesture.direction&&event.gesture.preventDefault(),0===this._currentTranslation&&0===this._getCurrentScroll()){this._transitionDragLength=event.gesture.deltaY;var direction=event.gesture.interimDirection;"down"===direction?this._transitionDragLength-=1:this._transitionDragLength+=1}var scroll=Math.max(event.gesture.deltaY-this._startScroll,0);this._thresholdHeightEnabled()&&scroll>=this.getThresholdHeight()?(event.gesture.stopDetect(),setImmediate(function(){_this._setState(STATE_ACTION),_this._translateTo(_this.getHeight(),{animate:!0}),_this._waitForAction(_this._onDone.bind(_this))})):scroll>=this.getHeight()?this._setState(STATE_PREACTION):this._setState(STATE_INITIAL),event.stopPropagation(),this._translateTo(scroll)}}},{key:"_onDragStart",value:function(event){this.isDisabled()||(this._startScroll=this._getCurrentScroll())}},{key:"_onDragEnd",value:function(event){if(!this.isDisabled()&&this._currentTranslation>0){var _scroll=this._currentTranslation;_scroll>this.getHeight()?(this._setState(STATE_ACTION),this._translateTo(this.getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))):this._translateTo(0,{animate:!0})}}},{key:"setActionCallback",value:function(callback){this._callback=callback}},{key:"_waitForAction",value:function(done){this._callback instanceof Function?this._callback.call(null,done):done()}},{key:"_onDone",value:function(done){this._translateTo(0,{animate:!0}),this._setState(STATE_INITIAL)}},{key:"getHeight",value:function(){return parseInt(this.getAttribute("height")||"64",10)}},{key:"setHeight",value:function(height){this.setAttribute("height",height+"px"),this._setStyle()}},{key:"setThresholdHeight",value:function(thresholdHeight){this.setAttribute("threshold-height",thresholdHeight+"px")}},{key:"getThresholdHeight",value:function(){return parseInt(this.getAttribute("threshold-height")||"96",10)}},{key:"_thresholdHeightEnabled",value:function(){var th=this.getThresholdHeight();return th>0&&th>=this.getHeight()}},{key:"_setState",value:function(state,noEvent){var lastState=this._getState();this.setAttribute("state",state),noEvent||lastState===this._getState()||util.triggerElementEvent(this,"changestate",{pullHook:this,state:state,lastState:lastState})}},{key:"_getState",value:function(){return this.getAttribute("state")}},{key:"getCurrentState",value:function(){return this._getState()}},{key:"_getCurrentScroll",value:function(){return this._pageElement.scrollTop}},{key:"getPullDistance",value:function(){return this._currentTranslation}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"_isContentFixed",value:function(){return this.hasAttribute("fixed-content")}},{key:"setDisabled",value:function(disabled){disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"_getScrollableElement",value:function(){return this._isContentFixed()?this:this._scrollElement}},{key:"_translateTo",value:function(scroll){var _this2=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];if(0!=this._currentTranslation||0!=scroll){var done=function(){0===scroll&&_this2._getScrollableElement().removeAttribute("style"),options.callback&&options.callback()};this._currentTranslation=scroll,options.animate?animit(this._getScrollableElement()).queue({transform:this._generateTranslationTransform(scroll)},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(done):animit(this._getScrollableElement()).queue({transform:this._generateTranslationTransform(scroll)}).play(done)}}},{key:"_getMinimumScroll",value:function(){var scrollHeight=this._scrollElement.getBoundingClientRect().height,pageHeight=this._pageElement.getBoundingClientRect().height;return scrollHeight>pageHeight?-(scrollHeight-pageHeight):0}},{key:"_createEventListeners",value:function(){this._gestureDetector=new ons.GestureDetector(this._pageElement,{dragMinDistance:1,dragDistanceCorrection:!1}),this._gestureDetector.on("drag",this._boundOnDrag),this._gestureDetector.on("dragstart",this._boundOnDragStart),this._gestureDetector.on("dragend",this._boundOnDragEnd),this._scrollElement.parentElement.addEventListener("scroll",this._boundOnScroll,!1)}},{key:"_destroyEventListeners",value:function(){this._gestureDetector.off("drag",this._boundOnDrag),this._gestureDetector.off("dragstart",this._boundOnDragStart),this._gestureDetector.off("dragend",this._boundOnDragEnd),this._gestureDetector.dispose(),this._gestureDetector=null,this._scrollElement.parentElement.removeEventListener("scroll",this._boundOnScroll,!1)}},{key:"attachedCallback",value:function(){this._createEventListeners()}},{key:"detachedCallback",value:function(){this._destroyEventListeners()}},{key:"attributeChangedCallback",value:function(name,last,current){}}]),PullHookElement}(ons._BaseElement);window.OnsPullHookElement||(window.OnsPullHookElement=document.registerElement("ons-pull-hook",{prototype:PullHookElement.prototype}),window.OnsPullHookElement.STATE_ACTION=STATE_ACTION,window.OnsPullHookElement.STATE_INITIAL=STATE_INITIAL,window.OnsPullHookElement.STATE_PREACTION=STATE_PREACTION)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var RippleElement=function(_ons$_BaseElement){function RippleElement(){_classCallCheck(this,RippleElement),_get(Object.getPrototypeOf(RippleElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(RippleElement,_ons$_BaseElement),_createClass(RippleElement,[{key:"createdCallback",value:function(){this.classList.add("ripple"),this._compile(),this._boundOnClick=this._onMouseDown.bind(this)}},{key:"_compile",value:function(){this._wave=document.createElement("span"),this._wave.classList.add("ripple__wave"),this.insertBefore(this._wave,this.children[0]),this.hasAttribute("color")&&(this._wave.style.background=this.getAttribute("color"))}},{key:"_updateTarget",value:function(){this.hasAttribute("target")&&"children"===this.getAttribute("target")?(this._target=this,this.style.display="inline-block",this.style.position="relative"):(this._target=this.parentNode,"static"===window.getComputedStyle(this._target).getPropertyValue("position")&&(this._target.style.position="relative"),this.style.display="block",this.style.position="absolute")}},{key:"_updateCenter",value:function(){this.hasAttribute("center")?this._center=!0:this._center=!1,this._wave.classList.remove("ripple__wave--done-center"),this._wave.classList.remove("ripple__wave--animate-center"),this._wave.classList.remove("ripple__wave--done"),this._wave.classList.remove("ripple__wave--animate")}},{key:"attributeChangedCallback",value:function(name,last,current){"target"===name&&this._updateTarget(),"color"===name&&(this._wave.style.background=current),"center"===name&&this._updateCenter()}},{key:"_isTouchDevice",value:function(){return"ontouchstart"in window||"onmsgesturechange"in window}},{key:"_addListener",value:function(){this._isTouchDevice()?this.addEventListener("touchstart",this._boundOnClick):this.addEventListener("mousedown",this._boundOnClick)}},{key:"_removeListener",value:function(){this._isTouchDevice()?this.removeEventListener("touchstart",this._boundOnClick):this.removeEventListener("mousedown",this._boundOnClick)}},{key:"attachedCallback",value:function(){this._updateCenter(),this._updateTarget(),this._addListener()}},{key:"detachedCallback",value:function(){this._removeListener()}},{key:"_onMouseDown",value:function(e){var _this=this,eventType=e.type,wave=this._wave,el=this._target,pos=el.getBoundingClientRect();if(!this.isDisabled()){this._center?(wave.classList.remove("ripple__wave--done-center"),wave.classList.remove("ripple__wave--animate-center")):(wave.classList.remove("ripple__wave--done"),wave.classList.remove("ripple__wave--animate"));var animationEnded=new Promise(function(resolve){var onAnimationEnd=function onAnimationEnd(){_this.removeEventListener("webkitAnimationEnd",onAnimationEnd),_this.removeEventListener("animationend",onAnimationEnd),resolve()};_this.addEventListener("webkitAnimationEnd",onAnimationEnd),_this.addEventListener("animationend",onAnimationEnd)}),mouseReleased=new Promise(function(resolve){var onMouseUp=function onMouseUp(){document.removeEventListener("webkitAnimationEnd",onMouseUp),document.removeEventListener("animationend",onMouseUp),resolve()};document.addEventListener("mouseup",onMouseUp),document.addEventListener("touchend",onMouseUp)});Promise.all([animationEnded,mouseReleased]).then(function(){_this._center?(wave.classList.remove("ripple__wave--animate-center"),wave.classList.add("ripple__wave--done-center")):(wave.classList.remove("ripple__wave--animate"),wave.classList.add("ripple__wave--done"))});var x=e.clientX,y=e.clientY;"touchstart"===eventType&&(x=e.changedTouches[0].clientX,y=e.changedTouches[0].clientY);var sizeX=void 0,sizeY=0;this._center?(sizeX=el.offsetWidth,sizeY=el.offsetHeight,sizeX=sizeX-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-left-width"))-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-right-width")),sizeY=sizeY-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-top-width"))-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-bottom-width"))):sizeX=sizeY=Math.max(el.offsetWidth,el.offsetHeight),wave.style.width=sizeX+"px",wave.style.height=sizeY+"px",x=x-pos.left-sizeX/2,y=y-pos.top-sizeY/2,wave.style.left=x+"px",wave.style.top=y+"px",this._center?wave.classList.add("ripple__wave--animate-center"):wave.classList.add("ripple__wave--animate")}}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}}]),RippleElement}(ons._BaseElement);window.OnsRippleElement||(window.OnsRippleElement=document.registerElement("ons-ripple",{prototype:RippleElement.prototype}))}(),window.OnsRowElement=window.OnsRowElement?window.OnsRowElement:document.registerElement("ons-row"),window.OnsScrollerElement=window.OnsScrollerElement?window.OnsScrollerElement:document.registerElement("ons-scroller");var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"speed-dial__item--*"},ModifierUtil=ons._internal.ModifierUtil,SpeedDialItemElement=function(_ons$_BaseElement){function SpeedDialItemElement(){_classCallCheck(this,SpeedDialItemElement),_get(Object.getPrototypeOf(SpeedDialItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SpeedDialItemElement,_ons$_BaseElement),_createClass(SpeedDialItemElement,[{key:"createdCallback",value:function(){ModifierUtil.initModifier(this,scheme),this.classList.add("fab"),this.classList.add("fab--mini"),this.classList.add("speed-dial__item"),this._boundOnClick=this._onClick.bind(this)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"_onClick",value:function(e){e.stopPropagation()}}]),SpeedDialItemElement}(ons._BaseElement);window.OnsSpeedDialItemElement||(window.OnsSpeedDialItemElement=document.registerElement("ons-speed-dial-item",{prototype:SpeedDialItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x3=parent,_x4=property,_x5=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"speed-dial--*"},ModifierUtil=ons._internal.ModifierUtil,SpeedDialElement=function(_ons$_BaseElement){function SpeedDialElement(){_classCallCheck(this,SpeedDialElement),_get(Object.getPrototypeOf(SpeedDialElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SpeedDialElement,_ons$_BaseElement),_createClass(SpeedDialElement,[{key:"createdCallback",value:function(){this._compile(),this._shown=!0,this._itemShown=!1,ModifierUtil.initModifier(this,scheme),this._boundOnClick=this._onClick.bind(this),this.classList.add("speed__dial"),this.hasAttribute("direction")?this._updateDirection(this.getAttribute("direction")):this._updateDirection("up"),this._updatePosition(),this.hasAttribute("disabled")&&this.setDisabled(!0)}},{key:"_compile",value:function(){var content=document.createElement("ons-fab");ons._util.arrayFrom(this.childNodes).forEach(function(element){return"ons-speed-dial-item"!==element.nodeName.toLowerCase()?content.firstChild.appendChild(element):!0});this.insertBefore(content,this.firstChild)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name?this._updateDirection(current):"position"===name?this._updatePosition():"disabled"===name&&(null!==current?this.setDisabled(!0):this.setDisabled(!1)))}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"_onClick",value:function(e){this.isDisabled()||this.toggleItems()}},{key:"_show",value:function(){this.isInline()||this.show()}},{key:"_hide",value:function(){this.isInline()||this.hide()}},{key:"_updateDirection",value:function(direction){for(var children=this.items,i=0;i<children.length;i++)children[i].style.transitionDelay=25*i+"ms",children[i].style.webkitTransitionDelay=25*i+"ms",children[i].style.bottom="auto",children[i].style.right="auto",children[i].style.top="auto",children[i].style.left="auto";switch(direction){case"up":for(var i=0;i<children.length;i++)children[i].style.bottom=72+56*i+"px",children[i].style.right="8px";break;case"down":for(var i=0;i<children.length;i++)children[i].style.top=72+56*i+"px",children[i].style.left="8px";break;case"left":for(var i=0;i<children.length;i++)children[i].style.top="8px",children[i].style.right=72+56*i+"px";break;case"right":for(var i=0;i<children.length;i++)children[i].style.top="8px",children[i].style.left=72+56*i+"px";break;default:throw new Error("Argument must be one of up, down, left or right.")}}},{key:"_updatePosition",value:function(){var position=this.getAttribute("position");switch(this.classList.remove("fab--top__left","fab--bottom__right","fab--bottom__left","fab--top__right","fab--top__center","fab--bottom__center"),position){case"top right":case"right top":this.classList.add("fab--top__right");break;case"top left":case"left top":this.classList.add("fab--top__left");break;case"bottom right":case"right bottom":this.classList.add("fab--bottom__right");break;case"bottom left":case"left bottom":this.classList.add("fab--bottom__left");break;case"center top":case"top center":this.classList.add("fab--top__center");break;case"center bottom":case"bottom center":this.classList.add("fab--bottom__center")}}},{key:"show",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.querySelector("ons-fab").show(),this._shown=!0}},{key:"hide",value:function(){var _this=this;arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.hideItems(),setTimeout(function(){_this.querySelector("ons-fab").hide()},200),this._shown=!1}},{key:"showItems",value:function(){if(!this._itemShown)for(var children=this.items,i=0;i<children.length;i++)children[i].style.transform="scale(1)",children[i].style.webkitTransform="scale(1)",children[i].style.transitionDelay=25*i+"ms",children[i].style.webkitTransitionDelay=25*i+"ms";this._itemShown=!0}},{key:"hideItems",value:function(){if(this._itemShown)for(var children=this.items,i=0;i<children.length;i++)children[i].style.transform="scale(0)",children[i].style.webkitTransform="scale(0)",children[i].style.transitionDelay=25*(children.length-i)+"ms",children[i].style.webkitTransitionDelay=25*(children.length-i)+"ms";this._itemShown=!1}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?(this.hideItems(),this.setAttribute("disabled",""),ons._util.arrayFrom(this.childNodes).forEach(function(element){return element.classList.contains("fab")?element.setAttribute("disabled",""):!0})):(this.removeAttribute("disabled"),ons._util.arrayFrom(this.childNodes).forEach(function(element){return element.classList.contains("fab")?element.removeAttribute("disabled"):!0}))}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"isInline",value:function(){return this.hasAttribute("inline")}},{key:"isShown",value:function(){return this._shown&&"none"!==this.style.display}},{key:"isItemShown",value:function(){return this._itemShown}},{key:"toggle",value:function(){this.isShown()?this.hide():this.show()}},{key:"toggleItems",value:function(){this.isItemShown()?this.hideItems():this.showItems()}},{key:"items",get:function(){return ons._util.arrayFrom(this.querySelectorAll("ons-speed-dial-item"))}}]),SpeedDialElement}(ons._BaseElement);window.OnsSpeedDialElement||(window.OnsSpeedDialElement=document.registerElement("ons-speed-dial",{ prototype:SpeedDialElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x2,_x3,_x4){for(var _again=!0;_again;){var object=_x2,property=_x3,receiver=_x4;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x2=parent,_x3=property,_x4=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var util=ons._util,rewritables={ready:function(splitterSideElement,callback){setImmediate(callback)},link:function(splitterSideElement,target,callback){callback(target)}},SplitterContentElement=function(_ons$_BaseElement){function SplitterContentElement(){_classCallCheck(this,SplitterContentElement),_get(Object.getPrototypeOf(SplitterContentElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterContentElement,_ons$_BaseElement),_createClass(SplitterContentElement,[{key:"createdCallback",value:function(){this._page=null}},{key:"load",value:function(page){var _this=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._page=page,options.callback=options.callback instanceof Function?options.callback:function(){},ons._internal.getPageHTMLAsync(page).then(function(html){rewritables.link(_this,util.createFragment(html),function(fragment){for(;_this.childNodes[0];)_this.childNodes[0]._hide instanceof Function&&_this.childNodes[0]._hide(),_this.removeChild(_this.childNodes[0]);_this.appendChild(fragment),util.arrayFrom(fragment.children).forEach(function(child){child._show instanceof Function&&child._show()}),options.callback()})})}},{key:"attachedCallback",value:function(){var _this2=this;this._assertParent(),this.hasAttribute("page")&&setImmediate(function(){return rewritables.ready(_this2,function(){return _this2.load(_this2.getAttribute("page"))})})}},{key:"detachedCallback",value:function(){}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}},{key:"_assertParent",value:function(){var parentElementName=this.parentElement.nodeName.toLowerCase();if("ons-splitter"!==parentElementName)throw new Error('"'+parentElementName+'" element is not allowed as parent element.')}},{key:"page",get:function(){return this._page}}]),SplitterContentElement}(ons._BaseElement);window.OnsSplitterContentElement||(window.OnsSplitterContentElement=document.registerElement("ons-splitter-content",{prototype:SplitterContentElement.prototype}),window.OnsSplitterContentElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var SplitterMaskElement=function(_ons$_BaseElement){function SplitterMaskElement(){_classCallCheck(this,SplitterMaskElement),_get(Object.getPrototypeOf(SplitterMaskElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterMaskElement,_ons$_BaseElement),_createClass(SplitterMaskElement,[{key:"createdCallback",value:function(){this._boundOnClick=this._onClick.bind(this)}},{key:"_onClick",value:function(event){this.parentElement&&"ons-splitter"===this.parentElement.nodeName.toLowerCase()&&(this.parentElement.closeRight(),this.parentElement.closeLeft()),event.stopPropagation()}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick)}}]),SplitterMaskElement}(ons._BaseElement);window.OnsSplitterMaskElement||(window.OnsSplitterMaskElement=document.registerElement("ons-splitter-mask",{prototype:SplitterMaskElement.prototype}))}();var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i["return"]&&_i["return"]()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_get=function(_x9,_x10,_x11){for(var _again=!0;_again;){var object=_x9,property=_x10,receiver=_x11;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x9=parent,_x10=property,_x11=receiver,_again=!0,desc=parent=void 0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(){"use strict";var util=ons._util,AnimatorFactory=ons._internal.AnimatorFactory,SPLIT_MODE="split",COLLAPSE_MODE="collapse",CollapseDetection=function(){function CollapseDetection(){_classCallCheck(this,CollapseDetection)}return _createClass(CollapseDetection,[{key:"activate",value:function(element){}},{key:"inactivate",value:function(){}}]),CollapseDetection}(),rewritables={ready:function(splitterSideElement,callback){setImmediate(callback)},link:function(splitterSideElement,target,callback){callback(target)}},OrientationCollapseDetection=function(_CollapseDetection){function OrientationCollapseDetection(orientation){if(_classCallCheck(this,OrientationCollapseDetection),_get(Object.getPrototypeOf(OrientationCollapseDetection.prototype),"constructor",this).call(this),"portrait"!==orientation&&"landscape"!==orientation)throw new Error("Invalid orientation: "+orientation);this._boundOnOrientationChange=this._onOrientationChange.bind(this),this._targetOrientation=orientation}return _inherits(OrientationCollapseDetection,_CollapseDetection),_createClass(OrientationCollapseDetection,[{key:"activate",value:function(element){this._element=element,ons.orientation.on("change",this._boundOnOrientationChange),this._update(ons.orientation.isPortrait())}},{key:"_onOrientationChange",value:function(info){this._update(info.isPortrait)}},{key:"_update",value:function(isPortrait){isPortrait&&"portrait"===this._targetOrientation?this._element._updateMode(COLLAPSE_MODE):isPortrait||"landscape"!==this._targetOrientation?this._element._updateMode(SPLIT_MODE):this._element._updateMode(COLLAPSE_MODE)}},{key:"inactivate",value:function(){this._element=null,ons.orientation.off("change",this._boundOnOrientationChange)}}]),OrientationCollapseDetection}(CollapseDetection),StaticCollapseDetection=function(_CollapseDetection2){function StaticCollapseDetection(){_classCallCheck(this,StaticCollapseDetection),_get(Object.getPrototypeOf(StaticCollapseDetection.prototype),"constructor",this).apply(this,arguments)}return _inherits(StaticCollapseDetection,_CollapseDetection2),_createClass(StaticCollapseDetection,[{key:"activate",value:function(element){element._updateMode(COLLAPSE_MODE)}}]),StaticCollapseDetection}(CollapseDetection),MediaQueryCollapseDetection=function(_CollapseDetection3){function MediaQueryCollapseDetection(query){_classCallCheck(this,MediaQueryCollapseDetection),_get(Object.getPrototypeOf(MediaQueryCollapseDetection.prototype),"constructor",this).call(this),this._mediaQueryString=query,this._boundOnChange=this._onChange.bind(this)}return _inherits(MediaQueryCollapseDetection,_CollapseDetection3),_createClass(MediaQueryCollapseDetection,[{key:"_onChange",value:function(queryList){this._element._updateMode(queryList.matches?COLLAPSE_MODE:SPLIT_MODE)}},{key:"activate",value:function(element){this._element=element,this._queryResult=window.matchMedia(this._mediaQueryString),this._queryResult.addListener(this._boundOnChange),this._onChange(this._queryResult)}},{key:"inactivate",value:function(){this._element=null,this._queryResult.removeListener(this._boundOnChange),this._queryResult=null}}]),MediaQueryCollapseDetection}(CollapseDetection),BaseMode=function(){function BaseMode(){_classCallCheck(this,BaseMode)}return _createClass(BaseMode,[{key:"isOpened",value:function(){return!1}},{key:"openMenu",value:function(){return!1}},{key:"closeMenu",value:function(){return!1}},{key:"enterMode",value:function(){}},{key:"exitMode",value:function(){}},{key:"handleGesture",value:function(){}}]),BaseMode}(),SplitMode=function(_BaseMode){function SplitMode(element){_classCallCheck(this,SplitMode),_get(Object.getPrototypeOf(SplitMode.prototype),"constructor",this).call(this),this._element=element}return _inherits(SplitMode,_BaseMode),_createClass(SplitMode,[{key:"isOpened",value:function(){return!1}},{key:"layout",value:function(){var element=this._element;element.style.width=element._getWidth(),element._isLeftSide()?(element.style.left="0",element.style.right="auto"):(element.style.left="auto",element.style.right="0")}},{key:"enterMode",value:function(){this.layout()}},{key:"exitMode",value:function(){var element=this._element;element.style.left="",element.style.right="",element.style.width="",element.style.zIndex=""}}]),SplitMode}(BaseMode),CollapseMode=function(_BaseMode2){function CollapseMode(element){_classCallCheck(this,CollapseMode),_get(Object.getPrototypeOf(CollapseMode.prototype),"constructor",this).call(this),this._state=CollapseMode.CLOSED_STATE,this._distance=0,this._element=element,this._lock=new DoorLock}return _inherits(CollapseMode,_BaseMode2),_createClass(CollapseMode,[{key:"_animator",get:function(){return this._element._getAnimator()}}],[{key:"CLOSED_STATE",get:function(){return"closed"}},{key:"OPENED_STATE",get:function(){return"opened"}},{key:"CHANGING_STATE",get:function(){return"changing"}}]),_createClass(CollapseMode,[{key:"_isLocked",value:function(){return this._lock.isLocked()}},{key:"isOpened",value:function(){return this._state!==CollapseMode.CLOSED_STATE}},{key:"isClosed",value:function(){return this._state===CollapseMode.CLOSED_STATE}},{key:"handleGesture",value:function(event){if(!this._isLocked()&&!this._openedOtherSideMenu())if("dragstart"===event.type)this._onDragStart(event);else if("dragleft"===event.type||"dragright"===event.type)this._ignoreDrag||this._onDrag(event);else{if("dragend"!==event.type)throw new Error("Invalid state");this._ignoreDrag||this._onDragEnd(event)}}},{key:"_onDragStart",value:function(event){if(this._ignoreDrag=!1,!this.isOpened()&&this._openedOtherSideMenu())this._ignoreDrag=!0;else if(this._element._swipeTargetWidth>0){var distance=this._element._isLeftSide()?event.gesture.center.clientX:window.innerWidth-event.gesture.center.clientX;distance>this._element._swipeTargetWidth&&(this._ignoreDrag=!0)}}},{key:"_onDrag",value:function(event){event.gesture.preventDefault();var deltaX=event.gesture.deltaX,deltaDistance=this._element._isLeftSide()?deltaX:-deltaX,startEvent=event.gesture.startEvent;"isOpened"in startEvent||(startEvent.isOpened=this.isOpened(),startEvent.distance=startEvent.isOpened?this._element._getWidthInPixel():0,startEvent.width=this._element._getWidthInPixel());var width=this._element._getWidthInPixel();if(!(0>deltaDistance&&startEvent.distance<=0||deltaDistance>0&&startEvent.distance>=width)){var distance=startEvent.isOpened?deltaDistance+width:deltaDistance,normalizedDistance=Math.max(0,Math.min(width,distance));startEvent.distance=normalizedDistance,this._state=CollapseMode.CHANGING_STATE,this._animator.translate(normalizedDistance)}}},{key:"_onDragEnd",value:function(event){var deltaX=event.gesture.deltaX,deltaDistance=this._element._isLeftSide()?deltaX:-deltaX,width=event.gesture.startEvent.width,distance=event.gesture.startEvent.isOpened?deltaDistance+width:deltaDistance,direction=event.gesture.interimDirection,shouldOpen=this._element._isLeftSide()&&"right"===direction&&distance>width*this._element._getThresholdRatioIfShouldOpen()||!this._element._isLeftSide()&&"left"===direction&&distance>width*this._element._getThresholdRatioIfShouldOpen();shouldOpen?this._openMenu():this._closeMenu()}},{key:"layout",value:function(){if(this._state!==CollapseMode.CHANGING_STATE)if(this._state===CollapseMode.CLOSED_STATE)this._animator.isActivated()&&this._animator.layoutOnClose();else{if(this._state!==CollapseMode.OPENED_STATE)throw new Error("Invalid state");this._animator.isActivated()&&this._animator.layoutOnOpen()}}},{key:"enterMode",value:function(){this._animator.activate(this._element._getContentElement(),this._element,this._element._getMaskElement()),this.layout()}},{key:"exitMode",value:function(){this._animator.inactivate()}},{key:"_openedOtherSideMenu",value:function(){var _this=this;return util.arrayFrom(this._element.parentElement.children).filter(function(child){return"ons-splitter-side"===child.nodeName.toLowerCase()&&_this._element!==child}).filter(function(side){return side.isOpened()}).length>0}},{key:"openMenu",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._state!==CollapseMode.CLOSED_STATE?!1:this._openMenu(options)}},{key:"_openMenu",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(this._isLocked())return!1;if(this._openedOtherSideMenu())return!1;if(this._element._emitPreOpenEvent())return!1;options.callback=options.callback instanceof Function?options.callback:function(){};var unlock=this._lock.lock(),done=function(){unlock(),_this2._element._emitPostOpenEvent(),options.callback()};return options.withoutAnimation?(this._state=CollapseMode.OPENED_STATE,this.layout(),done()):(this._state=CollapseMode.CHANGING_STATE,this._animator.open(function(){_this2._state=CollapseMode.OPENED_STATE,_this2.layout(),done()})),!0}},{key:"closeMenu",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._state!==CollapseMode.OPENED_STATE?!1:this._closeMenu(options)}},{key:"_closeMenu",value:function(){var _this3=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(this._isLocked())return!1;if(this._element._emitPreCloseEvent())return!1;options.callback=options.callback instanceof Function?options.callback:function(){};var unlock=this._lock.lock(),done=function(){unlock(),_this3._element._emitPostCloseEvent(),setImmediate(options.callback)};return options.withoutAnimation?(this._state=CollapseMode.CLOSED_STATE,this.layout(),done()):(this._state=CollapseMode.CHANGING_STATE,this._animator.close(function(){_this3._state=CollapseMode.CLOSED_STATE,_this3.layout(),done()})),!0}}]),CollapseMode}(BaseMode),SplitterSideElement=function(_ons$_BaseElement){function SplitterSideElement(){_classCallCheck(this,SplitterSideElement),_get(Object.getPrototypeOf(SplitterSideElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterSideElement,_ons$_BaseElement),_createClass(SplitterSideElement,[{key:"_updateForAnimationOptionsAttribute",value:function(){this._animationOptions=util.parseJSONObjectSafely(this.getAttribute("animation-options"),{})}},{key:"_getMaskElement",value:function(){return util.findChild(this.parentElement,"ons-splitter-mask")}},{key:"_getContentElement",value:function(){return util.findChild(this.parentElement,"ons-splitter-content")}},{key:"_getModeStrategy",value:function(){return this._mode===COLLAPSE_MODE?this._collapseMode:this._mode===SPLIT_MODE?this._splitMode:void 0}},{key:"createdCallback",value:function(){this._mode=null,this._page=null,this._isAttached=!1,this._collapseStrategy=new CollapseDetection,this._animatorFactory=new AnimatorFactory({animators:window.OnsSplitterElement._animatorDict,baseClass:ons._internal.SplitterAnimator,baseClassName:"SplitterAnimator",defaultAnimation:this.getAttribute("animation")}),this._collapseMode=new CollapseMode(this),this._splitMode=new SplitMode(this),this._boundHandleGesture=this._handleGesture.bind(this),this._cancelModeDetection=function(){},this._updateMode(SPLIT_MODE),this._updateForAnimationAttribute(),this._updateForWidthAttribute(),this._updateForSideAttribute(),this._updateForCollapseAttribute(),this._updateForSwipeableAttribute(),this._updateForSwipeTargetWidthAttribute(),this._updateForAnimationOptionsAttribute()}},{key:"_getAnimator",value:function(){return this._animator}},{key:"isSwipeable",value:function(){return this.hasAttribute("swipeable")}},{key:"_emitPostOpenEvent",value:function(){util.triggerElementEvent(this,"postopen",{side:this})}},{key:"_emitPostCloseEvent",value:function(){util.triggerElementEvent(this,"postclose",{side:this})}},{key:"_emitPreOpenEvent",value:function(){return this._emitCancelableEvent("preopen")}},{key:"_emitCancelableEvent",value:function(name){var isCanceled=!1;return util.triggerElementEvent(this,name,{side:this,cancel:function(){return isCanceled=!0}}),isCanceled}},{key:"_emitPreCloseEvent",value:function(){return this._emitCancelableEvent("preclose")}},{key:"_updateForCollapseAttribute",value:function(){if(!this.hasAttribute("collapse"))return void this._updateMode(SPLIT_MODE);var collapse=(""+this.getAttribute("collapse")).trim();""===collapse?this._updateCollapseStrategy(new StaticCollapseDetection):"portrait"===collapse||"landscape"===collapse?this._updateCollapseStrategy(new OrientationCollapseDetection(collapse)):this._updateCollapseStrategy(new MediaQueryCollapseDetection(collapse))}},{key:"_updateCollapseStrategy",value:function(strategy){this._isAttached&&(this._collapseStrategy.inactivate(),strategy.activate(this)),this._collapseStrategy=strategy}},{key:"_updateMode",value:function(mode){if(mode!==COLLAPSE_MODE&&mode!==SPLIT_MODE)throw new Error("invalid mode: "+mode);if(mode!==this._mode){var lastMode=this._getModeStrategy();lastMode&&lastMode.exitMode(),this._mode=mode;var currentMode=this._getModeStrategy();currentMode.enterMode(),this.setAttribute("mode",mode),util.triggerElementEvent(this,"modechange",{side:this,mode:mode})}}},{key:"_getThresholdRatioIfShouldOpen",value:function(){if(this.hasAttribute("threshold-ratio-should-open")){var value=parseFloat(this.getAttribute("threshold-ratio-should-open"));return Math.max(0,Math.min(1,value))}return.3}},{key:"_layout",value:function(){this._getModeStrategy().layout()}},{key:"_updateForSwipeTargetWidthAttribute",value:function(){this.hasAttribute("swipe-target-width")?this._swipeTargetWidth=Math.max(0,parseInt(this.getAttribute("swipe-target-width"),10)):this._swipeTargetWidth=-1}},{key:"_getWidth",value:function(){function normalize(width){return width=width.trim(),width.match(/^\d+(px|%)$/)?width:"80%"}return this.hasAttribute("width")?normalize(this.getAttribute("width")):"80%"}},{key:"_getWidthInPixel",value:function(){var width=this._getWidth(),_width$match=width.match(/^(\d+)(px|%)$/),_width$match2=_slicedToArray(_width$match,3),num=_width$match2[1],unit=_width$match2[2];if("px"===unit)return parseInt(num,10);if("%"===unit){var percent=parseInt(num,10);return Math.round(this.parentElement.offsetWidth*percent/100)}throw new Error("Invalid state")}},{key:"_getSide",value:function(){function normalize(side){return side=(""+side).trim(),"left"===side||"right"===side?side:"left"}return normalize(this.getAttribute("side"))}},{key:"_isLeftSide",value:function(){return"left"===this._getSide()}},{key:"_updateForWidthAttribute",value:function(){this._getModeStrategy().layout()}},{key:"_updateForSideAttribute",value:function(){this._getModeStrategy().layout()}},{key:"getCurrentMode",value:function(){return this._mode}},{key:"isOpened",value:function(){return this._getModeStrategy().isOpened()}},{key:"open",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._getModeStrategy().openMenu(options)}},{key:"close",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._getModeStrategy().closeMenu(options)}},{key:"load",value:function(page){var _this4=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._page=page,options.callback=options.callback instanceof Function?options.callback:function(){},ons._internal.getPageHTMLAsync(page).then(function(html){rewritables.link(_this4,util.createFragment(html),function(fragment){for(;_this4.childNodes[0];)_this4.childNodes[0]._hide instanceof Function&&_this4.childNodes[0]._hide(),_this4.removeChild(_this4.childNodes[0]);_this4.appendChild(fragment),util.arrayFrom(fragment.childNodes).forEach(function(node){node._show instanceof Function&&node._show()}),options.callback()})})}},{key:"toggle",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this.isOpened()?this.close(options):this.open(options)}},{key:"attributeChangedCallback",value:function(name,last,current){"width"===name?this._updateForWidthAttribute():"side"===name?this._updateForSideAttribute():"collapse"===name?this._updateForCollapseAttribute():"swipeable"===name?this._updateForSwipeableAttribute():"swipe-target-width"===name?this._updateForSwipeTargetWidthAttribute():"animation-options"===name?this._updateForAnimationOptionsAttribute():"animation"===name&&this._updateForAnimationAttribute()}},{key:"_updateForAnimationAttribute",value:function(){var isActivated=this._animator&&this._animator.isActivated();isActivated&&this._animator.inactivate(),this._animator=this._createAnimator(),isActivated&&this._animator.activate(this._getContentElement(),this,this._getMaskElement())}},{key:"_updateForSwipeableAttribute",value:function(){this._gestureDetector&&(this.isSwipeable()?this._gestureDetector.on("dragstart dragleft dragright dragend",this._boundHandleGesture):this._gestureDetector.off("dragstart dragleft dragright dragend",this._boundHandleGesture))}},{key:"_assertParent",value:function(){var parentElementName=this.parentElement.nodeName.toLowerCase();if("ons-splitter"!==parentElementName)throw new Error('"'+parentElementName+'" element is not allowed as parent element.')}},{key:"attachedCallback",value:function(){var _this5=this;this._isAttached=!0,this._collapseStrategy.activate(this),this._assertParent(),this._gestureDetector=new ons.GestureDetector(this.parentElement,{dragMinDistance:1}),this._updateForSwipeableAttribute(),this.hasAttribute("page")&&setImmediate(function(){return rewritables.ready(_this5,function(){return _this5.load(_this5.getAttribute("page"))})})}},{key:"detachedCallback",value:function(){this._isAttached=!1,this._collapseStrategy.inactivate(),this._gestureDetector.dispose(),this._gestureDetector=null,this._updateForSwipeableAttribute()}},{key:"_handleGesture",value:function(event){return this._getModeStrategy().handleGesture(event)}},{key:"_show",value:function(){util.arrayFrom(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayFrom(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayFrom(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}},{key:"_createAnimator",value:function(){return this._animatorFactory.newAnimator({animation:this.getAttribute("animation"),animationOptions:AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))})}},{key:"page",get:function(){return this._page}},{key:"mode",get:function(){this._mode}}]),SplitterSideElement}(ons._BaseElement);window.OnsSplitterSideElement||(window.OnsSplitterSideElement=document.registerElement("ons-splitter-side",{prototype:SplitterSideElement.prototype}),window.OnsSplitterSideElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"switch--*",".switch__input":"switch--*__input",".switch__toggle":"switch--*__toggle"},ModifierUtil=ons._internal.ModifierUtil,templateSource=ons._util.createElement('\n <div>\n <input type="checkbox" class="switch__input">\n <div class="switch__toggle"></div>\n </div>\n '),ExtendableLabelElement=void 0;"function"!=typeof HTMLLabelElement?(ExtendableLabelElement=function(){},ExtendableLabelElement.prototype=document.createElement("label")):ExtendableLabelElement=HTMLLabelElement;var generateId=function(){var i=0;return function(){return"ons-switch-id-"+i++}}(),SwitchElement=function(_ExtendableLabelElement){function SwitchElement(){_classCallCheck(this,SwitchElement),_get(Object.getPrototypeOf(SwitchElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SwitchElement,_ExtendableLabelElement),_createClass(SwitchElement,[{key:"isChecked",value:function(){return this.checked}},{key:"setChecked",value:function(isChecked){this.checked=!!isChecked}},{key:"getCheckboxElement",value:function(){return this._getCheckbox()}},{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._updateForCheckedAttribute(),this._updateForDisabledAttribute()}},{key:"_updateForCheckedAttribute",value:function(){this.hasAttribute("checked")?this._getCheckbox().checked=!0:this._getCheckbox().checked=!1}},{key:"_updateForDisabledAttribute",value:function(){this.hasAttribute("disabled")?this._getCheckbox().setAttribute("disabled",""):this._getCheckbox().removeAttribute("disabled")}},{key:"_compile",value:function(){this.classList.add("switch");for(var template=templateSource.cloneNode(!0);template.children[0];)this.appendChild(template.children[0]);this._getCheckbox().setAttribute("name",generateId())}},{key:"detachedCallback",value:function(){this._getCheckbox().removeEventListener("change",this._onChangeListener)}},{key:"attachedCallback",value:function(){this._getCheckbox().addEventListener("change",this._onChangeListener)}},{key:"_onChangeListener",value:function(){this.checked!==!0?this.removeAttribute("checked"):this.setAttribute("checked","")}},{key:"_isChecked",value:function(){return this._getCheckbox().checked}},{key:"_setChecked",value:function(isChecked){isChecked=!!isChecked;var checkbox=this._getCheckbox();checkbox.checked!=isChecked&&(checkbox.checked=isChecked)}},{key:"_getCheckbox",value:function(){return this.querySelector("input[type=checkbox]")}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("checked"===name?this._updateForCheckedAttribute():"disabled"===name&&this._updateForDisabledAttribute())}},{key:"checked",get:function(){return this._getCheckbox().checked},set:function(value){this._getCheckbox().checked=value,this.checked?this.setAttribute("checked",""):this.removeAttribute("checked"),this._updateForCheckedAttribute()}},{key:"disabled",get:function(){return this._getCheckbox().disabled},set:function(value){this._getCheckbox().disabled=value,this.disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}}]),SwitchElement}(ExtendableLabelElement);window.OnsSwitchElement||(window.OnsSwitchElement=document.registerElement("ons-switch",{prototype:SwitchElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={".tab-bar__content":"tab-bar--*__content",".tab-bar":"tab-bar--*"},AnimatorFactory=ons._internal.AnimatorFactory,TabbarAnimator=ons._internal.TabbarAnimator,TabbarFadeAnimator=ons._internal.TabbarFadeAnimator,TabbarNoneAnimator=ons._internal.TabbarNoneAnimator,TabbarSlideAnimator=ons._internal.TabbarSlideAnimator,ModifierUtil=ons._internal.ModifierUtil,util=ons._util,_animatorDict={"default":TabbarNoneAnimator,fade:TabbarFadeAnimator,slide:TabbarSlideAnimator,none:TabbarNoneAnimator},rewritables={ready:function(tabbarElement,callback){callback()},link:function(tabbarElement,target,callback){callback(target)},unlink:function(tabbarElement,target,callback){callback(target)}},generateId=function(){var i=0;return function(){return"ons-tabbar-gen-"+i++}}(),TabbarElement=function(_ons$_BaseElement){function TabbarElement(){_classCallCheck(this,TabbarElement),_get(Object.getPrototypeOf(TabbarElement.prototype),"constructor",this).apply(this,arguments); }return _inherits(TabbarElement,_ons$_BaseElement),_createClass(TabbarElement,[{key:"createdCallback",value:function(){this._tabbarId=generateId(),this._animatorFactory=new AnimatorFactory({animators:_animatorDict,baseClass:TabbarAnimator,baseClassName:"TabbarAnimator",defaultAnimation:this.getAttribute("animation")}),this._compile(),this._contentElement=ons._util.findChild(this,".tab-bar__content"),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){var wrapper=document.createDocumentFragment(),content=document.createElement("div");content.classList.add("ons-tab-bar__content"),content.classList.add("tab-bar__content");var tabbar=document.createElement("div");for(tabbar.classList.add("tab-bar"),tabbar.classList.add("ons-tab-bar__footer"),tabbar.classList.add("ons-tabbar-inner"),wrapper.appendChild(content),wrapper.appendChild(tabbar);this.childNodes[0];)tabbar.appendChild(this.removeChild(this.childNodes[0]));this.appendChild(wrapper),this._hasTopTabbar()&&this._prepareForTopTabbar()}},{key:"_hasTopTabbar",value:function(){return"top"===this.getAttribute("position")}},{key:"_prepareForTopTabbar",value:function(){var _this=this,content=ons._util.findChild(this,".tab-bar__content"),tabbar=ons._util.findChild(this,".tab-bar");content.setAttribute("no-status-bar-fill",""),content.classList.add("tab-bar--top__content"),tabbar.classList.add("tab-bar--top");var page=ons._util.findParent(this,"ons-page");page&&(this.style.top=window.getComputedStyle(page._getContentElement(),null).getPropertyValue("padding-top")),ons._internal.shouldFillStatusBar(this).then(function(){var fill=_this.querySelector(".tab-bar__status-bar-fill");return fill instanceof HTMLElement?fill:(fill=document.createElement("div"),fill.classList.add("tab-bar__status-bar-fill"),fill.style.width="0px",fill.style.height="0px",_this.insertBefore(fill,_this.children[0]),fill)})["catch"](function(){var el=_this.querySelector(".tab-bar__status-bar-fill");el instanceof HTMLElement&&el.remove()})}},{key:"_getTabbarElement",value:function(){return util.findChild(this,".tab-bar")}},{key:"loadPage",value:function(page,options){return options=options||{},options._removeElement=!0,this._loadPage(page,options)}},{key:"_loadPage",value:function(page,options){var _this2=this;OnsTabElement.prototype._createPageElement(page,function(pageElement){_this2._loadPageDOMAsync(pageElement,options)})}},{key:"_loadPageDOMAsync",value:function(pageElement,options){var _this3=this;options=options||{},rewritables.link(this,pageElement,function(pageElement){_this3._contentElement.appendChild(pageElement),_this3._switchPage(pageElement,options)})}},{key:"getTabbarId",value:function(){return this._tabbarId}},{key:"_getCurrentPageElement",value:function(){for(var pages=this._contentElement.children,page=null,i=0;i<pages.length;i++)if("none"!==pages[i].style.display){page=pages[i];break}if(page&&"ons-page"!==page.nodeName.toLowerCase())throw new Error('Invalid state: page element must be a "ons-page" element.');return page}},{key:"_switchPage",value:function(element,options){if(this._hasTopTabbar()&&element.setAttribute("no-status-bar-fill",""),-1!==this.getActiveTabIndex()){var oldPageElement=this._oldPageElement||ons._internal.nullElement;this._oldPageElement=element;var animator=this._animatorFactory.newAnimator(options);animator.apply(element,oldPageElement,options.selectedTabIndex,options.previousTabIndex,function(){oldPageElement!==ons._internal.nullElement&&(options._removeElement?rewritables.unlink(this,oldPageElement,function(pageElement){oldPageElement._destroy()}):(oldPageElement.style.display="none",oldPageElement._hide())),element.style.display="block",element._show(),options.callback instanceof Function&&options.callback()})}else options.callback instanceof Function&&options.callback()}},{key:"setActiveTab",value:function(index,options){var _this4=this;options=options||{},options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var previousTab=this._getActiveTabElement(),selectedTab=this._getTabElement(index),previousTabIndex=this.getActiveTabIndex(),selectedTabIndex=index;if(!selectedTab)return!1;if((selectedTab.hasAttribute("no-reload")||selectedTab.isPersistent())&&index===previousTabIndex)return util.triggerElementEvent(this,"reactive",{index:index,tabItem:selectedTab}),!1;var canceled=!1;if(util.triggerElementEvent(this,"prechange",{index:index,tabItem:selectedTab,cancel:function(){return canceled=!0}}),canceled)return selectedTab.setInactive(),previousTab&&previousTab.setActive(),!1;selectedTab.setActive();var needLoad=!selectedTab.isLoaded()&&!options.keepPage;if(util.arrayFrom(this._getTabbarElement().children).forEach(function(tab){tab!=selectedTab?tab.setInactive():needLoad||util.triggerElementEvent(_this4,"postchange",{index:index,tabItem:selectedTab})}),needLoad){var removeElement=!0;previousTab&&previousTab.isPersistent()&&(removeElement=!1);var params={callback:function(){util.triggerElementEvent(_this4,"postchange",{index:index,tabItem:selectedTab}),options.callback instanceof Function&&options.callback()},previousTabIndex:previousTabIndex,selectedTabIndex:selectedTabIndex,_removeElement:removeElement};if(options.animation&&(params.animation=options.animation),selectedTab.isPersistent()){var link=function(element,callback){rewritables.link(_this4,element,callback)};selectedTab._loadPageElement(function(pageElement){_this4._loadPersistentPageDOM(pageElement,params)},link)}else this._loadPage(selectedTab.getAttribute("page"),params)}return!0}},{key:"_loadPersistentPageDOM",value:function(element,options){options=options||{},util.isAttached(element)||this._contentElement.appendChild(element),this._switchPage(element,options)}},{key:"setTabbarVisibility",value:function(visible){this._contentElement.style[this._hasTopTabbar()?"top":"bottom"]=visible?"":"0px",this._getTabbarElement().style.display=visible?"":"none"}},{key:"getActiveTabIndex",value:function(){for(var tabs=this._getTabbarElement().children,i=0;i<tabs.length;i++)if(tabs[i]instanceof window.OnsTabElement&&tabs[i].isActive&&tabs[i].isActive())return i;return-1}},{key:"_getActiveTabElement",value:function(){return this._getTabElement(this.getActiveTabIndex())}},{key:"_getTabElement",value:function(index){return this._getTabbarElement().children[index]}},{key:"detachedCallback",value:function(){}},{key:"attachedCallback",value:function(){}},{key:"_show",value:function(){var currentPageElement=this._getCurrentPageElement();currentPageElement&&currentPageElement._show()}},{key:"_hide",value:function(){var currentPageElement=this._getCurrentPageElement();currentPageElement&&currentPageElement._hide()}},{key:"_destroy",value:function(){for(var pages=this._contentElement.children,i=pages.length-1;i>=0;i--)pages[i]._destroy();this.remove()}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),TabbarElement}(ons._BaseElement);window.OnsTabbarElement||(window.OnsTabbarElement=document.registerElement("ons-tabbar",{prototype:TabbarElement.prototype}),window.OnsTabbarElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof TabbarAnimator))throw new Error('"Animator" param must inherit TabbarAnimator');_animatorDict[name]=Animator},window.OnsTabbarElement.rewritables=rewritables)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"toolbar-button--*"},ModifierUtil=ons._internal.ModifierUtil,ToolbarButtonElement=function(_ons$_BaseElement){function ToolbarButtonElement(){_classCallCheck(this,ToolbarButtonElement),_get(Object.getPrototypeOf(ToolbarButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ToolbarButtonElement,_ons$_BaseElement),_createClass(ToolbarButtonElement,[{key:"createdCallback",value:function(){this.classList.add("toolbar-button"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ToolbarButtonElement}(ons._BaseElement);window.OnsToolbarButton||(window.OnsToolbarButton=document.registerElement("ons-toolbar-button",{prototype:ToolbarButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;if(void 0===getter)return;return getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return;_x=parent,_x2=property,_x3=receiver,_again=!0,desc=parent=void 0}};!function(){"use strict";var scheme={"":"navigation-bar--*",".navigation-bar__left":"navigation-bar--*__left",".navigation-bar__center":"navigation-bar--*__center",".navigation-bar__right":"navigation-bar--*__right"},ModifierUtil=ons._internal.ModifierUtil,ToolbarElement=function(_ons$_BaseElement){function ToolbarElement(){_classCallCheck(this,ToolbarElement),_get(Object.getPrototypeOf(ToolbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ToolbarElement,_ons$_BaseElement),_createClass(ToolbarElement,[{key:"createdCallback",value:function(){var _this=this;this._compile(),ModifierUtil.initModifier(this,scheme),this._tryToEnsureNodePosition(),setImmediate(function(){return _this._tryToEnsureNodePosition()})}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){var _this2=this;this._tryToEnsureNodePosition(),setImmediate(function(){return _this2._tryToEnsureNodePosition()})}},{key:"_tryToEnsureNodePosition",value:function(){if(this.parentNode&&!this.hasAttribute("inline")&&"ons-page"!==this.parentNode.nodeName.toLowerCase()){for(var page=this;;){if(page=page.parentNode,!page)return;if("ons-page"===page.nodeName.toLowerCase())break}page._registerToolbar(this)}}},{key:"_getToolbarLeftItemsElement",value:function(){return this.querySelector(".left")||ons._internal.nullElement}},{key:"_getToolbarCenterItemsElement",value:function(){return this.querySelector(".center")||ons._internal.nullElement}},{key:"_getToolbarRightItemsElement",value:function(){return this.querySelector(".right")||ons._internal.nullElement}},{key:"_getToolbarBackButtonLabelElement",value:function(){return this.querySelector("ons-back-button .back-button__label")||ons._internal.nullElement}},{key:"_compile",value:function(){var inline=this.hasAttribute("inline");this.classList.add("navigation-bar"),inline||(this.style.position="absolute",this.style.zIndex="10000",this.style.left="0px",this.style.right="0px",this.style.top="0px"),this._ensureToolbarItemElements()}},{key:"_ensureToolbarItemElements",value:function(){for(var center,hasCenterClassElementOnly=1===this.children.length&&this.children[0].classList.contains("center"),i=0;i<this.childNodes.length;i++)1!=this.childNodes[i].nodeType&&this.removeChild(this.childNodes[i]);if(hasCenterClassElementOnly)center=this._ensureToolbarItemContainer("center");else{center=this._ensureToolbarItemContainer("center");var left=this._ensureToolbarItemContainer("left"),right=this._ensureToolbarItemContainer("right");if(this.children[0]!==left||this.children[1]!==center||this.children[2]!==right){left.parentNode&&this.removeChild(left),center.parentNode&&this.removeChild(center),right.parentNode&&this.removeChild(right);var fragment=document.createDocumentFragment();fragment.appendChild(left),fragment.appendChild(center),fragment.appendChild(right),this.appendChild(fragment)}}center.classList.add("navigation-bar__title")}},{key:"_ensureToolbarItemContainer",value:function(name){var container=ons._util.findChild(this,"."+name);return container||(container=document.createElement("div"),container.classList.add(name)),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),container.classList.add("navigation-bar__"+name),container}}]),ToolbarElement}(ons._BaseElement);window.OnsToolbarElement||(window.OnsToolbarElement=document.registerElement("ons-toolbar",{prototype:ToolbarElement.prototype}))}();
src/parser/rogue/subtlety/modules/talents/FindWeakness.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import Enemies from 'parser/shared/modules/Enemies'; /** * Find Weakness * Your Shadowstrike and Cheap Shot abilities reveal a flaw in your target's defenses, causing all your attacks to bypass 40% of that enemy's armor for 10 sec. */ class FindWeakness extends Analyzer { static dependencies = { enemies: Enemies, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.FIND_WEAKNESS_TALENT.id); } badVanishCasts = 0; on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId === SPELLS.VANISH.id) { this.handleVanish(event); } } latestTs = 0; on_byPlayer_refreshdebuff(event) { const spellId = event.ability.guid; if (spellId === SPELLS.FIND_WEAKNESS_BUFF.id) { this.latestTs = event.timestamp; } } handleVanish(event) { const entities = this.enemies.getEntities(); const hasDebuff = Object.values(entities) .filter(enemy => enemy.hasBuff(SPELLS.FIND_WEAKNESS_BUFF.id)) .map(enemy => enemy.getBuff(SPELLS.FIND_WEAKNESS_BUFF.id).timestamp); //For now does not support target switching, just makes sure that enough time has passed since the last application if(Math.max(...hasDebuff, this.latestTs) > event.timestamp - 8000) { this.badVanishCasts++; event.meta = event.meta || {}; event.meta.isInefficientCast = true; event.meta.inefficientCastReason = `Use Vanish only when Find Weakness is not up or is about to run out.`; } } get vanishThresholds() { return { actual: this.badVanishCasts, isGreaterThan: { minor: 0, average: 0, major: 0, }, style: 'number', }; } suggestions(when) { when(this.vanishThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Use <SpellLink id={SPELLS.VANISH.id} /> only when you do not have <SpellLink id={SPELLS.FIND_WEAKNESS_TALENT.id} /> applied to your target </>) .icon(SPELLS.VANISH.icon) .actual(`You used Vanish ${this.badVanishCasts} times when Find Weakness was already applied`) .recommended(`${recommended} is recommended`); }); } statistic() { const uptime = this.enemies.getBuffUptime(SPELLS.FIND_WEAKNESS_BUFF.id) / this.owner.fightDuration; return ( <StatisticBox position={STATISTIC_ORDER.OPTIONAL(40)} icon={<SpellIcon id={SPELLS.FIND_WEAKNESS_TALENT.id} />} value={`${formatPercentage(uptime)} %`} label={`${SPELLS.FIND_WEAKNESS_TALENT.name} uptime`} /> ); } } export default FindWeakness;
examples/decorators/form/index.js
stackscz/re-app
import React from 'react'; import WildForm from './ExampleForm'; import Example from 're-app-examples/Example'; const codeFiles = [ { name: 'ExampleForm.js', content: require('!!raw!./ExampleForm.js'), description: 'ExampleForm', }, { name: './PaperOrientationInput.js', content: require('!!raw!./PaperOrientationInput.js'), description: 'PaperOrientationInput', }, { name: 'schema.json', content: require('!!raw!./schema.json'), description: 'Schema', }, ]; export default () => <Example readme={require('!!raw!./README.md')} codeFiles={codeFiles} sourcePath="decorators/form" > <WildForm /> </Example>;
src/components/overview/impress.js
abbr/ShowPreper
import React from 'react' import './impress.less' import AutoScale from 'components/mixins/autoScale' import Draggable from 'components/mixins/draggable' import Scalable from 'components/mixins/scalable' import Selectable from 'components/mixins/selectable' import Rotatable from 'components/mixins/rotatable' import Killable from 'components/mixins/killable' import { langs } from 'i18n/lang' import _ from 'lodash' var EditableComponent = require('components/widgets/editableComponent') module.exports = class extends Draggable.draggableMixin( Rotatable.rotatableMixin( Scalable.scalableMixin( Killable.killableMixin( Selectable.selectableMixin(AutoScale.autoScaleMixin(React.Component)) ) ) ), function getSelectedWidgets() { return this.props.selectedWidgets }, function getInitialWidgetPosition(e) { let bb = this.props.deck.getSlideBoundingBox( this.props.component.components[e] ) return { x: this.props.component.components[e].x || bb.left || 0, y: this.props.component.components[e].y || bb.top || 0, z: this.props.component.components[e].z || 0 } }, function mouseMoveWidgetUpdateFunction(e, updatedProps) { this.props.onSelectedWidgetUpdated && this.props.onSelectedWidgetUpdated( { container: this.props.component, index: e }, updatedProps ) }, function mouseUpWidgetUpdateFunction(e, updatedProps) { this.props.onSelectedWidgetUpdated && this.props.onSelectedWidgetUpdated( { container: this.props.component, index: e }, updatedProps, langs[this.props.language].moveComponents ) } ) { constructor(props) { super(props) this.state = { draggable: true } } UNSAFE_componentWillMount() { super.UNSAFE_componentWillMount && super.UNSAFE_componentWillMount() this.mouseDownHdlrs = [] } componentDidMount() { super.componentDidMount && super.componentDidMount() this._resized() window.addEventListener('resize', this._windowResized) } componentWillUnmount() { super.componentWillUnmount && super.componentWillUnmount() window.removeEventListener('resize', this._windowResized) } _windowResized = () => { this._resized(true) } _resized = recomputeDomSize => { let bb = this.props.deck.boundingBox || this.props.deck.getDefaultDeckBoundingBox() let newBB = this._scale(bb, recomputeDomSize) if (newBB) { this.props.onSelectedWidgetUpdated( { container: this.props.deck, index: -1 }, { boundingBox: newBB } ) } } zoom(pct) { let bb = this.props.deck.boundingBox || this.props.deck.getDefaultDeckBoundingBox() let width = bb.right - bb.left let height = bb.bottom - bb.top let cx = bb.left + width / 2 let cy = bb.top + height / 2 let newWidth = width * (1 + pct) let newHeight = height * (1 + pct) let newLeft = cx - newWidth / 2 let newRight = cx + newWidth / 2 let newTop = cy - newHeight / 2 let newBottom = cy + newHeight / 2 let newBB = { top: newTop, right: newRight, bottom: newBottom, left: newLeft } this.props.onSelectedWidgetUpdated( { container: this.props.deck, index: -1 }, { boundingBox: newBB } ) this._resized() } zoomIn = () => { this.zoom(-0.1) this.zoomInTimer = setInterval(() => this.zoom(-0.1), 100) } stopZoomIn = () => { clearInterval(this.zoomInTimer) } zoomOut = () => { this.zoom(0.1) this.zoomOutTimer = setInterval(() => this.zoom(0.1), 100) } stopZoomOut = () => { clearInterval(this.zoomOutTimer) } onMouseDown = (...args) => { this.mouseDownHdlrs.forEach( function(e) { e.apply(this, args) }.bind(this) ) } setDraggable = draggable => { this.setState({ draggable: draggable }) } render() { let selectedWidgets = this.props.deck.components.reduce((pv, e, i) => { if (e.selected) pv.push(i) return pv }, []) let deckView = this.props.deck.components.map((e, index) => { let component = _.cloneDeep(e) if (e.type === 'Slide') { let bb = this.props.deck.getSlideBoundingBox(e) component.y = bb.top component.x = bb.left component.width = bb.right - bb.left component.height = bb.bottom - bb.top } return ( <EditableComponent componentStyle={ (selectedWidgets.indexOf(index) >= 0 ? this.props.selectedSlidesStyle : null) || component.style || this.props.defaultSlideStyle || this.props.deck.defaultSlideStyle || {} } className="sp-overview-component" component={component} container={this.props.deck} language={this.props.language} key={index} idx={index} ref={index} scale={this.state.scale} selected={selectedWidgets.indexOf(index) >= 0} onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} onScaleMouseDown={this.onScaleMouseDown} onRotateMouseDown={this.onRotateMouseDown} onKillMouseDown={this.onKillMouseDown} onSelectedWidgetUpdated={this.props.onSelectedWidgetUpdated} setDraggable={this.setDraggable} /> ) }) let deckStyle = _.clone(this.state.scaleStyle) if (deckStyle && this.props.deck.perspective) { deckStyle.perspective = this.props.deck.perspective / (this.state.scale || 1) + 'px' } return ( <div onMouseDown={this.onSelectionMouseDown} className="sp-overview" style={this.props.presentationStyle || this.props.deck.style} > <span className="glyphicon glyphicon-zoom-in" onMouseDown={this.zoomIn} onMouseUp={this.stopZoomIn} /> <span className="glyphicon glyphicon-zoom-out" onMouseDown={this.zoomOut} onMouseUp={this.stopZoomOut} /> <div className="sp-overview-deck" style={deckStyle}> {deckView} </div> </div> ) } }
src/components/filter.js
menthena/project-a
import React from 'react'; const Filter = ({ labelText, placeholder, handleOnChange, value }) => ( <div className="filter"> <label>{labelText}</label> <input type="text" onChange={(event) => { handleOnChange(event.target.value); }} placeholder={placeholder} value={value} /> </div> ); export default Filter;
src/Components/Modal/index.js
gabriel-lopez-lopez/gll-billin-code-challenge
/** * Componente que crea ventana modales apoyandose en Bootstrap y jQuery * :( Not like * */ /*global $*/ import React, { Component } from 'react'; import { PropTypes } from 'prop-types'; // Estilos personalizados import './modal.less'; class Modal extends Component { constructor(props){ super(props); this.state = { modal: '' }; this.handleSuccess = this.handleSuccess.bind(this); this.handleCancel = this.handleCancel.bind(this); this.handleUpdate = this.handleUpdate.bind(this); } handleCancel() { this.props.handleCancel(); } handleSuccess() { $('#' + this.props.id + '.modal').modal('hide'); this.props.handleSuccess(); } componentDidMount() { let isConfirm = this.props.confirm || false, _modal = $('#' + this.props.id + '.modal'); this.state.modal = _modal; if (isConfirm) { _modal.find('.modal-dialog').addClass('modal-sm'); } } show () { this.state.modal.modal(); } hide () { this.state.modal.modal('hide'); } handleUpdate () { this.state.modal.modal('handleUpdate'); this.props.handleUpdate(); } render () { return ( <div id={this.props.id} className="modal fade" tabIndex="-1" role="dialog"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" onClick={this.handleCancel} aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 className="modal-title">{this.props.title}</h4> </div> <div className="modal-body"> {this.props.children} </div> <div className="modal-footer"> <button type="button" className={'btn btn-default ' + this.props.classBtnCancel} data-dismiss="modal" onClick={this.handleCancel}>{(this.props.labelBtnCancel) ? this.props.labelBtnCancel : 'Cancelar'}</button> <button type="button" className={'btn btn-primary ' + this.props.classBtnSuccess} onClick={this.handleSuccess}>{(this.props.labelBtnSuccess) ? this.props.labelBtnSuccess : 'Aceptar'}</button> </div> </div> </div> </div> ); } } Modal.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, confirm: PropTypes.bool, classBtnCancel: PropTypes.string, classBtnSuccess: PropTypes.string, labelBtnCancel: PropTypes.string, labelBtnSuccess: PropTypes.string, handleCancel: PropTypes.func, handleSuccess: PropTypes.func.isRequired, handleUpdate: PropTypes.func }; export default Modal;
app/components/Footer/index.js
j921216063/chenya
import React from 'react'; import Wrapper from './Wrapper'; import Icons from './Icons'; import Copyright from './Copyright'; function Footer() { return ( <Wrapper> <Icons /> <Copyright /> </Wrapper> ); } export default Footer;
extensions/amp-inline-gallery/1.0/base-element.js
nexxtv/amphtml
/** * Copyright 2021 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 * as Preact from '../../../src/preact'; import {CarouselContextProp} from '../../amp-base-carousel/1.0/carousel-props'; import {InlineGallery} from './component'; import {PreactBaseElement} from '../../../src/preact/base-element'; import {dict} from '../../../src/core/types/object'; import {setProp} from '../../../src/context'; import {useContext, useLayoutEffect} from '../../../src/preact'; export class BaseElement extends PreactBaseElement { /** @override */ init() { return dict({ 'children': <ContextExporter shimDomElement={this.element} />, }); } } /** @override */ BaseElement['Component'] = InlineGallery; /** @override */ BaseElement['detached'] = true; /** @override */ BaseElement['props'] = { 'loop': {attr: 'loop', type: 'boolean'}, }; /** * @param {!SelectorDef.OptionProps} props * @return {PreactDef.Renderable} */ function ContextExporter({shimDomElement}) { // Consume the `CarouselContext` produced by the `InlineGallery` component // and propagate it as a context prop. const context = useContext(CarouselContextProp.type); useLayoutEffect(() => { setProp(shimDomElement, CarouselContextProp, ContextExporter, context); }, [shimDomElement, context]); return <></>; }
gulpfile.js
satococoa/react-firebase-chat
/** * * Web Starter Kit * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 * */ 'use strict'; // Include Gulp & Tools We'll Use var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var del = require('del'); var runSequence = require('run-sequence'); var browserSync = require('browser-sync'); var pagespeed = require('psi'); var reload = browserSync.reload; var react = require('gulp-react'); var AUTOPREFIXER_BROWSERS = [ 'ie >= 10', 'ie_mob >= 10', 'ff >= 30', 'chrome >= 34', 'safari >= 7', 'opera >= 23', 'ios >= 7', 'android >= 4.4', 'bb >= 10' ]; // Lint JavaScript gulp.task('jshint', function () { return gulp.src('app/scripts/**/*.js') .pipe(reload({stream: true, once: true})) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')) .pipe($.if(!browserSync.active, $.jshint.reporter('fail'))); }); // Optimize Images gulp.task('images', function () { return gulp.src('app/images/**/*') .pipe($.cache($.imagemin({ progressive: true, interlaced: true }))) .pipe(gulp.dest('dist/images')) .pipe($.size({title: 'images'})); }); // Copy All Files At The Root Level (app) gulp.task('copy', function () { return gulp.src([ 'app/*', '!app/*.html', 'node_modules/apache-server-configs/dist/.htaccess' ], { dot: true }).pipe(gulp.dest('dist')) .pipe($.size({title: 'copy'})); }); // Copy Web Fonts To Dist gulp.task('fonts', function () { return gulp.src(['app/fonts/**']) .pipe(gulp.dest('dist/fonts')) .pipe($.size({title: 'fonts'})); }); // Compile and Automatically Prefix Stylesheets gulp.task('styles', function () { // For best performance, don't add Sass partials to `gulp.src` return gulp.src([ 'app/styles/*.scss', 'app/styles/**/*.css', 'app/styles/components/components.scss' ]) .pipe($.changed('styles', {extension: '.scss'})) .pipe($.rubySass({ style: 'expanded', precision: 10, bundleExec: true })) .on('error', console.error.bind(console)) .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS})) .pipe(gulp.dest('.tmp/styles')) // Concatenate And Minify Styles .pipe($.if('*.css', $.csso())) .pipe(gulp.dest('dist/styles')) .pipe($.size({title: 'styles'})); }); gulp.task('react', function () { return gulp.src('app/**/*.jsx') .pipe(react()) .pipe(gulp.dest('.tmp')) .pipe(gulp.dest('dist')); }); // Scan Your HTML For Assets & Optimize Them gulp.task('html', function () { var assets = $.useref.assets({searchPath: '{.tmp,app}'}); return gulp.src('app/**/*.html') .pipe(assets) // Concatenate And Minify JavaScript .pipe($.if('*.js', $.uglify({preserveComments: 'some'}))) // Remove Any Unused CSS // Note: If not using the Style Guide, you can delete it from // the next line to only include styles your project uses. .pipe($.if('*.css', $.uncss({ html: [ 'app/index.html', 'app/styleguide.html' ], // CSS Selectors for UnCSS to ignore ignore: [ /.navdrawer-container.open/, /.app-bar.open/ ] }))) // Concatenate And Minify Styles // In case you are still using useref build blocks .pipe($.if('*.css', $.csso())) .pipe(assets.restore()) .pipe($.useref()) // Update Production Style Guide Paths .pipe($.replace('components/components.css', 'components/main.min.css')) // Minify Any HTML .pipe($.if('*.html', $.minifyHtml())) // Output Files .pipe(gulp.dest('dist')) .pipe($.size({title: 'html'})); }); // Clean Output Directory gulp.task('clean', del.bind(null, ['.tmp', 'dist'])); // Watch Files For Changes & Reload gulp.task('serve', ['styles', 'react'], function () { browserSync({ notify: false, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: ['.tmp', 'app'] }); gulp.watch(['app/**/*.html'], reload); gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]); gulp.watch(['app/scripts/**/*.jsx'], ['react', reload]); gulp.watch(['app/scripts/**/*.js'], ['jshint']); gulp.watch(['app/images/**/*'], reload); }); // Build and serve the output from the dist build gulp.task('serve:dist', ['default'], function () { browserSync({ notify: false, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: 'dist' }); }); // Build Production Files, the Default Task gulp.task('default', ['clean'], function (cb) { runSequence('styles', 'react', ['html', 'images', 'fonts', 'copy'], cb); }); // Run PageSpeed Insights // Update `url` below to the public URL for your site gulp.task('pagespeed', pagespeed.bind(null, { // By default, we use the PageSpeed Insights // free (no API key) tier. You can use a Google // Developer API key if you have one. See // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY' url: 'https://example.com', strategy: 'mobile' })); // Load custom tasks from the `tasks` directory try { require('require-dir')('tasks'); } catch (err) {}
docs/src/app/components/pages/components/List/ExampleNested.js
kittyjumbalaya/material-components-web
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import ActionGrade from 'material-ui/svg-icons/action/grade'; import ContentInbox from 'material-ui/svg-icons/content/inbox'; import ContentDrafts from 'material-ui/svg-icons/content/drafts'; import ContentSend from 'material-ui/svg-icons/content/send'; import Subheader from 'material-ui/Subheader'; import Toggle from 'material-ui/Toggle'; export default class ListExampleNested extends React.Component { state = { open: false, }; handleToggle = () => { this.setState({ open: !this.state.open, }); }; handleNestedListToggle = (item) => { this.setState({ open: item.state.open, }); }; render() { return ( <div> <Toggle toggled={this.state.open} onToggle={this.handleToggle} labelPosition="right" label="This toggle controls the expanded state of the submenu item." /> <br /> <MobileTearSheet> <List> <Subheader>Nested List Items</Subheader> <ListItem primaryText="Sent mail" leftIcon={<ContentSend />} /> <ListItem primaryText="Drafts" leftIcon={<ContentDrafts />} /> <ListItem primaryText="Inbox" leftIcon={<ContentInbox />} initiallyOpen={true} primaryTogglesNestedList={true} nestedItems={[ <ListItem key={1} primaryText="Starred" leftIcon={<ActionGrade />} />, <ListItem key={2} primaryText="Sent Mail" leftIcon={<ContentSend />} disabled={true} nestedItems={[ <ListItem key={1} primaryText="Drafts" leftIcon={<ContentDrafts />} />, ]} />, <ListItem key={3} primaryText="Inbox" leftIcon={<ContentInbox />} open={this.state.open} onNestedListToggle={this.handleNestedListToggle} nestedItems={[ <ListItem key={1} primaryText="Drafts" leftIcon={<ContentDrafts />} />, ]} />, ]} /> </List> </MobileTearSheet> </div> ); } }
packages/material-ui-icons/src/LocationOnSharp.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" /></g></React.Fragment> , 'LocationOnSharp');
src/slide.js
zymokey/react-carousel
import React from 'react'; export default class Slide extends React.Component { getSlideStyle(){ if(this.props.fade){ return this.props.curStyle ? 'caros-slide-fade curSlide-fade' : 'caros-slide-fade'; } else { return 'caros-slide'; } } render(){ return( <div className={this.getSlideStyle()}> <img src={this.props.imgsrc} /> </div> ); } }
src/svg-icons/notification/phone-bluetooth-speaker.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPhoneBluetoothSpeaker = (props) => ( <SvgIcon {...props}> <path d="M14.71 9.5L17 7.21V11h.5l2.85-2.85L18.21 6l2.15-2.15L17.5 1H17v3.79L14.71 2.5l-.71.71L16.79 6 14 8.79l.71.71zM18 2.91l.94.94-.94.94V2.91zm0 4.3l.94.94-.94.94V7.21zm2 8.29c-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.59l2.2-2.21c.28-.26.36-.65.25-1C8.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-1z"/> </SvgIcon> ); NotificationPhoneBluetoothSpeaker = pure(NotificationPhoneBluetoothSpeaker); NotificationPhoneBluetoothSpeaker.displayName = 'NotificationPhoneBluetoothSpeaker'; NotificationPhoneBluetoothSpeaker.muiName = 'SvgIcon'; export default NotificationPhoneBluetoothSpeaker;
src/components/ContextMenuPopupTrigger.js
dahel/react-context-menu-popup
import React from 'react'; class ContextMenuPopupTrigger extends React.Component { render() { return ( <div className={this.getClassName()} onClick={this.handleClick.bind(this)} style={this.props.style} >{this.props.children}</div> ) } getClassName() { return this.props.className || 'context-menu-popup__trigger'; } handleClick() { if (this.props.customOnClickHandler) { this.props.customOnClickHandler(this.props.contextMenuPopup); } else { this.props.onClick(); } } } export default ContextMenuPopupTrigger;
src/main/resources/test/components/saiku/Wrapper.spec.js
OSBI/meteorite-core-ui
/** * Copyright 2016 OSBI Ltd * * 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 React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ReactDOM from 'react-dom'; import Wrapper from '../../../src/js/components/saiku/Wrapper'; describe('Wrapper', () => { it('uses "div" by default', () => { let component = ReactTestUtils.renderIntoDocument( <Wrapper>Wrapper content</Wrapper> ); assert.equal(ReactDOM.findDOMNode(component).nodeName, 'DIV'); }); it('has "wrapper" class by default', () => { let component = ReactTestUtils.renderIntoDocument( <Wrapper>Wrapper content</Wrapper> ); assert.equal(ReactDOM.findDOMNode(component).className, 'wrapper'); }); it('Should have "wrapper-page" class name if props is `page`', () => { let component = ReactTestUtils.renderIntoDocument( <Wrapper page>Wrapper content</Wrapper> ); assert.equal(ReactDOM.findDOMNode(component).className, 'wrapper-page'); }); it('Should have "wrapper" class names if props ' + 'is `isOpenSidebar` equals the true', () => { let component = ReactTestUtils.renderIntoDocument( <Wrapper isOpenSidebar>Wrapper content</Wrapper> ); let componentClassName = ReactDOM.findDOMNode(component).className; assert.ok(componentClassName.match(/\bwrapper\b/)); }); it('Should have "smaller forced" class names ' + 'if props is `isOpenSidebar` equals the false', () => { let component = ReactTestUtils.renderIntoDocument( <Wrapper isOpenSidebar={false}>Wrapper content</Wrapper> ); let componentClassName = ReactDOM.findDOMNode(component).className; assert.ok(componentClassName.match(/\bwrapper\b/)); assert.ok(componentClassName.match(/\bsmaller\b/)); assert.ok(componentClassName.match(/\bforced\b/)); }); it('Should merge additional classes', () => { let component = ReactTestUtils.renderIntoDocument( <Wrapper className="foo">Wrapper content</Wrapper> ); let componentClassName = ReactDOM.findDOMNode(component).className; assert.ok(componentClassName.match(/\bwrapper\b/)); assert.ok(componentClassName.match(/\bfoo\b/)); }); });
app/components/Header/index.js
kossel/react-boilerplate
import React from 'react'; import { FormattedMessage } from 'react-intl'; import A from './A'; import Img from './Img'; import NavBar from './NavBar'; import HeaderLink from './HeaderLink'; import Banner from './banner.jpg'; import messages from './messages'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <A href="https://twitter.com/mxstbr"> <Img src={Banner} alt="react-boilerplate - Logo" /> </A> <NavBar> <HeaderLink to="/"> <FormattedMessage {...messages.home} /> </HeaderLink> <HeaderLink to="/features"> <FormattedMessage {...messages.features} /> </HeaderLink> </NavBar> </div> ); } } export default Header;
ui/src/js/password/forgotPassword/SendRequest.js
Dica-Developer/weplantaforest
import axios from 'axios'; import counterpart from 'counterpart'; import React, { Component } from 'react'; import IconButton from '../../common/components/IconButton'; import InputText from '../../common/components/InputText'; import Notification from '../../common/components/Notification'; export default class SendRequest extends Component { constructor() { super(); this.state = { name: '' }; } updateValue(toUpdate, value) { this.setState({ [toUpdate]: value }); } sendPasswortResetMail() { if (this.state.name != '') { var that = this; axios .post('http://localhost:8081/password_request?userName=' + encodeURIComponent(this.state.name) + '&language=' + localStorage.getItem('language')) .then(function(response) { that.props.setResetted(); }) .catch(function(error) { that.refs.notification.handleError(error); }); } else { this.refs.notification.addNotification(counterpart.translate('NO_USERNAME.TITLE'), counterpart.translate('NO_USERNAME.TEXT'), 'error'); } } render() { return ( <div className="col-md-12"> <h1>{counterpart.translate('PASSWORD_FORGOT')}</h1> <div className="form"> {counterpart.translate('PASSWORD_FORGOT_TEXT')} <br /> <InputText toUpdate="name" updateValue={this.updateValue.bind(this)} /> <br /> <IconButton text={counterpart.translate('SEND_PASSWORD_RESET_MAIL')} glyphIcon="glyphicon-envelope" onClick={this.sendPasswortResetMail.bind(this)} /> </div> <Notification ref="notification" /> </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
docs/app/Examples/modules/Checkbox/Types/index.js
Rohanhacker/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import { Message } from 'semantic-ui-react' const CheckboxTypesExamples = () => ( <ExampleSection title='Types'> <Message info> All checkbox types use an input with type <code>checkbox</code>, except for type <code>radio</code>. {' '}Use <code>inputType</code> if you'd like to mix and match style and behavior. {' '}For instance, type <code>slider</code> with <code>inputType</code> radio for exclusive sliders. </Message> <ComponentExample title='Checkbox' description='A box for checking.' examplePath='modules/Checkbox/Types/CheckboxExampleCheckbox' /> <ComponentExample description='You can define a label with a props object.' examplePath='modules/Checkbox/Types/CheckboxExampleShorthandObject' /> <ComponentExample description='You can define a label by passing your own element.' examplePath='modules/Checkbox/Types/CheckboxExampleShorthandElement' /> <ComponentExample title='Toggle' description='A checkbox can toggle.' examplePath='modules/Checkbox/Types/CheckboxExampleToggle' /> <ComponentExample title='Slider' description='A checkbox can look like a slider.' examplePath='modules/Checkbox/Types/CheckboxExampleSlider' /> <ComponentExample title='Radio' description='A checkbox can be formatted as a radio element. This means it is an exclusive option.' examplePath='modules/Checkbox/Types/CheckboxExampleRadio' /> <ComponentExample title='Radio Group' examplePath='modules/Checkbox/Types/CheckboxExampleRadioGroup' > <Message warning> Radios in a group must be <a href='https://facebook.github.io/react/docs/forms.html#controlled-components' target='_blank'> &nbsp;controlled components. </a> </Message> </ComponentExample> </ExampleSection> ) export default CheckboxTypesExamples
examples/universal/client/index.js
zanjs/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
__tests__/index.android.js
TASnomad/Fallon-react-native-app
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
packages/material-ui-icons/src/Filter1.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="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm11 10h2V5h-4v2h2v8zm7-14H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z" /></React.Fragment> , 'Filter1');
bitpig/__tests__/index.android.js
kuncloud/bitcoinHelper
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
app/app/containers/App.js
jonmak08/github-pulls
import React, {Component, PropTypes} from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import * as pageActions from '../actions/page'; import * as updateActions from '../actions/update'; import {setLastUpdateCheck} from '../actions/config'; import UpdateMsg from '../components/UpdateMsg'; const MS_DAY = (24 * 60 * 60 * 1000); class App extends Component { checkForUpdate = () => { var {lastUpdateCheck} = this.props; if (!lastUpdateCheck || Date.now() - lastUpdateCheck >= MS_DAY) { var time = Date.now(); this.props.checkForUpdates(time); this.props.setLastUpdateCheck(time); } } componentWillReceiveProps(nextProps) { if (nextProps.updateLater) { clearTimeout(this.timeout); } } componentDidMount() { this.checkForUpdate(); } componentWillUnmount() { window.removeEventListener('online', this.handleOffline); window.removeEventListener('offline', this.handleOffline); clearInterval(this.timeout); } componentWillMount() { window.addEventListener('online', this.handleOffline); window.addEventListener('offline', this.handleOffline); this.handleOffline(); this.timeout = setInterval( this.checkForUpdate, MS_DAY ); } handleOffline = (e) => { this.props.pageOnline(navigator.onLine); } render() { var { currentVersion, downloadNewVersion, remindMeLater, updateAvailable, updateLater, } = this.props; var updateMsg = null; var className = ''; if (updateAvailable && !updateLater) { updateMsg = <UpdateMsg currentVersion={currentVersion} downloadNewVersion={downloadNewVersion} newVersion={updateAvailable.name} remindMeLater={remindMeLater} {...this.props} />; className = 'has-update'; } return ( <div className={className}> {updateMsg} {this.props.children} { (() => { let retVal; if (process.env.NODE_ENV !== 'production') { const DevTools = require('./DevTools'); retVal = <DevTools />; } return retVal; })() } </div> ); } } App.propTypes = { children: PropTypes.element.isRequired }; function mapStateToProps(state) { return Object.assign({}, state); } let mapDispatchToProps = bindActionCreators.bind(null, {...pageActions, ...updateActions, setLastUpdateCheck}); export default connect(mapStateToProps, mapDispatchToProps)(App);
ajax/libs/handsontable/0.10.3/jquery.handsontable.full.js
hasantayyar/cdnjs
/** * Handsontable 0.10.3 * Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs * * Copyright 2012, Marcin Warpechowski * Licensed under the MIT license. * http://handsontable.com/ * * Date: Mon Feb 10 2014 14:15:11 GMT+0100 (CET) */ /*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */ var Handsontable = { //class namespace extension: {}, //extenstion namespace helper: {} //helper namespace }; (function ($, window, Handsontable) { "use strict"; //http://stackoverflow.com/questions/3629183/why-doesnt-indexof-work-on-an-array-ie8 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } /** * Array.filter() shim by Trevor Menagh (https://github.com/trevmex) with some modifications */ if (!Array.prototype.filter) { Array.prototype.filter = function (fun, thisp) { "use strict"; if (typeof this === "undefined" || this === null) { throw new TypeError(); } if (typeof fun !== "function") { throw new TypeError(); } thisp = thisp || this; if (isNodeList(thisp)) { thisp = convertNodeListToArray(thisp); } var len = thisp.length, res = [], i, val; for (i = 0; i < len; i += 1) { if (thisp.hasOwnProperty(i)) { val = thisp[i]; // in case fun mutates this if (fun.call(thisp, val, i, thisp)) { res.push(val); } } } return res; function isNodeList(object) { return /NodeList/i.test(object.item); } function convertNodeListToArray(nodeList) { var array = []; for (var i = 0, len = nodeList.length; i < len; i++){ array[i] = nodeList[i] } return array; } }; } /* * Copyright 2012 The Polymer Authors. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ if (typeof WeakMap === 'undefined') { (function() { var defineProperty = Object.defineProperty; try { var properDefineProperty = true; defineProperty(function(){}, 'foo', {}); } catch (e) { properDefineProperty = false; } /* IE8 does not support Date.now() but IE8 compatibility mode in IE9 and IE10 does. M$ deserves a high five for this one :) */ var counter = +(new Date) % 1e9; var WeakMap = function() { this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__'); if(!properDefineProperty){ this._wmCache = []; } }; if(properDefineProperty){ WeakMap.prototype = { set: function(key, value) { var entry = key[this.name]; if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, {value: [key, value], writable: true}); }, get: function(key) { var entry; return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined; }, 'delete': function(key) { this.set(key, undefined); } }; } else { WeakMap.prototype = { set: function(key, value) { if(typeof key == 'undefined' || typeof value == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ this._wmCache[i].value = value; return; } } this._wmCache.push({key: key, value: value}); }, get: function(key) { if(typeof key == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ return this._wmCache[i].value; } } return; }, 'delete': function(key) { if(typeof key == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ Array.prototype.slice.call(this._wmCache, i, 1); } } } }; } window.WeakMap = WeakMap; })(); } Handsontable.activeGuid = null; /** * Handsontable constructor * @param rootElement The jQuery element in which Handsontable DOM will be inserted * @param userSettings * @constructor */ Handsontable.Core = function (rootElement, userSettings) { var priv , datamap , grid , selection , editorManager , autofill , instance = this , GridSettings = function () {}; Handsontable.helper.extend(GridSettings.prototype, DefaultSettings.prototype); //create grid settings as a copy of default settings Handsontable.helper.extend(GridSettings.prototype, userSettings); //overwrite defaults with user settings Handsontable.helper.extend(GridSettings.prototype, expandType(userSettings)); this.rootElement = rootElement; var $document = $(document.documentElement); var $body = $(document.body); this.guid = 'ht_' + Handsontable.helper.randomString(); //this is the namespace for global events if (!this.rootElement[0].id) { this.rootElement[0].id = this.guid; //if root element does not have an id, assign a random id } priv = { cellSettings: [], columnSettings: [], columnsSettingConflicts: ['data', 'width'], settings: new GridSettings(), // current settings instance settingsFromDOM: {}, selStart: new Handsontable.SelectionPoint(), selEnd: new Handsontable.SelectionPoint(), isPopulated: null, scrollable: null, extensions: {}, firstRun: true }; grid = { /** * Inserts or removes rows and columns * @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col" * @param {Number} index * @param {Number} amount * @param {String} [source] Optional. Source of hook runner. * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows. */ alter: function (action, index, amount, source, keepEmptyRows) { var delta; amount = amount || 1; switch (action) { case "insert_row": delta = datamap.createRow(index, amount); if (delta) { if (priv.selStart.exists() && priv.selStart.row() >= index) { priv.selStart.row(priv.selStart.row() + delta); selection.transformEnd(delta, 0); //will call render() internally } else { selection.refreshBorders(); //it will call render and prepare methods } } break; case "insert_col": delta = datamap.createCol(index, amount); if (delta) { if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ var spliceArray = [index, 0]; spliceArray.length += delta; //inserts empty (undefined) elements at the end of an array Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); //inserts empty (undefined) elements into the colHeader array } if (priv.selStart.exists() && priv.selStart.col() >= index) { priv.selStart.col(priv.selStart.col() + delta); selection.transformEnd(0, delta); //will call render() internally } else { selection.refreshBorders(); //it will call render and prepare methods } } break; case "remove_row": datamap.removeRow(index, amount); priv.cellSettings.splice(index, amount); grid.adjustRowsAndCols(); selection.refreshBorders(); //it will call render and prepare methods break; case "remove_col": datamap.removeCol(index, amount); for(var row = 0, len = datamap.getAll().length; row < len; row++){ if(row in priv.cellSettings){ //if row hasn't been rendered it wouldn't have cellSettings priv.cellSettings[row].splice(index, amount); } } if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ if(typeof index == 'undefined'){ index = -1; } instance.getSettings().colHeaders.splice(index, amount); } priv.columnSettings.splice(index, amount); grid.adjustRowsAndCols(); selection.refreshBorders(); //it will call render and prepare methods break; default: throw new Error('There is no such action "' + action + '"'); break; } if (!keepEmptyRows) { grid.adjustRowsAndCols(); //makes sure that we did not add rows that will be removed in next refresh } }, /** * Makes sure there are empty rows at the bottom of the table */ adjustRowsAndCols: function () { var r, rlen, emptyRows = instance.countEmptyRows(true), emptyCols; //should I add empty rows to data source to meet minRows? rlen = instance.countRows(); if (rlen < priv.settings.minRows) { for (r = 0; r < priv.settings.minRows - rlen; r++) { datamap.createRow(instance.countRows(), 1, true); } } //should I add empty rows to meet minSpareRows? if (emptyRows < priv.settings.minSpareRows) { for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) { datamap.createRow(instance.countRows(), 1, true); } } //count currently empty cols emptyCols = instance.countEmptyCols(true); //should I add empty cols to meet minCols? if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) { for (; instance.countCols() < priv.settings.minCols; emptyCols++) { datamap.createCol(instance.countCols(), 1, true); } } //should I add empty cols to meet minSpareCols? if (!priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) { for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) { datamap.createCol(instance.countCols(), 1, true); } } if (priv.settings.enterBeginsEditing) { for (; (((priv.settings.minRows || priv.settings.minSpareRows) && instance.countRows() > priv.settings.minRows) && (priv.settings.minSpareRows && emptyRows > priv.settings.minSpareRows)); emptyRows--) { datamap.removeRow(); } } if (priv.settings.enterBeginsEditing && !priv.settings.columns) { for (; (((priv.settings.minCols || priv.settings.minSpareCols) && instance.countCols() > priv.settings.minCols) && (priv.settings.minSpareCols && emptyCols > priv.settings.minSpareCols)); emptyCols--) { datamap.removeCol(); } } var rowCount = instance.countRows(); var colCount = instance.countCols(); if (rowCount === 0 || colCount === 0) { selection.deselect(); } if (priv.selStart.exists()) { var selectionChanged; var fromRow = priv.selStart.row(); var fromCol = priv.selStart.col(); var toRow = priv.selEnd.row(); var toCol = priv.selEnd.col(); //if selection is outside, move selection to last row if (fromRow > rowCount - 1) { fromRow = rowCount - 1; selectionChanged = true; if (toRow > fromRow) { toRow = fromRow; } } else if (toRow > rowCount - 1) { toRow = rowCount - 1; selectionChanged = true; if (fromRow > toRow) { fromRow = toRow; } } //if selection is outside, move selection to last row if (fromCol > colCount - 1) { fromCol = colCount - 1; selectionChanged = true; if (toCol > fromCol) { toCol = fromCol; } } else if (toCol > colCount - 1) { toCol = colCount - 1; selectionChanged = true; if (fromCol > toCol) { fromCol = toCol; } } if (selectionChanged) { instance.selectCell(fromRow, fromCol, toRow, toCol); } } }, /** * Populate cells at position with 2d array * @param {Object} start Start selection position * @param {Array} input 2d array * @param {Object} [end] End selection position (only for drag-down mode) * @param {String} [source="populateFromArray"] * @param {String} [method="overwrite"] * @return {Object|undefined} ending td in pasted area (only if any cell was changed) */ populateFromArray: function (start, input, end, source, method) { var r, rlen, c, clen, setData = [], current = {}; rlen = input.length; if (rlen === 0) { return false; } var repeatCol , repeatRow , cmax , rmax; // insert data with specified pasteMode method switch (method) { case 'shift_down' : repeatCol = end ? end.col - start.col + 1 : 0; repeatRow = end ? end.row - start.row + 1 : 0; input = Handsontable.helper.translateRowsToColumns(input); for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) { if (c < clen) { for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) { input[c].push(input[c][r % rlen]); } input[c].unshift(start.col + c, start.row, 0); instance.spliceCol.apply(instance, input[c]); } else { input[c % clen][0] = start.col + c; instance.spliceCol.apply(instance, input[c % clen]); } } break; case 'shift_right' : repeatCol = end ? end.col - start.col + 1 : 0; repeatRow = end ? end.row - start.row + 1 : 0; for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) { if (r < rlen) { for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) { input[r].push(input[r][c % clen]); } input[r].unshift(start.row + r, start.col, 0); instance.spliceRow.apply(instance, input[r]); } else { input[r % rlen][0] = start.row + r; instance.spliceRow.apply(instance, input[r % rlen]); } } break; case 'overwrite' : default: // overwrite and other not specified options current.row = start.row; current.col = start.col; for (r = 0; r < rlen; r++) { if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) { break; } current.col = start.col; clen = input[r] ? input[r].length : 0; for (c = 0; c < clen; c++) { if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) { break; } if (!instance.getCellMeta(current.row, current.col).readOnly) { setData.push([current.row, current.col, input[r][c]]); } current.col++; if (end && c === clen - 1) { c = -1; } } current.row++; if (end && r === rlen - 1) { r = -1; } } instance.setDataAtCell(setData, null, null, source || 'populateFromArray'); break; } }, /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @param {Object[]} coordsArr * @returns {Object} */ getCornerCoords: function (coordsArr) { function mapProp(func, array, prop) { function getProp(el) { return el[prop]; } if (Array.prototype.map) { return func.apply(Math, array.map(getProp)); } return func.apply(Math, $.map(array, getProp)); } return { TL: { row: mapProp(Math.min, coordsArr, "row"), col: mapProp(Math.min, coordsArr, "col") }, BR: { row: mapProp(Math.max, coordsArr, "row"), col: mapProp(Math.max, coordsArr, "col") } }; }, /** * Returns array of td objects given start and end coordinates */ getCellsAtCoords: function (start, end) { var corners = grid.getCornerCoords([start, end]); var r, c, output = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { output.push(instance.view.getCellAtCoords({ row: r, col: c })); } } return output; } }; this.selection = selection = { //this public assignment is only temporary inProgress: false, /** * Sets inProgress to true. This enables onSelectionEnd and onSelectionEndByProp to function as desired */ begin: function () { instance.selection.inProgress = true; }, /** * Sets inProgress to false. Triggers onSelectionEnd and onSelectionEndByProp */ finish: function () { var sel = instance.getSelected(); instance.PluginHooks.run("afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]); instance.PluginHooks.run("afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3])); instance.selection.inProgress = false; }, isInProgress: function () { return instance.selection.inProgress; }, /** * Starts selection range on given td object * @param {Object} coords */ setRangeStart: function (coords) { priv.selStart.coords(coords); selection.setRangeEnd(coords); }, /** * Ends selection range on given td object * @param {Object} coords * @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end */ setRangeEnd: function (coords, scrollToCell) { instance.selection.begin(); priv.selEnd.coords(coords); if (!priv.settings.multiSelect) { priv.selStart.coords(coords); } //set up current selection instance.view.wt.selections.current.clear(); instance.view.wt.selections.current.add(priv.selStart.arr()); //set up area selection instance.view.wt.selections.area.clear(); if (selection.isMultiple()) { instance.view.wt.selections.area.add(priv.selStart.arr()); instance.view.wt.selections.area.add(priv.selEnd.arr()); } //set up highlight if (priv.settings.currentRowClassName || priv.settings.currentColClassName) { instance.view.wt.selections.highlight.clear(); instance.view.wt.selections.highlight.add(priv.selStart.arr()); instance.view.wt.selections.highlight.add(priv.selEnd.arr()); } //trigger handlers instance.PluginHooks.run("afterSelection", priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()); instance.PluginHooks.run("afterSelectionByProp", priv.selStart.row(), datamap.colToProp(priv.selStart.col()), priv.selEnd.row(), datamap.colToProp(priv.selEnd.col())); if (scrollToCell !== false) { instance.view.scrollViewport(coords); } selection.refreshBorders(); }, /** * Destroys editor, redraws borders around cells, prepares editor * @param {Boolean} revertOriginal * @param {Boolean} keepEditor */ refreshBorders: function (revertOriginal, keepEditor) { if (!keepEditor) { editorManager.destroyEditor(revertOriginal); } instance.view.render(); if (selection.isSelected() && !keepEditor) { editorManager.prepareEditor(); } }, /** * Returns information if we have a multiselection * @return {Boolean} */ isMultiple: function () { return !(priv.selEnd.col() === priv.selStart.col() && priv.selEnd.row() === priv.selStart.row()); }, /** * Selects cell relative to current cell (if possible) */ transformStart: function (rowDelta, colDelta, force) { if (priv.selStart.row() + rowDelta > instance.countRows() - 1) { if (force && priv.settings.minSpareRows > 0) { instance.alter("insert_row", instance.countRows()); } else if (priv.settings.autoWrapCol) { rowDelta = 1 - instance.countRows(); colDelta = priv.selStart.col() + colDelta == instance.countCols() - 1 ? 1 - instance.countCols() : 1; } } else if (priv.settings.autoWrapCol && priv.selStart.row() + rowDelta < 0 && priv.selStart.col() + colDelta >= 0) { rowDelta = instance.countRows() - 1; colDelta = priv.selStart.col() + colDelta == 0 ? instance.countCols() - 1 : -1; } if (priv.selStart.col() + colDelta > instance.countCols() - 1) { if (force && priv.settings.minSpareCols > 0) { instance.alter("insert_col", instance.countCols()); } else if (priv.settings.autoWrapRow) { rowDelta = priv.selStart.row() + rowDelta == instance.countRows() - 1 ? 1 - instance.countRows() : 1; colDelta = 1 - instance.countCols(); } } else if (priv.settings.autoWrapRow && priv.selStart.col() + colDelta < 0 && priv.selStart.row() + rowDelta >= 0) { rowDelta = priv.selStart.row() + rowDelta == 0 ? instance.countRows() - 1 : -1; colDelta = instance.countCols() - 1; } var totalRows = instance.countRows(); var totalCols = instance.countCols(); var coords = { row: priv.selStart.row() + rowDelta, col: priv.selStart.col() + colDelta }; if (coords.row < 0) { coords.row = 0; } else if (coords.row > 0 && coords.row >= totalRows) { coords.row = totalRows - 1; } if (coords.col < 0) { coords.col = 0; } else if (coords.col > 0 && coords.col >= totalCols) { coords.col = totalCols - 1; } selection.setRangeStart(coords); }, /** * Sets selection end cell relative to current selection end cell (if possible) */ transformEnd: function (rowDelta, colDelta) { if (priv.selEnd.exists()) { var totalRows = instance.countRows(); var totalCols = instance.countCols(); var coords = { row: priv.selEnd.row() + rowDelta, col: priv.selEnd.col() + colDelta }; if (coords.row < 0) { coords.row = 0; } else if (coords.row > 0 && coords.row >= totalRows) { coords.row = totalRows - 1; } if (coords.col < 0) { coords.col = 0; } else if (coords.col > 0 && coords.col >= totalCols) { coords.col = totalCols - 1; } selection.setRangeEnd(coords); } }, /** * Returns true if currently there is a selection on screen, false otherwise * @return {Boolean} */ isSelected: function () { return priv.selEnd.exists(); }, /** * Returns true if coords is within current selection coords * @return {Boolean} */ inInSelection: function (coords) { if (!selection.isSelected()) { return false; } var sel = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col); }, /** * Deselects all selected cells */ deselect: function () { if (!selection.isSelected()) { return; } instance.selection.inProgress = false; //needed by HT inception priv.selEnd = new Handsontable.SelectionPoint(); //create new empty point to remove the existing one instance.view.wt.selections.current.clear(); instance.view.wt.selections.area.clear(); editorManager.destroyEditor(); selection.refreshBorders(); instance.PluginHooks.run('afterDeselect'); }, /** * Select all cells */ selectAll: function () { if (!priv.settings.multiSelect) { return; } selection.setRangeStart({ row: 0, col: 0 }); selection.setRangeEnd({ row: instance.countRows() - 1, col: instance.countCols() - 1 }, false); }, /** * Deletes data from selected cells */ empty: function () { if (!selection.isSelected()) { return; } var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); var r, c, changes = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { if (!instance.getCellMeta(r, c).readOnly) { changes.push([r, c, '']); } } } instance.setDataAtCell(changes); } }; this.autofill = autofill = { //this public assignment is only temporary handle: null, /** * Create fill handle and fill border objects */ init: function () { if (!autofill.handle) { autofill.handle = {}; } else { autofill.handle.disabled = false; } }, /** * Hide fill handle and fill border permanently */ disable: function () { autofill.handle.disabled = true; }, /** * Selects cells down to the last row in the left column, then fills down to that cell */ selectAdjacent: function () { var select, data, r, maxR, c; if (selection.isMultiple()) { select = instance.view.wt.selections.area.getCorners(); } else { select = instance.view.wt.selections.current.getCorners(); } data = datamap.getAll(); rows : for (r = select[2] + 1; r < instance.countRows(); r++) { for (c = select[1]; c <= select[3]; c++) { if (data[r][c]) { break rows; } } if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) { maxR = r; } } if (maxR) { instance.view.wt.selections.fill.clear(); instance.view.wt.selections.fill.add([select[0], select[1]]); instance.view.wt.selections.fill.add([maxR, select[3]]); autofill.apply(); } }, /** * Apply fill values to the area in fill border, omitting the selection border */ apply: function () { var drag, select, start, end, _data; autofill.handle.isDragged = 0; drag = instance.view.wt.selections.fill.getCorners(); if (!drag) { return; } instance.view.wt.selections.fill.clear(); if (selection.isMultiple()) { select = instance.view.wt.selections.area.getCorners(); } else { select = instance.view.wt.selections.current.getCorners(); } if (drag[0] === select[0] && drag[1] < select[1]) { start = { row: drag[0], col: drag[1] }; end = { row: drag[2], col: select[1] - 1 }; } else if (drag[0] === select[0] && drag[3] > select[3]) { start = { row: drag[0], col: select[3] + 1 }; end = { row: drag[2], col: drag[3] }; } else if (drag[0] < select[0] && drag[1] === select[1]) { start = { row: drag[0], col: drag[1] }; end = { row: select[0] - 1, col: drag[3] }; } else if (drag[2] > select[2] && drag[1] === select[1]) { start = { row: select[2] + 1, col: drag[1] }; end = { row: drag[2], col: drag[3] }; } if (start) { _data = SheetClip.parse(datamap.getText(priv.selStart.coords(), priv.selEnd.coords())); instance.PluginHooks.run('beforeAutofill', start, end, _data); grid.populateFromArray(start, _data, end, 'autofill'); selection.setRangeStart({row: drag[0], col: drag[1]}); selection.setRangeEnd({row: drag[2], col: drag[3]}); } /*else { //reset to avoid some range bug selection.refreshBorders(); }*/ }, /** * Show fill border */ showBorder: function (coords) { coords.row = coords[0]; coords.col = coords[1]; var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) { coords = [coords.row, corners.BR.col]; } else if (priv.settings.fillHandle !== 'vertical') { coords = [corners.BR.row, coords.col]; } else { return; //wrong direction } instance.view.wt.selections.fill.clear(); instance.view.wt.selections.fill.add([priv.selStart.coords().row, priv.selStart.coords().col]); instance.view.wt.selections.fill.add([priv.selEnd.coords().row, priv.selEnd.coords().col]); instance.view.wt.selections.fill.add(coords); instance.view.render(); } }; this.init = function () { instance.PluginHooks.run('beforeInit'); this.view = new Handsontable.TableView(this); editorManager = new Handsontable.EditorManager(instance, priv, selection, datamap); this.updateSettings(priv.settings, true); this.parseSettingsFromDOM(); this.forceFullRender = true; //used when data was changed this.view.render(); if (typeof priv.firstRun === 'object') { instance.PluginHooks.run('afterChange', priv.firstRun[0], priv.firstRun[1]); priv.firstRun = false; } instance.PluginHooks.run('afterInit'); }; function ValidatorsQueue() { //moved this one level up so it can be used in any function here. Probably this should be moved to a separate file var resolved = false; return { validatorsInQueue: 0, addValidatorToQueue: function () { this.validatorsInQueue++; resolved = false; }, removeValidatorFormQueue: function () { this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1; this.checkIfQueueIsEmpty(); }, onQueueEmpty: function () { }, checkIfQueueIsEmpty: function () { if (this.validatorsInQueue == 0 && resolved == false) { resolved = true; this.onQueueEmpty(); } } }; } function validateChanges(changes, source, callback) { var waitingForValidator = new ValidatorsQueue(); waitingForValidator.onQueueEmpty = resolve; for (var i = changes.length - 1; i >= 0; i--) { if (changes[i] === null) { changes.splice(i, 1); } else { var row = changes[i][0]; var col = datamap.propToCol(changes[i][1]); var logicalCol = instance.runHooksAndReturn('modifyCol', col); //column order may have changes, so we need to translate physical col index (stored in datasource) to logical (displayed to user) var cellProperties = instance.getCellMeta(row, logicalCol); if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') { if (changes[i][3].length > 0 && /^-?[\d\s]*\.?\d*$/.test(changes[i][3])) { changes[i][3] = numeral().unformat(changes[i][3] || '0'); //numeral cannot unformat empty string } } if (instance.getCellValidator(cellProperties)) { waitingForValidator.addValidatorToQueue(); instance.validateCell(changes[i][3], cellProperties, (function (i, cellProperties) { return function (result) { if (typeof result !== 'boolean') { throw new Error("Validation error: result is not boolean"); } if (result === false && cellProperties.allowInvalid === false) { changes.splice(i, 1); // cancel the change cellProperties.valid = true; // we cancelled the change, so cell value is still valid --i; } waitingForValidator.removeValidatorFormQueue(); } })(i, cellProperties) , source); } } } waitingForValidator.checkIfQueueIsEmpty(); function resolve() { var beforeChangeResult; if (changes.length) { beforeChangeResult = instance.PluginHooks.execute("beforeChange", changes, source); if (typeof beforeChangeResult === 'function') { $.when(result).then(function () { callback(); //called when async validators and async beforeChange are resolved }); } else if (beforeChangeResult === false) { changes.splice(0, changes.length); //invalidate all changes (remove everything from array) } } if (typeof beforeChangeResult !== 'function') { callback(); //called when async validators are resolved and beforeChange was not async } } } /** * Internal function to apply changes. Called after validateChanges * @param {Array} changes Array in form of [row, prop, oldValue, newValue] * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ function applyChanges(changes, source) { var i = changes.length - 1; if (i < 0) { return; } for (; 0 <= i; i--) { if (changes[i] === null) { changes.splice(i, 1); continue; } if (priv.settings.minSpareRows) { while (changes[i][0] > instance.countRows() - 1) { datamap.createRow(); } } if (instance.dataType === 'array' && priv.settings.minSpareCols) { while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) { datamap.createCol(); } } datamap.set(changes[i][0], changes[i][1], changes[i][3]); } instance.forceFullRender = true; //used when data was changed grid.adjustRowsAndCols(); selection.refreshBorders(null, true); instance.PluginHooks.run('afterChange', changes, source || 'edit'); } this.validateCell = function (value, cellProperties, callback, source) { var validator = instance.getCellValidator(cellProperties); if (Object.prototype.toString.call(validator) === '[object RegExp]') { validator = (function (validator) { return function (value, callback) { callback(validator.test(value)); } })(validator); } if (typeof validator == 'function') { value = instance.PluginHooks.execute("beforeValidate", value, cellProperties.row, cellProperties.prop, source); // To provide consistent behaviour, validation should be always asynchronous setTimeout(function () { validator.call(cellProperties, value, function (valid) { cellProperties.valid = valid; valid = instance.PluginHooks.execute("afterValidate", valid, value, cellProperties.row, cellProperties.prop, source); callback(valid); }); }); } else { //resolve callback even if validator function was not found cellProperties.valid = true; callback(true); } }; function setDataInputToArray(row, prop_or_col, value) { if (typeof row === "object") { //is it an array of changes return row; } else if ($.isPlainObject(value)) { //backwards compatibility return value; } else { return [ [row, prop_or_col, value] ]; } } /** * Set data at given cell * @public * @param {Number|Array} row or array of changes in format [[row, col, value], ...] * @param {Number|String} col or source String * @param {String} value * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ this.setDataAtCell = function (row, col, value, source) { var input = setDataInputToArray(row, col, value) , i , ilen , changes = [] , prop; for (i = 0, ilen = input.length; i < ilen; i++) { if (typeof input[i] !== 'object') { throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter'); } if (typeof input[i][1] !== 'number') { throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`'); } prop = datamap.colToProp(input[i][1]); changes.push([ input[i][0], prop, datamap.get(input[i][0], prop), input[i][2] ]); } if (!source && typeof row === "object") { source = col; } validateChanges(changes, source, function () { applyChanges(changes, source); }); }; /** * Set data at given row property * @public * @param {Number|Array} row or array of changes in format [[row, prop, value], ...] * @param {String} prop or source String * @param {String} value * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ this.setDataAtRowProp = function (row, prop, value, source) { var input = setDataInputToArray(row, prop, value) , i , ilen , changes = []; for (i = 0, ilen = input.length; i < ilen; i++) { changes.push([ input[i][0], input[i][1], datamap.get(input[i][0], input[i][1]), input[i][2] ]); } if (!source && typeof row === "object") { source = prop; } validateChanges(changes, source, function () { applyChanges(changes, source); }); }; /** * Listen to document body keyboard input */ this.listen = function () { Handsontable.activeGuid = instance.guid; if (document.activeElement && document.activeElement !== document.body) { document.activeElement.blur(); } else if (!document.activeElement) { //IE document.body.focus(); } }; /** * Stop listening to document body keyboard input */ this.unlisten = function () { Handsontable.activeGuid = null; }; /** * Returns true if current Handsontable instance is listening on document body keyboard input */ this.isListening = function () { return Handsontable.activeGuid === instance.guid; }; /** * Destroys current editor, renders and selects current cell. If revertOriginal != true, edited data is saved * @param {Boolean} revertOriginal */ this.destroyEditor = function (revertOriginal) { selection.refreshBorders(revertOriginal); }; /** * Populate cells at position with 2d array * @param {Number} row Start row * @param {Number} col Start column * @param {Array} input 2d array * @param {Number=} endRow End row (use when you want to cut input when certain row is reached) * @param {Number=} endCol End column (use when you want to cut input when certain column is reached) * @param {String=} [source="populateFromArray"] * @param {String=} [method="overwrite"] * @return {Object|undefined} ending td in pasted area (only if any cell was changed) */ this.populateFromArray = function (row, col, input, endRow, endCol, source, method) { if (!(typeof input === 'object' && typeof input[0] === 'object')) { throw new Error("populateFromArray parameter `input` must be an array of arrays"); //API changed in 0.9-beta2, let's check if you use it correctly } return grid.populateFromArray({row: row, col: col}, input, typeof endRow === 'number' ? {row: endRow, col: endCol} : null, source, method); }; /** * Adds/removes data from the column * @param {Number} col Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ this.spliceCol = function (col, index, amount/*, elements... */) { return datamap.spliceCol.apply(datamap, arguments); }; /** * Adds/removes data from the row * @param {Number} row Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ this.spliceRow = function (row, index, amount/*, elements... */) { return datamap.spliceRow.apply(datamap, arguments); }; /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @param {Object[]} coordsArr * @returns {Object} */ this.getCornerCoords = function (coordsArr) { return grid.getCornerCoords(coordsArr); }; /** * Returns current selection. Returns undefined if there is no selection. * @public * @return {Array} [`startRow`, `startCol`, `endRow`, `endCol`] */ this.getSelected = function () { //https://github.com/warpech/jquery-handsontable/issues/44 //cjl if (selection.isSelected()) { return [priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()]; } }; /** * Parse settings from DOM and CSS * @public */ this.parseSettingsFromDOM = function () { var overflow = this.rootElement.css('overflow'); if (overflow === 'scroll' || overflow === 'auto') { this.rootElement[0].style.overflow = 'visible'; priv.settingsFromDOM.overflow = overflow; } else if (priv.settings.width === void 0 || priv.settings.height === void 0) { priv.settingsFromDOM.overflow = 'auto'; } if (priv.settings.width === void 0) { priv.settingsFromDOM.width = this.rootElement.width(); } else { priv.settingsFromDOM.width = void 0; } priv.settingsFromDOM.height = void 0; if (priv.settings.height === void 0) { if (priv.settingsFromDOM.overflow === 'scroll' || priv.settingsFromDOM.overflow === 'auto') { //this needs to read only CSS/inline style and not actual height //so we need to call getComputedStyle on cloned container var clone = this.rootElement[0].cloneNode(false); var parent = this.rootElement[0].parentNode; if (parent) { clone.removeAttribute('id'); parent.appendChild(clone); var computedHeight = parseInt(window.getComputedStyle(clone, null).getPropertyValue('height'), 10); if(isNaN(computedHeight) && clone.currentStyle){ computedHeight = parseInt(clone.currentStyle.height, 10) } if (computedHeight > 0) { priv.settingsFromDOM.height = computedHeight; } parent.removeChild(clone); } } } }; /** * Render visible data * @public */ this.render = function () { if (instance.view) { instance.forceFullRender = true; //used when data was changed instance.parseSettingsFromDOM(); selection.refreshBorders(null, true); } }; /** * Load data from array * @public * @param {Array} data */ this.loadData = function (data) { if (typeof data === 'object' && data !== null) { if (!(data.push && data.splice)) { //check if data is array. Must use duck-type check so Backbone Collections also pass it //when data is not an array, attempt to make a single-row array of it data = [data]; } } else if(data === null) { data = []; var row; for (var r = 0, rlen = priv.settings.startRows; r < rlen; r++) { row = []; for (var c = 0, clen = priv.settings.startCols; c < clen; c++) { row.push(null); } data.push(row); } } else { throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)"); } priv.isPopulated = false; GridSettings.prototype.data = data; if (priv.settings.dataSchema instanceof Array || data[0] instanceof Array) { instance.dataType = 'array'; } else if (typeof priv.settings.dataSchema === 'function') { instance.dataType = 'function'; } else { instance.dataType = 'object'; } datamap = new Handsontable.DataMap(instance, priv, GridSettings); clearCellSettingCache(); grid.adjustRowsAndCols(); instance.PluginHooks.run('afterLoadData'); if (priv.firstRun) { priv.firstRun = [null, 'loadData']; } else { instance.PluginHooks.run('afterChange', null, 'loadData'); instance.render(); } priv.isPopulated = true; function clearCellSettingCache() { priv.cellSettings.length = 0; } }; /** * Return the current data object (the same that was passed by `data` configuration option or `loadData` method). Optionally you can provide cell range `r`, `c`, `r2`, `c2` to get only a fragment of grid data * @public * @param {Number} r (Optional) From row * @param {Number} c (Optional) From col * @param {Number} r2 (Optional) To row * @param {Number} c2 (Optional) To col * @return {Array|Object} */ this.getData = function (r, c, r2, c2) { if (typeof r === 'undefined') { return datamap.getAll(); } else { return datamap.getRange({row: r, col: c}, {row: r2, col: c2}, datamap.DESTINATION_RENDERER); } }; this.getCopyableData = function (startRow, startCol, endRow, endCol) { return datamap.getCopyableText({row: startRow, col: startCol}, {row: endRow, col: endCol}); } /** * Update settings * @public */ this.updateSettings = function (settings, init) { var i, clen; if (typeof settings.rows !== "undefined") { throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?"); } if (typeof settings.cols !== "undefined") { throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?"); } for (i in settings) { if (i === 'data') { continue; //loadData will be triggered later } else { if (instance.PluginHooks.hooks[i] !== void 0 || instance.PluginHooks.legacy[i] !== void 0) { if (typeof settings[i] === 'function' || Handsontable.helper.isArray(settings[i])) { instance.PluginHooks.add(i, settings[i]); } } else { // Update settings if (!init && settings.hasOwnProperty(i)) { GridSettings.prototype[i] = settings[i]; } //launch extensions if (Handsontable.extension[i]) { priv.extensions[i] = new Handsontable.extension[i](instance, settings[i]); } } } } // Load data or create data map if (settings.data === void 0 && priv.settings.data === void 0) { instance.loadData(null); //data source created just now } else if (settings.data !== void 0) { instance.loadData(settings.data); //data source given as option } else if (settings.columns !== void 0) { datamap.createMap(); } // Init columns constructors configuration clen = instance.countCols(); //Clear cellSettings cache priv.cellSettings.length = 0; if (clen > 0) { var proto, column; for (i = 0; i < clen; i++) { priv.columnSettings[i] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts); // shortcut for prototype proto = priv.columnSettings[i].prototype; // Use settings provided by user if (GridSettings.prototype.columns) { column = GridSettings.prototype.columns[i]; Handsontable.helper.extend(proto, column); Handsontable.helper.extend(proto, expandType(column)); } } } if (typeof settings.fillHandle !== "undefined") { if (autofill.handle && settings.fillHandle === false) { autofill.disable(); } else if (!autofill.handle && settings.fillHandle !== false) { autofill.init(); } } if (typeof settings.className !== "undefined") { if (GridSettings.prototype.className) { instance.rootElement.removeClass(GridSettings.prototype.className); } if (settings.className) { instance.rootElement.addClass(settings.className); } } if (!init) { instance.PluginHooks.run('afterUpdateSettings'); } grid.adjustRowsAndCols(); if (instance.view && !priv.firstRun) { instance.forceFullRender = true; //used when data was changed selection.refreshBorders(null, true); } }; this.getValue = function () { var sel = instance.getSelected(); if (GridSettings.prototype.getValue) { if (typeof GridSettings.prototype.getValue === 'function') { return GridSettings.prototype.getValue.call(instance); } else if (sel) { return instance.getData()[sel[0]][GridSettings.prototype.getValue]; } } else if (sel) { return instance.getDataAtCell(sel[0], sel[1]); } }; function expandType(obj) { if (!obj.hasOwnProperty('type')) return; //ignore obj.prototype.type var type, expandedType = {}; if (typeof obj.type === 'object') { type = obj.type; } else if (typeof obj.type === 'string') { type = Handsontable.cellTypes[obj.type]; if (type === void 0) { throw new Error('You declared cell type "' + obj.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } } for (var i in type) { if (type.hasOwnProperty(i) && !obj.hasOwnProperty(i)) { expandedType[i] = type[i]; } } return expandedType; } /** * Returns current settings object * @return {Object} */ this.getSettings = function () { return priv.settings; }; /** * Returns current settingsFromDOM object * @return {Object} */ this.getSettingsFromDOM = function () { return priv.settingsFromDOM; }; /** * Clears grid * @public */ this.clear = function () { selection.selectAll(); selection.empty(); }; /** * Inserts or removes rows and columns * @param {String} action See grid.alter for possible values * @param {Number} index * @param {Number} amount * @param {String} [source] Optional. Source of hook runner. * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows. * @public */ this.alter = function (action, index, amount, source, keepEmptyRows) { grid.alter(action, index, amount, source, keepEmptyRows); }; /** * Returns <td> element corresponding to params row, col * @param {Number} row * @param {Number} col * @public * @return {Element} */ this.getCell = function (row, col) { return instance.view.getCellAtCoords({row: row, col: col}); }; /** * Returns property name associated with column number * @param {Number} col * @public * @return {String} */ this.colToProp = function (col) { return datamap.colToProp(col); }; /** * Returns column number associated with property name * @param {String} prop * @public * @return {Number} */ this.propToCol = function (prop) { return datamap.propToCol(prop); }; /** * Return value at `row`, `col` * @param {Number} row * @param {Number} col * @public * @return value (mixed data type) */ this.getDataAtCell = function (row, col) { return datamap.get(row, datamap.colToProp(col)); }; /** * Return value at `row`, `prop` * @param {Number} row * @param {String} prop * @public * @return value (mixed data type) */ this.getDataAtRowProp = function (row, prop) { return datamap.get(row, prop); }; /** * Return value at `col` * @param {Number} col * @public * @return value (mixed data type) */ this.getDataAtCol = function (col) { return [].concat.apply([], datamap.getRange({row: 0, col: col}, {row: priv.settings.data.length - 1, col: col}, datamap.DESTINATION_RENDERER)); }; /** * Return value at `prop` * @param {String} prop * @public * @return value (mixed data type) */ this.getDataAtProp = function (prop) { return [].concat.apply([], datamap.getRange({row: 0, col: datamap.propToCol(prop)}, {row: priv.settings.data.length - 1, col: datamap.propToCol(prop)}, datamap.DESTINATION_RENDERER)); }; /** * Return value at `row` * @param {Number} row * @public * @return value (mixed data type) */ this.getDataAtRow = function (row) { return priv.settings.data[row]; }; /** * Returns cell meta data object corresponding to params row, col * @param {Number} row * @param {Number} col * @public * @return {Object} */ this.getCellMeta = function (row, col) { var prop = datamap.colToProp(col) , cellProperties; row = translateRowIndex(row); col = translateColIndex(col); if ("undefined" === typeof priv.columnSettings[col]) { priv.columnSettings[col] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts); } if (!priv.cellSettings[row]) { priv.cellSettings[row] = []; } if (!priv.cellSettings[row][col]) { priv.cellSettings[row][col] = new priv.columnSettings[col](); } cellProperties = priv.cellSettings[row][col]; //retrieve cellProperties from cache cellProperties.row = row; cellProperties.col = col; cellProperties.prop = prop; cellProperties.instance = instance; instance.PluginHooks.run('beforeGetCellMeta', row, col, cellProperties); Handsontable.helper.extend(cellProperties, expandType(cellProperties)); //for `type` added in beforeGetCellMeta if (cellProperties.cells) { var settings = cellProperties.cells.call(cellProperties, row, col, prop); if (settings) { Handsontable.helper.extend(cellProperties, settings); Handsontable.helper.extend(cellProperties, expandType(settings)); //for `type` added in cells } } instance.PluginHooks.run('afterGetCellMeta', row, col, cellProperties); return cellProperties; /** * If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied) * we need to translate logical (stored) row index to physical (displayed) index. * @param row - original row index * @returns {int} translated row index */ function translateRowIndex(row){ var getVars = {row: row}; instance.PluginHooks.execute('beforeGet', getVars); return getVars.row; } /** * If displayed columns order is different than the order of columns stored in memory (i.e. column were moved using manualColumnMove plugin) * we need to translate logical (stored) column index to physical (displayed) index. * @param col - original column index * @returns {int} - translated column index */ function translateColIndex(col){ return Handsontable.PluginHooks.execute(instance, 'modifyCol', col); // warning: this must be done after datamap.colToProp } }; var rendererLookup = Handsontable.helper.cellMethodLookupFactory('renderer'); this.getCellRenderer = function (row, col) { var renderer = rendererLookup.call(this, row, col); return Handsontable.renderers.getRenderer(renderer); }; this.getCellEditor = Handsontable.helper.cellMethodLookupFactory('editor'); this.getCellValidator = Handsontable.helper.cellMethodLookupFactory('validator'); /** * Validates all cells using their validator functions and calls callback when finished. Does not render the view * @param callback */ this.validateCells = function (callback) { var waitingForValidator = new ValidatorsQueue(); waitingForValidator.onQueueEmpty = callback; var i = instance.countRows() - 1; while (i >= 0) { var j = instance.countCols() - 1; while (j >= 0) { waitingForValidator.addValidatorToQueue(); instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function () { waitingForValidator.removeValidatorFormQueue(); }, 'validateCells'); j--; } i--; } waitingForValidator.checkIfQueueIsEmpty(); }; /** * Return array of row headers (if they are enabled). If param `row` given, return header at given row as string * @param {Number} row (Optional) * @return {Array|String} */ this.getRowHeader = function (row) { if (row === void 0) { var out = []; for (var i = 0, ilen = instance.countRows(); i < ilen; i++) { out.push(instance.getRowHeader(i)); } return out; } else if (Object.prototype.toString.call(priv.settings.rowHeaders) === '[object Array]' && priv.settings.rowHeaders[row] !== void 0) { return priv.settings.rowHeaders[row]; } else if (typeof priv.settings.rowHeaders === 'function') { return priv.settings.rowHeaders(row); } else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') { return row + 1; } else { return priv.settings.rowHeaders; } }; /** * Returns information of this table is configured to display row headers * @returns {boolean} */ this.hasRowHeaders = function () { return !!priv.settings.rowHeaders; }; /** * Returns information of this table is configured to display column headers * @returns {boolean} */ this.hasColHeaders = function () { if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) { //Polymer has empty value = null return !!priv.settings.colHeaders; } for (var i = 0, ilen = instance.countCols(); i < ilen; i++) { if (instance.getColHeader(i)) { return true; } } return false; }; /** * Return array of column headers (if they are enabled). If param `col` given, return header at given column as string * @param {Number} col (Optional) * @return {Array|String} */ this.getColHeader = function (col) { if (col === void 0) { var out = []; for (var i = 0, ilen = instance.countCols(); i < ilen; i++) { out.push(instance.getColHeader(i)); } return out; } else { col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col); if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) { return priv.settings.columns[col].title; } else if (Object.prototype.toString.call(priv.settings.colHeaders) === '[object Array]' && priv.settings.colHeaders[col] !== void 0) { return priv.settings.colHeaders[col]; } else if (typeof priv.settings.colHeaders === 'function') { return priv.settings.colHeaders(col); } else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') { return Handsontable.helper.spreadsheetColumnLabel(col); } else { return priv.settings.colHeaders; } } }; /** * Return column width from settings (no guessing). Private use intended * @param {Number} col * @return {Number} */ this._getColWidthFromSettings = function (col) { var cellProperties = instance.getCellMeta(0, col); var width = cellProperties.width; if (width === void 0 || width === priv.settings.width) { width = cellProperties.colWidths; } if (width !== void 0 && width !== null) { switch (typeof width) { case 'object': //array width = width[col]; break; case 'function': width = width(col); break; } if (typeof width === 'string') { width = parseInt(width, 10); } } return width; }; /** * Return column width * @param {Number} col * @return {Number} */ this.getColWidth = function (col) { col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col); var response = { width: instance._getColWidthFromSettings(col) }; if (!response.width) { response.width = 50; } instance.PluginHooks.run('afterGetColWidth', col, response); return response.width; }; /** * Return total number of rows in grid * @return {Number} */ this.countRows = function () { return priv.settings.data.length; }; /** * Return total number of columns in grid * @return {Number} */ this.countCols = function () { if (instance.dataType === 'object' || instance.dataType === 'function') { if (priv.settings.columns && priv.settings.columns.length) { return priv.settings.columns.length; } else { return datamap.colToPropCache.length; } } else if (instance.dataType === 'array') { if (priv.settings.columns && priv.settings.columns.length) { return priv.settings.columns.length; } else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) { return priv.settings.data[0].length; } else { return 0; } } }; /** * Return index of first visible row * @return {Number} */ this.rowOffset = function () { return instance.view.wt.getSetting('offsetRow'); }; /** * Return index of first visible column * @return {Number} */ this.colOffset = function () { return instance.view.wt.getSetting('offsetColumn'); }; /** * Return number of visible rows. Returns -1 if table is not visible * @return {Number} */ this.countVisibleRows = function () { return instance.view.wt.drawn ? instance.view.wt.wtTable.rowStrategy.countVisible() : -1; }; /** * Return number of visible columns. Returns -1 if table is not visible * @return {Number} */ this.countVisibleCols = function () { return instance.view.wt.drawn ? instance.view.wt.wtTable.columnStrategy.countVisible() : -1; }; /** * Return number of empty rows * @return {Boolean} ending If true, will only count empty rows at the end of the data source */ this.countEmptyRows = function (ending) { var i = instance.countRows() - 1 , empty = 0; while (i >= 0) { datamap.get(i, 0); if (instance.isEmptyRow(datamap.getVars.row)) { empty++; } else if (ending) { break; } i--; } return empty; }; /** * Return number of empty columns * @return {Boolean} ending If true, will only count empty columns at the end of the data source row */ this.countEmptyCols = function (ending) { if (instance.countRows() < 1) { return 0; } var i = instance.countCols() - 1 , empty = 0; while (i >= 0) { if (instance.isEmptyCol(i)) { empty++; } else if (ending) { break; } i--; } return empty; }; /** * Return true if the row at the given index is empty, false otherwise * @param {Number} r Row index * @return {Boolean} */ this.isEmptyRow = function (r) { return priv.settings.isEmptyRow.call(instance, r); }; /** * Return true if the column at the given index is empty, false otherwise * @param {Number} c Column index * @return {Boolean} */ this.isEmptyCol = function (c) { return priv.settings.isEmptyCol.call(instance, c); }; /** * Selects cell on grid. Optionally selects range to another cell * @param {Number} row * @param {Number} col * @param {Number} [endRow] * @param {Number} [endCol] * @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to the selection * @public * @return {Boolean} */ this.selectCell = function (row, col, endRow, endCol, scrollToCell) { if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) { return false; } if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) { return false; } if (typeof endRow !== "undefined") { if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) { return false; } if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) { return false; } } priv.selStart.coords({row: row, col: col}); if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) { document.activeElement.blur(); //needed or otherwise prepare won't focus the cell. selectionSpec tests this (should move focus to selected cell) } instance.listen(); if (typeof endRow === "undefined") { selection.setRangeEnd({row: row, col: col}, scrollToCell); } else { selection.setRangeEnd({row: endRow, col: endCol}, scrollToCell); } instance.selection.finish(); return true; }; this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) { arguments[1] = datamap.propToCol(arguments[1]); if (typeof arguments[3] !== "undefined") { arguments[3] = datamap.propToCol(arguments[3]); } return instance.selectCell.apply(instance, arguments); }; /** * Deselects current sell selection on grid * @public */ this.deselectCell = function () { selection.deselect(); }; /** * Remove grid from DOM * @public */ this.destroy = function () { instance.clearTimeouts(); if (instance.view) { //in case HT is destroyed before initialization has finished instance.view.wt.destroy(); } instance.rootElement.empty(); instance.rootElement.removeData('handsontable'); instance.rootElement.off('.handsontable'); $(window).off('.' + instance.guid); $document.off('.' + instance.guid); $body.off('.' + instance.guid); instance.PluginHooks.run('afterDestroy'); }; /** * Returns active editor object * @returns {Object} */ this.getActiveEditor = function(){ return editorManager.getActiveEditor(); }; /** * Return Handsontable instance * @public * @return {Object} */ this.getInstance = function () { return instance.rootElement.data("handsontable"); }; (function () { // Create new instance of plugin hooks instance.PluginHooks = new Handsontable.PluginHookClass(); // Upgrade methods to call of global PluginHooks instance var _run = instance.PluginHooks.run , _exe = instance.PluginHooks.execute; instance.PluginHooks.run = function (key, p1, p2, p3, p4, p5) { _run.call(this, instance, key, p1, p2, p3, p4, p5); Handsontable.PluginHooks.run(instance, key, p1, p2, p3, p4, p5); }; instance.PluginHooks.execute = function (key, p1, p2, p3, p4, p5) { var globalHandlerResult = Handsontable.PluginHooks.execute(instance, key, p1, p2, p3, p4, p5); var localHandlerResult = _exe.call(this, instance, key, globalHandlerResult, p2, p3, p4, p5); return typeof localHandlerResult == 'undefined' ? globalHandlerResult : localHandlerResult; }; // Map old API with new methods instance.addHook = function () { instance.PluginHooks.add.apply(instance.PluginHooks, arguments); }; instance.addHookOnce = function () { instance.PluginHooks.once.apply(instance.PluginHooks, arguments); }; instance.removeHook = function () { instance.PluginHooks.remove.apply(instance.PluginHooks, arguments); }; instance.runHooks = function () { instance.PluginHooks.run.apply(instance.PluginHooks, arguments); }; instance.runHooksAndReturn = function () { return instance.PluginHooks.execute.apply(instance.PluginHooks, arguments); }; })(); this.timeouts = {}; /** * Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called * @public */ this.registerTimeout = function (key, handle, ms) { clearTimeout(this.timeouts[key]); this.timeouts[key] = setTimeout(handle, ms || 0); }; /** * Clears all known timeouts * @public */ this.clearTimeouts = function () { for (var key in this.timeouts) { if (this.timeouts.hasOwnProperty(key)) { clearTimeout(this.timeouts[key]); } } }; /** * Handsontable version */ this.version = '0.10.3'; //inserted by grunt from package.json }; var DefaultSettings = function () {}; DefaultSettings.prototype = { data: void 0, width: void 0, height: void 0, startRows: 5, startCols: 5, rowHeaders: null, colHeaders: null, minRows: 0, minCols: 0, maxRows: Infinity, maxCols: Infinity, minSpareRows: 0, minSpareCols: 0, multiSelect: true, fillHandle: true, fixedRowsTop: 0, fixedColumnsLeft: 0, outsideClickDeselects: true, enterBeginsEditing: true, enterMoves: {row: 1, col: 0}, tabMoves: {row: 0, col: 1}, autoWrapRow: false, autoWrapCol: false, copyRowsLimit: 1000, copyColsLimit: 1000, pasteMode: 'overwrite', currentRowClassName: void 0, currentColClassName: void 0, stretchH: 'hybrid', isEmptyRow: function (r) { var val; for (var c = 0, clen = this.countCols(); c < clen; c++) { val = this.getDataAtCell(r, c); if (val !== '' && val !== null && typeof val !== 'undefined') { return false; } } return true; }, isEmptyCol: function (c) { var val; for (var r = 0, rlen = this.countRows(); r < rlen; r++) { val = this.getDataAtCell(r, c); if (val !== '' && val !== null && typeof val !== 'undefined') { return false; } } return true; }, observeDOMVisibility: true, allowInvalid: true, invalidCellClassName: 'htInvalid', placeholderCellClassName: 'htPlaceholder', readOnlyCellClassName: 'htDimmed', fragmentSelection: false, readOnly: false, nativeScrollbars: false, type: 'text', copyable: true, debug: false //shows debug overlays in Walkontable }; Handsontable.DefaultSettings = DefaultSettings; $.fn.handsontable = function (action) { var i , ilen , args , output , userSettings , $this = this.first() // Use only first element from list , instance = $this.data('handsontable'); // Init case if (typeof action !== 'string') { userSettings = action || {}; if (instance) { instance.updateSettings(userSettings); } else { instance = new Handsontable.Core($this, userSettings); $this.data('handsontable', instance); instance.init(); } return $this; } // Action case else { args = []; if (arguments.length > 1) { for (i = 1, ilen = arguments.length; i < ilen; i++) { args.push(arguments[i]); } } if (instance) { if (typeof instance[action] !== 'undefined') { output = instance[action].apply(instance, args); } else { throw new Error('Handsontable do not provide action: ' + action); } } return output; } }; /** * Handsontable TableView constructor * @param {Object} instance */ Handsontable.TableView = function (instance) { var that = this , $window = $(window) , $documentElement = $(document.documentElement); this.instance = instance; this.settings = instance.getSettings(); this.settingsFromDOM = instance.getSettingsFromDOM(); instance.rootElement.data('originalStyle', instance.rootElement[0].getAttribute('style')); //needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions // in IE7 getAttribute('style') returns an object instead of a string, but we only support IE8+ instance.rootElement.addClass('handsontable'); var table = document.createElement('TABLE'); table.className = 'htCore'; this.THEAD = document.createElement('THEAD'); table.appendChild(this.THEAD); this.TBODY = document.createElement('TBODY'); table.appendChild(this.TBODY); instance.$table = $(table); instance.rootElement.prepend(instance.$table); instance.rootElement.on('mousedown.handsontable', function (event) { if (!that.isTextSelectionAllowed(event.target)) { clearTextSelection(); event.preventDefault(); window.focus(); //make sure that window that contains HOT is active. Important when HOT is in iframe. } }); $documentElement.on('keyup.' + instance.guid, function (event) { if (instance.selection.isInProgress() && !event.shiftKey) { instance.selection.finish(); } }); var isMouseDown; $documentElement.on('mouseup.' + instance.guid, function (event) { if (instance.selection.isInProgress() && event.which === 1) { //is left mouse button instance.selection.finish(); } isMouseDown = false; if (instance.autofill.handle && instance.autofill.handle.isDragged) { if (instance.autofill.handle.isDragged > 1) { instance.autofill.apply(); } instance.autofill.handle.isDragged = 0; } if (Handsontable.helper.isOutsideInput(document.activeElement)) { instance.unlisten(); } }); $documentElement.on('mousedown.' + instance.guid, function (event) { var next = event.target; if (next !== that.wt.wtTable.spreader) { //immediate click on "spreader" means click on the right side of vertical scrollbar while (next !== document.documentElement) { if (next === null) { return; //click on something that was a row but now is detached (possibly because your click triggered a rerender) } if (next === instance.rootElement[0] || next.nodeName === 'HANDSONTABLE-TABLE') { return; //click inside container or Web Component (HANDSONTABLE-TABLE is the name of the custom element) } next = next.parentNode; } } if (that.settings.outsideClickDeselects) { instance.deselectCell(); } else { instance.destroyEditor(); } }); instance.rootElement.on('mousedown.handsontable', '.dragdealer', function () { instance.destroyEditor(); }); instance.$table.on('selectstart', function (event) { if (that.settings.fragmentSelection) { return; } //https://github.com/warpech/jquery-handsontable/issues/160 //selectstart is IE only event. Prevent text from being selected when performing drag down in IE8 event.preventDefault(); }); var clearTextSelection = function () { //http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript if (window.getSelection) { if (window.getSelection().empty) { // Chrome window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { // Firefox window.getSelection().removeAllRanges(); } } else if (document.selection) { // IE? document.selection.empty(); } }; var walkontableConfig = { debug: function () { return that.settings.debug; }, table: table, stretchH: this.settings.stretchH, data: instance.getDataAtCell, totalRows: instance.countRows, totalColumns: instance.countCols, nativeScrollbars: this.settings.nativeScrollbars, offsetRow: 0, offsetColumn: 0, width: this.getWidth(), height: this.getHeight(), fixedColumnsLeft: function () { return that.settings.fixedColumnsLeft; }, fixedRowsTop: function () { return that.settings.fixedRowsTop; }, rowHeaders: function () { return instance.hasRowHeaders() ? [function (index, TH) { that.appendRowHeader(index, TH); }] : [] }, columnHeaders: function () { return instance.hasColHeaders() ? [function (index, TH) { that.appendColHeader(index, TH); }] : [] }, columnWidth: instance.getColWidth, 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); that.instance.PluginHooks.run('afterRenderer', TD, row, col, prop, value, cellProperties); }, selections: { current: { className: 'current', border: { width: 2, color: '#5292F7', style: 'solid', cornerVisible: function () { return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple() } } }, area: { className: 'area', border: { width: 1, color: '#89AFF9', style: 'solid', cornerVisible: function () { return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple() } } }, highlight: { highlightRowClassName: that.settings.currentRowClassName, highlightColumnClassName: that.settings.currentColClassName }, fill: { className: 'fill', border: { width: 1, color: 'red', style: 'solid' } } }, hideBorderOnMouseDownOver: function () { return that.settings.fragmentSelection; }, onCellMouseDown: function (event, coords, TD) { instance.listen(); isMouseDown = true; var coordsObj = {row: coords[0], col: coords[1]}; if (event.button === 2 && instance.selection.inInSelection(coordsObj)) { //right mouse button //do nothing } else if (event.shiftKey) { instance.selection.setRangeEnd(coordsObj); } else { instance.selection.setRangeStart(coordsObj); } instance.PluginHooks.run('afterOnCellMouseDown', event, coords, TD); }, /*onCellMouseOut: function (/*event, coords, TD* /) { if (isMouseDown && that.settings.fragmentSelection === 'single') { clearTextSelection(); //otherwise text selection blinks during multiple cells selection } },*/ onCellMouseOver: function (event, coords, TD) { var coordsObj = {row: coords[0], col: coords[1]}; if (isMouseDown) { /*if (that.settings.fragmentSelection === 'single') { clearTextSelection(); //otherwise text selection blinks during multiple cells selection }*/ instance.selection.setRangeEnd(coordsObj); } else if (instance.autofill.handle && instance.autofill.handle.isDragged) { instance.autofill.handle.isDragged++; instance.autofill.showBorder(coords); } instance.PluginHooks.run('afterOnCellMouseOver', event, coords, TD); }, onCellCornerMouseDown: function (event) { instance.autofill.handle.isDragged = 1; event.preventDefault(); instance.PluginHooks.run('afterOnCellCornerMouseDown', event); }, onCellCornerDblClick: function () { instance.autofill.selectAdjacent(); }, beforeDraw: function (force) { that.beforeRender(force); }, onDraw: function(force){ that.onDraw(force); }, onScrollVertically: function () { instance.runHooks('afterScrollVertically'); }, onScrollHorizontally: function () { instance.runHooks('afterScrollHorizontally'); } }; instance.PluginHooks.run('beforeInitWalkontable', walkontableConfig); this.wt = new Walkontable(walkontableConfig); $window.on('resize.' + instance.guid, function () { instance.registerTimeout('resizeTimeout', function () { instance.parseSettingsFromDOM(); var newWidth = that.getWidth(); var newHeight = that.getHeight(); if (walkontableConfig.width !== newWidth || walkontableConfig.height !== newHeight) { instance.forceFullRender = true; that.render(); walkontableConfig.width = newWidth; walkontableConfig.height = newHeight; } }, 60); }); $(that.wt.wtTable.spreader).on('mousedown.handsontable, contextmenu.handsontable', function (event) { if (event.target === that.wt.wtTable.spreader && event.which === 3) { //right mouse button exactly on spreader means right clickon the right hand side of vertical scrollbar event.stopPropagation(); } }); $documentElement.on('click.' + instance.guid, function () { if (that.settings.observeDOMVisibility) { if (that.wt.drawInterrupted) { that.instance.forceFullRender = true; that.render(); } } }); }; Handsontable.TableView.prototype.isTextSelectionAllowed = function (el) { if ( Handsontable.helper.isInput(el) ) { return (true); } if (this.settings.fragmentSelection && this.wt.wtDom.isChildOf(el, this.TBODY)) { return (true); } return false; }; Handsontable.TableView.prototype.isCellEdited = function () { var activeEditor = this.instance.getActiveEditor(); return activeEditor && activeEditor.isOpened(); }; Handsontable.TableView.prototype.getWidth = function () { var val = this.settings.width !== void 0 ? this.settings.width : this.settingsFromDOM.width; return typeof val === 'function' ? val() : val; }; Handsontable.TableView.prototype.getHeight = function () { var val = this.settings.height !== void 0 ? this.settings.height : this.settingsFromDOM.height; return typeof val === 'function' ? val() : val; }; Handsontable.TableView.prototype.beforeRender = function (force) { if (force) { //force = did Walkontable decide to do full render this.instance.PluginHooks.run('beforeRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render? this.wt.update('width', this.getWidth()); this.wt.update('height', this.getHeight()); } }; Handsontable.TableView.prototype.onDraw = function(force){ if (force) { //force = did Walkontable decide to do full render this.instance.PluginHooks.run('afterRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render? } }; Handsontable.TableView.prototype.render = function () { this.wt.draw(!this.instance.forceFullRender); this.instance.forceFullRender = false; this.instance.rootElement.triggerHandler('render.handsontable'); }; /** * Returns td object given coordinates */ Handsontable.TableView.prototype.getCellAtCoords = function (coords) { var td = this.wt.wtTable.getCell([coords.row, coords.col]); if (td < 0) { //there was an exit code (cell is out of bounds) return null; } else { return td; } }; /** * Scroll viewport to selection * @param coords */ Handsontable.TableView.prototype.scrollViewport = function (coords) { this.wt.scrollViewport([coords.row, coords.col]); }; /** * Append row header to a TH element * @param row * @param TH */ Handsontable.TableView.prototype.appendRowHeader = function (row, TH) { if (row > -1) { this.wt.wtDom.fastInnerHTML(TH, this.instance.getRowHeader(row)); } else { var DIV = document.createElement('DIV'); DIV.className = 'relative'; this.wt.wtDom.fastInnerText(DIV, '\u00A0'); this.wt.wtDom.empty(TH); TH.appendChild(DIV); } }; /** * Append column header to a TH element * @param col * @param TH */ Handsontable.TableView.prototype.appendColHeader = function (col, TH) { var DIV = document.createElement('DIV') , SPAN = document.createElement('SPAN'); DIV.className = 'relative'; SPAN.className = 'colHeader'; this.wt.wtDom.fastInnerHTML(SPAN, this.instance.getColHeader(col)); DIV.appendChild(SPAN); this.wt.wtDom.empty(TH); TH.appendChild(DIV); this.instance.PluginHooks.run('afterGetColHeader', col, TH); }; /** * Given a element's left position relative to the viewport, returns maximum element width until the right edge of the viewport (before scrollbar) * @param {Number} left * @return {Number} */ Handsontable.TableView.prototype.maximumVisibleElementWidth = function (left) { var rootWidth = this.wt.wtViewport.getWorkspaceWidth(); if(this.settings.nativeScrollbars) { return rootWidth; } return rootWidth - left; }; /** * Given a element's top position relative to the viewport, returns maximum element height until the bottom edge of the viewport (before scrollbar) * @param {Number} top * @return {Number} */ Handsontable.TableView.prototype.maximumVisibleElementHeight = function (top) { var rootHeight = this.wt.wtViewport.getWorkspaceHeight(); if(this.settings.nativeScrollbars) { return rootHeight; } return rootHeight - top; }; /** * Utility to register editors and common namespace for keeping reference to all editor classes */ (function (Handsontable) { 'use strict'; function RegisteredEditor(editorClass) { var clazz, instances; instances = {}; clazz = editorClass; this.getInstance = function (hotInstance) { if (!(hotInstance.guid in instances)) { instances[hotInstance.guid] = new clazz(hotInstance); } return instances[hotInstance.guid]; } } var registeredEditorNames = {}; var registeredEditorClasses = new WeakMap(); Handsontable.editors = { /** * Registers editor under given name * @param {String} editorName * @param {Function} editorClass */ registerEditor: function (editorName, editorClass) { var editor = new RegisteredEditor(editorClass); if (typeof editorName === "string") { registeredEditorNames[editorName] = editor; } registeredEditorClasses.set(editorClass, editor); }, /** * Returns instance (singleton) of editor class * @param {String|Function} editorName/editorClass * @returns {Function} editorClass */ getEditor: function (editorName, hotInstance) { var editor; if (typeof editorName == 'function') { if (!(registeredEditorClasses.get(editorName))) { this.registerEditor(null, editorName); } editor = registeredEditorClasses.get(editorName); } else if (typeof editorName == 'string') { editor = registeredEditorNames[editorName]; } else { throw Error('Only strings and functions can be passed as "editor" parameter '); } if (!editor) { throw Error('No editor registered under name "' + editorName + '"'); } return editor.getInstance(hotInstance); } }; })(Handsontable); (function(Handsontable){ 'use strict'; Handsontable.EditorManager = function(instance, priv, selection){ var that = this; var $document = $(document); var keyCodes = Handsontable.helper.keyCode; var activeEditor; var init = function () { function onKeyDown(event) { if (!instance.isListening()) { return; } if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin priv.settings.beforeOnKeyDown.call(instance, event); } instance.PluginHooks.run('beforeKeyDown', event); if (!event.isImmediatePropagationStopped()) { priv.lastKeyCode = event.keyCode; if (selection.isSelected()) { var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) if (!activeEditor.isWaiting()) { if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown) { that.openEditor(''); event.stopPropagation(); //required by HandsontableEditor return; } } var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart; switch (event.keyCode) { case keyCodes.A: if (ctrlDown) { selection.selectAll(); //select all cells event.preventDefault(); event.stopPropagation(); break; } case keyCodes.ARROW_UP: if (that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionUp(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_DOWN: if (that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionDown(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_RIGHT: if(that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionRight(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_LEFT: if(that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionLeft(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.TAB: var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves; if (event.shiftKey) { selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left } else { selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed) } event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.BACKSPACE: case keyCodes.DELETE: selection.empty(event); that.prepareEditor(); event.preventDefault(); break; case keyCodes.F2: /* F2 */ that.openEditor(); event.preventDefault(); //prevent Opera from opening Go to Page dialog break; case keyCodes.ENTER: /* return/enter */ if(that.isEditorOpened()){ if (activeEditor.state !== Handsontable.EditorState.WAITING){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionAfterEnter(event.shiftKey); } else { if (instance.getSettings().enterBeginsEditing){ that.openEditor(); } else { moveSelectionAfterEnter(event.shiftKey); } } event.preventDefault(); //don't add newline to field event.stopImmediatePropagation(); //required by HandsontableEditor break; case keyCodes.ESCAPE: if(that.isEditorOpened()){ that.closeEditorAndRestoreOriginalValue(ctrlDown); } event.preventDefault(); break; case keyCodes.HOME: if (event.ctrlKey || event.metaKey) { rangeModifier({row: 0, col: priv.selStart.col()}); } else { rangeModifier({row: priv.selStart.row(), col: 0}); } event.preventDefault(); //don't scroll the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.END: if (event.ctrlKey || event.metaKey) { rangeModifier({row: instance.countRows() - 1, col: priv.selStart.col()}); } else { rangeModifier({row: priv.selStart.row(), col: instance.countCols() - 1}); } event.preventDefault(); //don't scroll the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.PAGE_UP: selection.transformStart(-instance.countVisibleRows(), 0); instance.view.wt.scrollVertical(-instance.countVisibleRows()); instance.view.render(); event.preventDefault(); //don't page up the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.PAGE_DOWN: selection.transformStart(instance.countVisibleRows(), 0); instance.view.wt.scrollVertical(instance.countVisibleRows()); instance.view.render(); event.preventDefault(); //don't page down the window event.stopPropagation(); //required by HandsontableEditor break; default: break; } } } } $document.on('keydown.handsontable.' + instance.guid, onKeyDown); function onDblClick() { // that.instance.destroyEditor(); that.openEditor(); } instance.view.wt.update('onCellDblClick', onDblClick); instance.addHook('afterDestroy', function(){ $document.off('keydown.handsontable.' + instance.guid); }); function moveSelectionAfterEnter(shiftKey){ var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves; if (shiftKey) { selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up } else { selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed) } } function moveSelectionUp(shiftKey){ if (shiftKey) { selection.transformEnd(-1, 0); } else { selection.transformStart(-1, 0); } } function moveSelectionDown(shiftKey){ if (shiftKey) { selection.transformEnd(1, 0); //expanding selection down with shift } else { selection.transformStart(1, 0); //move selection down } } function moveSelectionRight(shiftKey){ if (shiftKey) { selection.transformEnd(0, 1); } else { selection.transformStart(0, 1); } } function moveSelectionLeft(shiftKey){ if (shiftKey) { selection.transformEnd(0, -1); } else { selection.transformStart(0, -1); } } }; /** * Destroy current editor, if exists * @param {Boolean} revertOriginal */ this.destroyEditor = function (revertOriginal) { this.closeEditor(revertOriginal); }; this.getActiveEditor = function () { return activeEditor; }; /** * Prepare text input to be displayed at given grid cell */ this.prepareEditor = function () { if (activeEditor && activeEditor.isWaiting()){ this.closeEditor(false, false, function(dataSaved){ if(dataSaved){ that.prepareEditor(); } }); return; } var row = priv.selStart.row(); var col = priv.selStart.col(); var prop = instance.colToProp(col); var td = instance.getCell(row, col); var originalValue = instance.getDataAtCell(row, col); var cellProperties = instance.getCellMeta(row, col); var editorClass = instance.getCellEditor(cellProperties); activeEditor = Handsontable.editors.getEditor(editorClass, instance); activeEditor.prepare(row, col, prop, td, originalValue, cellProperties); }; this.isEditorOpened = function () { return activeEditor.isOpened(); }; this.openEditor = function (initialValue) { activeEditor.beginEditing(initialValue); }; this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) { if (!activeEditor){ if(callback) { callback(false); } } else { activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback); } }; this.closeEditorAndSaveChanges = function(ctrlDown){ return this.closeEditor(false, ctrlDown); }; this.closeEditorAndRestoreOriginalValue = function(ctrlDown){ return this.closeEditor(true, ctrlDown); }; init(); }; })(Handsontable); /** * Utility to register renderers and common namespace for keeping reference to all renderers classes */ (function (Handsontable) { 'use strict'; var registeredRenderers = {}; Handsontable.renderers = { /** * Registers renderer under given name * @param {String} rendererName * @param {Function} rendererFunction */ registerRenderer: function (rendererName, rendererFunction) { registeredRenderers[rendererName] = rendererFunction }, /** * @param {String|Function} rendererName/rendererFunction * @returns {Function} rendererFunction */ getRenderer: function (rendererName) { if (typeof rendererName == 'function'){ return rendererName; } if (typeof rendererName != 'string'){ throw Error('Only strings and functions can be passed as "renderer" parameter '); } if (!(rendererName in registeredRenderers)) { throw Error('No editor registered under name "' + rendererName + '"'); } return registeredRenderers[rendererName]; } }; })(Handsontable); /** * DOM helper optimized for maximum performance * It is recommended for Handsontable plugins and renderers, because it is much faster than jQuery * @type {WalkonableDom} */ Handsontable.Dom = new WalkontableDom(); /** * Returns true if keyCode represents a printable character * @param {Number} keyCode * @return {Boolean} */ Handsontable.helper.isPrintableChar = function (keyCode) { return ((keyCode == 32) || //space (keyCode >= 48 && keyCode <= 57) || //0-9 (keyCode >= 96 && keyCode <= 111) || //numpad (keyCode >= 186 && keyCode <= 192) || //;=,-./` (keyCode >= 219 && keyCode <= 222) || //[]{}\|"' keyCode >= 226 || //special chars (229 for Asian chars) (keyCode >= 65 && keyCode <= 90)); //a-z }; Handsontable.helper.isMetaKey = function (keyCode) { var keyCodes = Handsontable.helper.keyCode; var metaKeys = [ keyCodes.ARROW_DOWN, keyCodes.ARROW_UP, keyCodes.ARROW_LEFT, keyCodes.ARROW_RIGHT, keyCodes.HOME, keyCodes.END, keyCodes.DELETE, keyCodes.BACKSPACE, keyCodes.F1, keyCodes.F2, keyCodes.F3, keyCodes.F4, keyCodes.F5, keyCodes.F6, keyCodes.F7, keyCodes.F8, keyCodes.F9, keyCodes.F10, keyCodes.F11, keyCodes.F12, keyCodes.TAB, keyCodes.PAGE_DOWN, keyCodes.PAGE_UP, keyCodes.ENTER, keyCodes.ESCAPE, keyCodes.SHIFT, keyCodes.CAPS_LOCK, keyCodes.ALT ]; return metaKeys.indexOf(keyCode) != -1; }; Handsontable.helper.isCtrlKey = function (keyCode) { var keys = Handsontable.helper.keyCode; return [keys.CONTROL_LEFT, 224, keys.COMMAND_LEFT, keys.COMMAND_RIGHT].indexOf(keyCode) != -1; }; /** * Converts a value to string * @param value * @return {String} */ Handsontable.helper.stringify = function (value) { switch (typeof value) { case 'string': case 'number': return value + ''; break; case 'object': if (value === null) { return ''; } else { return value.toString(); } break; case 'undefined': return ''; break; default: return value.toString(); } }; /** * Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc * @param index * @returns {String} */ Handsontable.helper.spreadsheetColumnLabel = function (index) { var dividend = index + 1; var columnLabel = ''; var modulo; while (dividend > 0) { modulo = (dividend - 1) % 26; columnLabel = String.fromCharCode(65 + modulo) + columnLabel; dividend = parseInt((dividend - modulo) / 26, 10); } return columnLabel; }; /** * Checks if value of n is a numeric one * http://jsperf.com/isnan-vs-isnumeric/4 * @param n * @returns {boolean} */ Handsontable.helper.isNumeric = function (n) { var t = typeof n; return t == 'number' ? !isNaN(n) && isFinite(n) : t == 'string' ? !n.length ? false : n.length == 1 ? /\d/.test(n) : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) : t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false; }; Handsontable.helper.isArray = function (obj) { return Object.prototype.toString.call(obj).match(/array/i) !== null; }; /** * Checks if child is a descendant of given parent node * http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another * @param parent * @param child * @returns {boolean} */ Handsontable.helper.isDescendant = function (parent, child) { var node = child.parentNode; while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; }; /** * Generates a random hex string. Used as namespace for Handsontable instance events. * @return {String} - 16 character random string: "92b1bfc74ec4" */ Handsontable.helper.randomString = function () { return walkontableRandomString(); }; /** * Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`. * Creates temporary dummy function to call it as constructor. * Described in ticket: https://github.com/warpech/jquery-handsontable/pull/516 * @param {Object} Child child class * @param {Object} Parent parent class * @return {Object} extended Child */ Handsontable.helper.inherit = function (Child, Parent) { Parent.prototype.constructor = Parent; Child.prototype = new Parent(); Child.prototype.constructor = Child; return Child; }; /** * Perform shallow extend of a target object with extension's own properties * @param {Object} target An object that will receive the new properties * @param {Object} extension An object containing additional properties to merge into the target */ Handsontable.helper.extend = function (target, extension) { for (var i in extension) { if (extension.hasOwnProperty(i)) { target[i] = extension[i]; } } }; Handsontable.helper.getPrototypeOf = function (obj) { var prototype; if(typeof obj.__proto__ == "object"){ prototype = obj.__proto__; } else { var oldConstructor, constructor = obj.constructor; if (typeof obj.constructor == "function") { oldConstructor = constructor; if (delete obj.constructor){ constructor = obj.constructor; // get real constructor obj.constructor = oldConstructor; // restore constructor } } prototype = constructor ? constructor.prototype : null; // needed for IE } return prototype; }; /** * Factory for columns constructors. * @param {Object} GridSettings * @param {Array} conflictList * @return {Object} ColumnSettings */ Handsontable.helper.columnFactory = function (GridSettings, conflictList) { function ColumnSettings () {} Handsontable.helper.inherit(ColumnSettings, GridSettings); // Clear conflict settings for (var i = 0, len = conflictList.length; i < len; i++) { ColumnSettings.prototype[conflictList[i]] = void 0; } return ColumnSettings; }; Handsontable.helper.translateRowsToColumns = function (input) { var i , ilen , j , jlen , output = [] , olen = 0; for (i = 0, ilen = input.length; i < ilen; i++) { for (j = 0, jlen = input[i].length; j < jlen; j++) { if (j == olen) { output.push([]); olen++; } output[j].push(input[i][j]) } } return output; }; Handsontable.helper.to2dArray = function (arr) { var i = 0 , ilen = arr.length; while (i < ilen) { arr[i] = [arr[i]]; i++; } }; Handsontable.helper.extendArray = function (arr, extension) { var i = 0 , ilen = extension.length; while (i < ilen) { arr.push(extension[i]); i++; } }; /** * Determines if the given DOM element is an input field. * Notice: By 'input' we mean input, textarea and select nodes * @param element - DOM element * @returns {boolean} */ Handsontable.helper.isInput = function (element) { var inputs = ['INPUT', 'SELECT', 'TEXTAREA']; return inputs.indexOf(element.nodeName) > -1; } /** * Determines if the given DOM element is an input field placed OUTSIDE of HOT. * Notice: By 'input' we mean input, textarea and select nodes * @param element - DOM element * @returns {boolean} */ Handsontable.helper.isOutsideInput = function (element) { return Handsontable.helper.isInput(element) && element.className.indexOf('handsontableInput') == -1; }; Handsontable.helper.keyCode = { MOUSE_LEFT: 1, MOUSE_RIGHT: 3, MOUSE_MIDDLE: 2, BACKSPACE: 8, COMMA: 188, DELETE: 46, END: 35, ENTER: 13, ESCAPE: 27, CONTROL_LEFT: 91, COMMAND_LEFT: 17, COMMAND_RIGHT: 93, ALT: 18, HOME: 36, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, SPACE: 32, SHIFT: 16, CAPS_LOCK: 20, TAB: 9, ARROW_RIGHT: 39, ARROW_LEFT: 37, ARROW_UP: 38, ARROW_DOWN: 40, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, A: 65, X: 88, C: 67, V: 86 }; /** * Determines whether given object is a plain Object. * Note: String and Array are not plain Objects * @param {*} obj * @returns {boolean} */ Handsontable.helper.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; /** * Determines whether given object is an Array. * Note: String is not an Array * @param {*} obj * @returns {boolean} */ Handsontable.helper.isArray = function(obj){ return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) == '[object Array]'; }; Handsontable.helper.pivot = function (arr) { var pivotedArr = []; if(!arr || arr.length == 0 || !arr[0] || arr[0].length == 0){ return pivotedArr; } var rowCount = arr.length; var colCount = arr[0].length; for(var i = 0; i < rowCount; i++){ for(var j = 0; j < colCount; j++){ if(!pivotedArr[j]){ pivotedArr[j] = []; } pivotedArr[j][i] = arr[i][j]; } } return pivotedArr; }; Handsontable.helper.proxy = function (fun, context) { return function () { return fun.apply(context, arguments); }; }; /** * Factory that produces a function for searching methods (or any properties) which could be defined directly in * table configuration or implicitly, within cell type definition. * * For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be * defined implicitly using "type" property. * * Methods/properties defined explicitly always takes precedence over those defined through "type". * * If the method/property is not found in an object, searching is continued recursively through prototype chain, until * it reaches the Object.prototype. * * * @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable') * @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type" * @returns {Function} */ Handsontable.helper.cellMethodLookupFactory = function (methodName, allowUndefined) { allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined; return function cellMethodLookup (row, col) { return (function getMethodFromProperties(properties) { if (!properties){ return; //method not found } else if (properties.hasOwnProperty(methodName) && properties[methodName]) { //check if it is own and is not empty return properties[methodName]; //method defined directly } else if (properties.hasOwnProperty('type') && properties.type) { //check if it is own and is not empty var type; if(typeof properties.type != 'string' ){ throw new Error('Cell type must be a string '); } type = translateTypeNameToObject(properties.type); if (type.hasOwnProperty(methodName)) { return type[methodName]; //method defined in type. } else if (allowUndefined) { return; //method does not defined in type (eg. validator), returns undefined } } return getMethodFromProperties(Handsontable.helper.getPrototypeOf(properties)); })(typeof row == 'number' ? this.getCellMeta(row, col) : row); }; function translateTypeNameToObject(typeName) { var type = Handsontable.cellTypes[typeName]; if(typeof type == 'undefined'){ throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } return type; } }; Handsontable.SelectionPoint = function () { this._row = null; //private use intended this._col = null; }; Handsontable.SelectionPoint.prototype.exists = function () { return (this._row !== null); }; Handsontable.SelectionPoint.prototype.row = function (val) { if (val !== void 0) { this._row = val; } return this._row; }; Handsontable.SelectionPoint.prototype.col = function (val) { if (val !== void 0) { this._col = val; } return this._col; }; Handsontable.SelectionPoint.prototype.coords = function (coords) { if (coords !== void 0) { this._row = coords.row; this._col = coords.col; } return { row: this._row, col: this._col } }; Handsontable.SelectionPoint.prototype.arr = function (arr) { if (arr !== void 0) { this._row = arr[0]; this._col = arr[1]; } return [this._row, this._col] }; (function (Handsontable) { 'use strict'; /** * Utility class that gets and saves data from/to the data source using mapping of columns numbers to object property names * TODO refactor arguments of methods getRange, getText to be numbers (not objects) * TODO remove priv, GridSettings from object constructor * * @param instance * @param priv * @param GridSettings * @constructor */ Handsontable.DataMap = function (instance, priv, GridSettings) { this.instance = instance; this.priv = priv; this.GridSettings = GridSettings; this.dataSource = this.instance.getSettings().data; if (this.dataSource[0]) { this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]); } else { this.duckSchema = {}; } this.createMap(); this.getVars = {}; //used by modifier this.setVars = {}; //used by modifier }; Handsontable.DataMap.prototype.DESTINATION_RENDERER = 1; Handsontable.DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2; Handsontable.DataMap.prototype.recursiveDuckSchema = function (obj) { var schema; if ($.isPlainObject(obj)) { schema = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { if ($.isPlainObject(obj[i])) { schema[i] = this.recursiveDuckSchema(obj[i]); } else { schema[i] = null; } } } } else { schema = []; } return schema; }; Handsontable.DataMap.prototype.recursiveDuckColumns = function (schema, lastCol, parent) { var prop, i; if (typeof lastCol === 'undefined') { lastCol = 0; parent = ''; } if ($.isPlainObject(schema)) { for (i in schema) { if (schema.hasOwnProperty(i)) { if (schema[i] === null) { prop = parent + i; this.colToPropCache.push(prop); this.propToColCache[prop] = lastCol; lastCol++; } else { lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.'); } } } } return lastCol; }; Handsontable.DataMap.prototype.createMap = function () { if (typeof this.getSchema() === "undefined") { throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`"); } var i, ilen, schema = this.getSchema(); this.colToPropCache = []; this.propToColCache = {}; var columns = this.instance.getSettings().columns; if (columns) { for (i = 0, ilen = columns.length; i < ilen; i++) { this.colToPropCache[i] = columns[i].data; this.propToColCache[columns[i].data] = i; } } else { this.recursiveDuckColumns(schema); } }; Handsontable.DataMap.prototype.colToProp = function (col) { col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col); if (this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') { return this.colToPropCache[col]; } else { return col; } }; Handsontable.DataMap.prototype.propToCol = function (prop) { var col; if (typeof this.propToColCache[prop] !== 'undefined') { col = this.propToColCache[prop]; } else { col = prop; } col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col); return col; }; Handsontable.DataMap.prototype.getSchema = function () { var schema = this.instance.getSettings().dataSchema; if (schema) { if (typeof schema === 'function') { return schema(); } return schema; } return this.duckSchema; }; /** * Creates row at the bottom of the data array * @param {Number} [index] Optional. Index of the row before which the new row will be inserted */ Handsontable.DataMap.prototype.createRow = function (index, amount, createdAutomatically) { var row , colCount = this.instance.countCols() , numberOfCreatedRows = 0 , currentIndex; if (!amount) { amount = 1; } if (typeof index !== 'number' || index >= this.instance.countRows()) { index = this.instance.countRows(); } currentIndex = index; var maxRows = this.instance.getSettings().maxRows; while (numberOfCreatedRows < amount && this.instance.countRows() < maxRows) { if (this.instance.dataType === 'array') { row = []; for (var c = 0; c < colCount; c++) { row.push(null); } } else if (this.instance.dataType === 'function') { row = this.instance.getSettings().dataSchema(index); } else { row = $.extend(true, {}, this.getSchema()); } if (index === this.instance.countRows()) { this.dataSource.push(row); } else { this.dataSource.splice(index, 0, row); } numberOfCreatedRows++; currentIndex++; } this.instance.PluginHooks.run('afterCreateRow', index, numberOfCreatedRows, createdAutomatically); this.instance.forceFullRender = true; //used when data was changed return numberOfCreatedRows; }; /** * Creates col at the right of the data array * @param {Number} [index] Optional. Index of the column before which the new column will be inserted * * @param {Number} [amount] Optional. */ Handsontable.DataMap.prototype.createCol = function (index, amount, createdAutomatically) { if (this.instance.dataType === 'object' || this.instance.getSettings().columns) { throw new Error("Cannot create new column. When data source in an object, " + "you can only have as much columns as defined in first data row, data schema or in the 'columns' setting." + "If you want to be able to add new columns, you have to use array datasource."); } var rlen = this.instance.countRows() , data = this.dataSource , constructor , numberOfCreatedCols = 0 , currentIndex; if (!amount) { amount = 1; } currentIndex = index; var maxCols = this.instance.getSettings().maxCols; while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) { constructor = Handsontable.helper.columnFactory(this.GridSettings, this.priv.columnsSettingConflicts); if (typeof index !== 'number' || index >= this.instance.countCols()) { for (var r = 0; r < rlen; r++) { if (typeof data[r] === 'undefined') { data[r] = []; } data[r].push(null); } // Add new column constructor this.priv.columnSettings.push(constructor); } else { for (var r = 0; r < rlen; r++) { data[r].splice(currentIndex, 0, null); } // Add new column constructor at given index this.priv.columnSettings.splice(currentIndex, 0, constructor); } numberOfCreatedCols++; currentIndex++; } this.instance.PluginHooks.run('afterCreateCol', index, numberOfCreatedCols, createdAutomatically); this.instance.forceFullRender = true; //used when data was changed return numberOfCreatedCols; }; /** * Removes row from the data array * @param {Number} [index] Optional. Index of the row to be removed. If not provided, the last row will be removed * @param {Number} [amount] Optional. Amount of the rows to be removed. If not provided, one row will be removed */ Handsontable.DataMap.prototype.removeRow = function (index, amount) { if (!amount) { amount = 1; } if (typeof index !== 'number') { index = -amount; } index = (this.instance.countRows() + index) % this.instance.countRows(); // We have to map the physical row ids to logical and than perform removing with (possibly) new row id var logicRows = this.physicalRowsToLogical(index, amount); var actionWasNotCancelled = this.instance.PluginHooks.execute('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); this.instance.PluginHooks.run('afterRemoveRow', index, amount); this.instance.forceFullRender = true; //used when data was changed }; /** * Removes column from the data array * @param {Number} [index] Optional. Index of the column to be removed. If not provided, the last column will be removed * @param {Number} [amount] Optional. Amount of the columns to be removed. If not provided, one column will be removed */ Handsontable.DataMap.prototype.removeCol = function (index, amount) { if (this.instance.dataType === 'object' || this.instance.getSettings().columns) { throw new Error("cannot remove column with object data source or columns option specified"); } if (!amount) { amount = 1; } if (typeof index !== 'number') { index = -amount; } index = (this.instance.countCols() + index) % this.instance.countCols(); var actionWasNotCancelled = this.instance.PluginHooks.execute('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); this.instance.PluginHooks.run('afterRemoveCol', index, amount); this.instance.forceFullRender = true; //used when data was changed }; /** * Add / removes data from the column * @param {Number} col Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ Handsontable.DataMap.prototype.spliceCol = function (col, index, amount/*, elements...*/) { var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : []; var colData = this.instance.getDataAtCol(col); var removed = colData.slice(index, index + amount); var after = colData.slice(index + amount); Handsontable.helper.extendArray(elements, after); var i = 0; while (i < amount) { elements.push(null); //add null in place of removed elements i++; } Handsontable.helper.to2dArray(elements); this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol'); return removed; }; /** * Add / removes data from the row * @param {Number} row Index of row in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ Handsontable.DataMap.prototype.spliceRow = function (row, index, amount/*, elements...*/) { var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : []; var rowData = this.instance.getDataAtRow(row); var removed = rowData.slice(index, index + amount); var after = rowData.slice(index + amount); Handsontable.helper.extendArray(elements, after); var i = 0; while (i < amount) { elements.push(null); //add null in place of removed elements i++; } this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow'); return removed; }; /** * Returns single value from the data array * @param {Number} row * @param {Number} prop */ Handsontable.DataMap.prototype.get = function (row, prop) { this.getVars.row = row; this.getVars.prop = prop; this.instance.PluginHooks.run('beforeGet', this.getVars); if (typeof this.getVars.prop === 'string' && this.getVars.prop.indexOf('.') > -1) { var sliced = this.getVars.prop.split("."); var out = this.dataSource[this.getVars.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 this.getVars.prop === 'function') { /** * allows for interacting with complex structures, for example * d3/jQuery getter/setter properties: * * {columns: [{ * data: function(row, value){ * if(arguments.length === 1){ * return row.property(); * } * row.property(value); * } * }]} */ return this.getVars.prop(this.dataSource.slice( this.getVars.row, this.getVars.row + 1 )[0]); } else { return this.dataSource[this.getVars.row] ? this.dataSource[this.getVars.row][this.getVars.prop] : null; } }; var copyableLookup = Handsontable.helper.cellMethodLookupFactory('copyable', false); /** * Returns single value from the data array (intended for clipboard copy to an external application) * @param {Number} row * @param {Number} prop * @return {String} */ Handsontable.DataMap.prototype.getCopyable = function (row, prop) { if (copyableLookup.call(this.instance, row, this.propToCol(prop))) { return this.get(row, prop); } return ''; }; /** * Saves single value to the data array * @param {Number} row * @param {Number} prop * @param {String} value * @param {String} [source] Optional. Source of hook runner. */ Handsontable.DataMap.prototype.set = function (row, prop, value, source) { this.setVars.row = row; this.setVars.prop = prop; this.setVars.value = value; this.instance.PluginHooks.run('beforeSet', this.setVars, source || "datamapGet"); if (typeof this.setVars.prop === 'string' && this.setVars.prop.indexOf('.') > -1) { var sliced = this.setVars.prop.split("."); var out = this.dataSource[this.setVars.row]; for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) { out = out[sliced[i]]; } out[sliced[i]] = this.setVars.value; } else if (typeof this.setVars.prop === 'function') { /* see the `function` handler in `get` */ this.setVars.prop(this.dataSource.slice( this.setVars.row, this.setVars.row + 1 )[0], this.setVars.value); } else { this.dataSource[this.setVars.row][this.setVars.prop] = this.setVars.value; } }; /** * This ridiculous piece of code maps rows Id that are present in table data to those displayed for user. * The trick is, the physical row id (stored in settings.data) is not necessary the same * as the logical (displayed) row id (e.g. when sorting is applied). */ Handsontable.DataMap.prototype.physicalRowsToLogical = function (index, amount) { var totalRows = this.instance.countRows(); var physicRow = (totalRows + index) % totalRows; var logicRows = []; var rowsToRemove = amount; while (physicRow < totalRows && rowsToRemove) { this.get(physicRow, 0); //this performs an actual mapping and saves the result to getVars logicRows.push(this.getVars.row); rowsToRemove--; physicRow++; } return logicRows; }; /** * Clears the data array */ Handsontable.DataMap.prototype.clear = function () { for (var r = 0; r < this.instance.countRows(); r++) { for (var c = 0; c < this.instance.countCols(); c++) { this.set(r, this.colToProp(c), ''); } } }; /** * Returns the data array * @return {Array} */ Handsontable.DataMap.prototype.getAll = function () { return this.dataSource; }; /** * Returns data range as array * @param {Object} start Start selection position * @param {Object} end End selection position * @param {Number} destination Destination of datamap.get * @return {Array} */ Handsontable.DataMap.prototype.getRange = function (start, end, destination) { var r, rlen, c, clen, output = [], row; var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get; rlen = Math.max(start.row, end.row); clen = Math.max(start.col, end.col); for (r = Math.min(start.row, end.row); r <= rlen; r++) { row = []; for (c = Math.min(start.col, end.col); c <= clen; c++) { row.push(getFn.call(this, r, this.colToProp(c))); } output.push(row); } return output; }; /** * Return data as text (tab separated columns) * @param {Object} start (Optional) Start selection position * @param {Object} end (Optional) End selection position * @return {String} */ Handsontable.DataMap.prototype.getText = function (start, end) { return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_RENDERER)); }; /** * Return data as copyable text (tab separated columns intended for clipboard copy to an external application) * @param {Object} start (Optional) Start selection position * @param {Object} end (Optional) End selection position * @return {String} */ Handsontable.DataMap.prototype.getCopyableText = function (start, end) { return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR)); }; })(Handsontable); (function (Handsontable) { 'use strict'; /* Adds appropriate CSS class to table cell, based on cellProperties */ Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) { if (cellProperties.readOnly) { instance.view.wt.wtDom.addClass(TD, cellProperties.readOnlyCellClassName); } if (cellProperties.valid === false && cellProperties.invalidCellClassName) { instance.view.wt.wtDom.addClass(TD, cellProperties.invalidCellClassName); } if (!value && cellProperties.placeholder) { instance.view.wt.wtDom.addClass(TD, cellProperties.placeholderCellClassName); } } })(Handsontable); /** * Default text renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var TextRenderer = function (instance, TD, row, col, prop, value, cellProperties) { Handsontable.renderers.cellDecorator.apply(this, arguments); if (!value && cellProperties.placeholder) { value = cellProperties.placeholder; } var escaped = Handsontable.helper.stringify(value); if (cellProperties.rendererTemplate) { instance.view.wt.wtDom.empty(TD); var TEMPLATE = document.createElement('TEMPLATE'); TEMPLATE.setAttribute('bind', '{{}}'); TEMPLATE.innerHTML = cellProperties.rendererTemplate; HTMLTemplateElement.decorate(TEMPLATE); TEMPLATE.model = instance.getDataAtRow(row); TD.appendChild(TEMPLATE); } else { instance.view.wt.wtDom.fastInnerText(TD, escaped); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } }; //Handsontable.TextRenderer = TextRenderer; //Left for backward compatibility Handsontable.renderers.TextRenderer = TextRenderer; Handsontable.renderers.registerRenderer('text', TextRenderer); })(Handsontable); (function (Handsontable) { var clonableWRAPPER = document.createElement('DIV'); clonableWRAPPER.className = 'htAutocompleteWrapper'; var clonableARROW = document.createElement('DIV'); clonableARROW.className = 'htAutocompleteArrow'; clonableARROW.appendChild(document.createTextNode('\u25BC')); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips var wrapTdContentWithWrapper = function(TD, WRAPPER){ WRAPPER.innerHTML = TD.innerHTML; Handsontable.Dom.empty(TD); TD.appendChild(WRAPPER); }; /** * Autocomplete renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ var AutocompleteRenderer = function (instance, TD, row, col, prop, value, cellProperties) { var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties); TD.appendChild(ARROW); Handsontable.Dom.addClass(TD, 'htAutocomplete'); if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed //otherwise empty fields appear borderless in demo/renderers.html (IE) TD.appendChild(document.createTextNode('\u00A0')); //\u00A0 equals &nbsp; for a text node //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } if (!instance.acArrowListener) { //not very elegant but easy and fast instance.acArrowListener = function () { instance.view.wt.getSetting('onCellDblClick'); }; instance.rootElement.on('mousedown', '.htAutocompleteArrow', instance.acArrowListener); //this way we don't bind event listener to each arrow. We rely on propagation instead } }; Handsontable.AutocompleteRenderer = AutocompleteRenderer; Handsontable.renderers.AutocompleteRenderer = AutocompleteRenderer; Handsontable.renderers.registerRenderer('autocomplete', AutocompleteRenderer); })(Handsontable); /** * Checkbox renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var clonableINPUT = document.createElement('INPUT'); clonableINPUT.className = 'htCheckboxRendererInput'; clonableINPUT.type = 'checkbox'; clonableINPUT.setAttribute('autocomplete', 'off'); var CheckboxRenderer = function (instance, TD, row, col, prop, value, cellProperties) { if (typeof cellProperties.checkedTemplate === "undefined") { cellProperties.checkedTemplate = true; } if (typeof cellProperties.uncheckedTemplate === "undefined") { cellProperties.uncheckedTemplate = false; } instance.view.wt.wtDom.empty(TD); //TODO identify under what circumstances this line can be removed var INPUT = clonableINPUT.cloneNode(false); //this is faster than createElement if (value === cellProperties.checkedTemplate || value === Handsontable.helper.stringify(cellProperties.checkedTemplate)) { INPUT.checked = true; TD.appendChild(INPUT); } else if (value === cellProperties.uncheckedTemplate || value === Handsontable.helper.stringify(cellProperties.uncheckedTemplate)) { TD.appendChild(INPUT); } else if (value === null) { //default value INPUT.className += ' noValue'; TD.appendChild(INPUT); } else { instance.view.wt.wtDom.fastInnerText(TD, '#bad value#'); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } var $input = $(INPUT); if (cellProperties.readOnly) { $input.on('click', function (event) { event.preventDefault(); }); } else { $input.on('mousedown', function (event) { event.stopPropagation(); //otherwise can confuse cell mousedown handler }); $input.on('mouseup', function (event) { event.stopPropagation(); //otherwise can confuse cell dblclick handler }); $input.on('change', function(){ if (this.checked) { instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate); } else { instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate); } }); } if(!instance.CheckboxRenderer || !instance.CheckboxRenderer.beforeKeyDownHookBound){ instance.CheckboxRenderer = { beforeKeyDownHookBound : true }; instance.addHook('beforeKeyDown', function(event){ if(event.keyCode == Handsontable.helper.keyCode.SPACE){ var selection = instance.getSelected(); var cell, checkbox, cellProperties; var selStart = { row: Math.min(selection[0], selection[2]), col: Math.min(selection[1], selection[3]) }; var selEnd = { row: Math.max(selection[0], selection[2]), col: Math.max(selection[1], selection[3]) }; for(var row = selStart.row; row <= selEnd.row; row++ ){ for(var col = selEnd.col; col <= selEnd.col; col++){ cell = instance.getCell(row, col); cellProperties = instance.getCellMeta(row, col); checkbox = cell.querySelectorAll('input[type=checkbox]'); if(checkbox.length > 0 && !cellProperties.readOnly){ if(!event.isImmediatePropagationStopped()){ event.stopImmediatePropagation(); event.preventDefault(); } for(var i = 0, len = checkbox.length; i < len; i++){ checkbox[i].checked = !checkbox[i].checked; $(checkbox[i]).trigger('change'); } } } } } }); } }; Handsontable.CheckboxRenderer = CheckboxRenderer; Handsontable.renderers.CheckboxRenderer = CheckboxRenderer; Handsontable.renderers.registerRenderer('checkbox', CheckboxRenderer); })(Handsontable); /** * Numeric cell renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var NumericRenderer = function (instance, TD, row, col, prop, value, cellProperties) { if (Handsontable.helper.isNumeric(value)) { if (typeof cellProperties.language !== 'undefined') { numeral.language(cellProperties.language) } value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/ instance.view.wt.wtDom.addClass(TD, 'htNumeric'); } Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties); }; Handsontable.NumericRenderer = NumericRenderer; //Left for backward compatibility with versions prior 0.10.0 Handsontable.renderers.NumericRenderer = NumericRenderer; Handsontable.renderers.registerRenderer('numeric', NumericRenderer); })(Handsontable); (function(Handosntable){ 'use strict'; var PasswordRenderer = function (instance, TD, row, col, prop, value, cellProperties) { Handsontable.renderers.TextRenderer.apply(this, arguments); value = TD.innerHTML; var hash; var hashLength = cellProperties.hashLength || value.length; var hashSymbol = cellProperties.hashSymbol || '*'; for( hash = ''; hash.split(hashSymbol).length - 1 < hashLength; hash += hashSymbol); instance.view.wt.wtDom.fastInnerHTML(TD, hash); }; Handosntable.PasswordRenderer = PasswordRenderer; Handosntable.renderers.PasswordRenderer = PasswordRenderer; Handosntable.renderers.registerRenderer('password', PasswordRenderer); })(Handsontable); (function (Handsontable) { function HtmlRenderer(instance, TD, row, col, prop, value, cellProperties){ Handsontable.renderers.cellDecorator.apply(this, arguments); Handsontable.Dom.fastInnerHTML(TD, value); } Handsontable.renderers.registerRenderer('html', HtmlRenderer); Handsontable.renderers.HtmlRenderer = HtmlRenderer; })(Handsontable); (function (Handsontable) { 'use strict'; Handsontable.EditorState = { VIRGIN: 'STATE_VIRGIN', //before editing EDITING: 'STATE_EDITING', WAITING: 'STATE_WAITING', //waiting for async validation FINISHED: 'STATE_FINISHED' }; function BaseEditor(instance) { this.instance = instance; this.state = Handsontable.EditorState.VIRGIN; this._opened = false; this._closeCallback = null; this.init(); } BaseEditor.prototype._fireCallbacks = function(result) { if(this._closeCallback){ this._closeCallback(result); this._closeCallback = null; } } BaseEditor.prototype.init = function(){}; BaseEditor.prototype.getValue = function(){ throw Error('Editor getValue() method unimplemented'); }; BaseEditor.prototype.setValue = function(newValue){ throw Error('Editor setValue() method unimplemented'); }; BaseEditor.prototype.open = function(){ throw Error('Editor open() method unimplemented'); }; BaseEditor.prototype.close = function(){ throw Error('Editor close() method unimplemented'); }; BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties){ this.TD = td; this.row = row; this.col = col; this.prop = prop; this.originalValue = originalValue; this.cellProperties = cellProperties; this.state = Handsontable.EditorState.VIRGIN; }; BaseEditor.prototype.extend = function(){ var baseClass = this.constructor; function Editor(){ baseClass.apply(this, arguments); } function inherit(Child, Parent){ function Bridge() { } Bridge.prototype = Parent.prototype; Child.prototype = new Bridge(); Child.prototype.constructor = Child; return Child; } return inherit(Editor, baseClass); }; BaseEditor.prototype.saveValue = function (val, ctrlDown) { if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells) var sel = this.instance.getSelected(); this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit'); } else { this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit'); } }; BaseEditor.prototype.beginEditing = function(initialValue){ if (this.state != Handsontable.EditorState.VIRGIN) { return; } if (this.cellProperties.readOnly) { return; } this.instance.view.scrollViewport({row: this.row, col: this.col}); this.instance.view.render(); this.state = Handsontable.EditorState.EDITING; initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue; this.setValue(Handsontable.helper.stringify(initialValue)); this.open(); this._opened = true; this.focus(); this.instance.view.render(); //only rerender the selections (FillHandle should disappear when beginediting is triggered) }; BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) { if (callback) { var previousCloseCallback = this._closeCallback; this._closeCallback = function (result) { if(previousCloseCallback){ previousCloseCallback(result); } callback(result); }; } if (this.isWaiting()) { return; } if (this.state == Handsontable.EditorState.VIRGIN) { var that = this; setTimeout(function () { that._fireCallbacks(true); }); return; } if (this.state == Handsontable.EditorState.EDITING) { if (restoreOriginalValue) { this.cancelChanges(); return; } var val = [ [String.prototype.trim.call(this.getValue())] //String.prototype.trim is defined in Walkontable polyfill.js ]; this.state = Handsontable.EditorState.WAITING; this.saveValue(val, ctrlDown); if(this.instance.getCellValidator(this.cellProperties)){ var that = this; this.instance.addHookOnce('afterValidate', function (result) { that.state = Handsontable.EditorState.FINISHED; that.discardEditor(result); }); } else { this.state = Handsontable.EditorState.FINISHED; this.discardEditor(true); } } }; BaseEditor.prototype.cancelChanges = function () { this.state = Handsontable.EditorState.FINISHED; this.discardEditor(); }; BaseEditor.prototype.discardEditor = function (result) { if (this.state !== Handsontable.EditorState.FINISHED) { return; } if (result === false && this.cellProperties.allowInvalid !== true) { //validator was defined and failed this.instance.selectCell(this.row, this.col); this.focus(); this.state = Handsontable.EditorState.EDITING; this._fireCallbacks(false); } else { this.close(); this._opened = false; this.state = Handsontable.EditorState.VIRGIN; this._fireCallbacks(true); } }; BaseEditor.prototype.isOpened = function(){ return this._opened; }; BaseEditor.prototype.isWaiting = function () { return this.state === Handsontable.EditorState.WAITING; }; Handsontable.editors.BaseEditor = BaseEditor; })(Handsontable); (function(Handsontable){ var TextEditor = Handsontable.editors.BaseEditor.prototype.extend(); TextEditor.prototype.init = function(){ this.createElements(); this.bindEvents(); }; TextEditor.prototype.getValue = function(){ return this.TEXTAREA.value }; TextEditor.prototype.setValue = function(newValue){ this.TEXTAREA.value = newValue; }; var onBeforeKeyDown = function onBeforeKeyDown(event){ var instance = this; var that = instance.getActiveEditor(); var keyCodes = Handsontable.helper.keyCode; var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) //Process only events that have been fired in the editor if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()){ return; } if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) { //when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea event.stopImmediatePropagation(); return; } switch (event.keyCode) { case keyCodes.ARROW_RIGHT: if (that.wtDom.getCaretPosition(that.TEXTAREA) !== that.TEXTAREA.value.length) { event.stopImmediatePropagation(); } break; case keyCodes.ARROW_LEFT: /* arrow left */ if (that.wtDom.getCaretPosition(that.TEXTAREA) !== 0) { event.stopImmediatePropagation(); } break; case keyCodes.ENTER: var selected = that.instance.getSelected(); var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]); if ((ctrlDown && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line if(that.isOpened()){ that.setValue(that.getValue() + '\n'); that.focus(); } else { that.beginEditing(that.originalValue + '\n') } event.stopImmediatePropagation(); } event.preventDefault(); //don't add newline to field break; case keyCodes.A: case keyCodes.X: case keyCodes.C: case keyCodes.V: if(ctrlDown){ event.stopImmediatePropagation(); //CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context) break; } case keyCodes.BACKSPACE: case keyCodes.DELETE: case keyCodes.HOME: case keyCodes.END: event.stopImmediatePropagation(); //backspace, delete, home, end should only work locally when cell is edited (not in table context) break; } }; TextEditor.prototype.open = function(){ this.refreshDimensions(); //need it instantly, to prevent https://github.com/warpech/jquery-handsontable/issues/348 this.instance.addHook('beforeKeyDown', onBeforeKeyDown); }; TextEditor.prototype.close = function(){ this.textareaParentStyle.display = 'none'; if (document.activeElement === this.TEXTAREA) { this.instance.listen(); //don't refocus the table if user focused some cell outside of HT on purpose } this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; TextEditor.prototype.focus = function(){ this.TEXTAREA.focus(); this.wtDom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length); }; TextEditor.prototype.createElements = function () { this.$body = $(document.body); this.wtDom = new WalkontableDom(); this.TEXTAREA = document.createElement('TEXTAREA'); this.$textarea = $(this.TEXTAREA); this.wtDom.addClass(this.TEXTAREA, 'handsontableInput'); this.textareaStyle = this.TEXTAREA.style; this.textareaStyle.width = 0; this.textareaStyle.height = 0; this.TEXTAREA_PARENT = document.createElement('DIV'); this.wtDom.addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder'); this.textareaParentStyle = this.TEXTAREA_PARENT.style; this.textareaParentStyle.top = 0; this.textareaParentStyle.left = 0; this.textareaParentStyle.display = 'none'; this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); this.instance.rootElement[0].appendChild(this.TEXTAREA_PARENT); var that = this; Handsontable.PluginHooks.add('afterRender', function () { that.instance.registerTimeout('refresh_editor_dimensions', function () { that.refreshDimensions(); }, 0); }); }; TextEditor.prototype.refreshDimensions = function () { if (this.state !== Handsontable.EditorState.EDITING) { return; } ///start prepare textarea position this.TD = this.instance.getCell(this.row, this.col); if (!this.TD) { //TD is outside of the viewport. Otherwise throws exception when scrolling the table while a cell is edited return; } var $td = $(this.TD); //because old td may have been scrolled out with scrollViewport var currentOffset = this.wtDom.offset(this.TD); var containerOffset = this.wtDom.offset(this.instance.rootElement[0]); var scrollTop = this.instance.rootElement.scrollTop(); var scrollLeft = this.instance.rootElement.scrollLeft(); var editTop = currentOffset.top - containerOffset.top + scrollTop - 1; var editLeft = currentOffset.left - containerOffset.left + scrollLeft - 1; var settings = this.instance.getSettings(); var rowHeadersCount = settings.rowHeaders === false ? 0 : 1; var colHeadersCount = settings.colHeaders === false ? 0 : 1; if (editTop < 0) { editTop = 0; } if (editLeft < 0) { editLeft = 0; } if (rowHeadersCount > 0 && parseInt($td.css('border-top-width'), 10) > 0) { editTop += 1; } if (colHeadersCount > 0 && parseInt($td.css('border-left-width'), 10) > 0) { editLeft += 1; } this.textareaParentStyle.top = editTop + 'px'; this.textareaParentStyle.left = editLeft + 'px'; ///end prepare textarea position var width = $td.width() , maxWidth = this.instance.view.maximumVisibleElementWidth(editLeft) - 10 //10 is TEXTAREAs border and padding , height = $td.outerHeight() - 4 , maxHeight = this.instance.view.maximumVisibleElementHeight(editTop) - 5; //10 is TEXTAREAs border and padding if (parseInt($td.css('border-top-width'), 10) > 0) { height -= 1; } if (parseInt($td.css('border-left-width'), 10) > 0) { if (rowHeadersCount > 0) { width -= 1; } } //in future may change to pure JS http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize this.$textarea.autoResize({ minHeight: Math.min(height, maxHeight), maxHeight: maxHeight, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar) minWidth: Math.min(width, maxWidth), maxWidth: maxWidth, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar) animate: false, extraSpace: 0 }); this.textareaParentStyle.display = 'block'; }; TextEditor.prototype.bindEvents = function () { this.$textarea.on('cut.editor', function (event) { event.stopPropagation(); }); this.$textarea.on('paste.editor', function (event) { event.stopPropagation(); }); }; Handsontable.editors.TextEditor = TextEditor; Handsontable.editors.registerEditor('text', Handsontable.editors.TextEditor); })(Handsontable); (function(Handsontable){ //Blank editor, because all the work is done by renderer var CheckboxEditor = Handsontable.editors.BaseEditor.prototype.extend(); CheckboxEditor.prototype.beginEditing = function () { this.saveValue([ [!this.originalValue] ]); }; CheckboxEditor.prototype.finishEditing = function () {}; CheckboxEditor.prototype.init = function () {}; CheckboxEditor.prototype.open = function () {}; CheckboxEditor.prototype.close = function () {}; CheckboxEditor.prototype.getValue = function () {}; CheckboxEditor.prototype.setValue = function () {}; CheckboxEditor.prototype.focus = function () {}; Handsontable.editors.CheckboxEditor = CheckboxEditor; Handsontable.editors.registerEditor('checkbox', CheckboxEditor); })(Handsontable); (function (Handsontable) { var DateEditor = Handsontable.editors.TextEditor.prototype.extend(); DateEditor.prototype.init = function () { if (!$.datepicker) { throw new Error("jQuery UI Datepicker dependency not found. Did you forget to include jquery-ui.custom.js or its substitute?"); } Handsontable.editors.TextEditor.prototype.init.apply(this, arguments); this.isCellEdited = false; var that = this; this.instance.addHook('afterDestroy', function () { that.destroyElements(); }) }; DateEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); this.datePicker = document.createElement('DIV'); this.instance.view.wt.wtDom.addClass(this.datePicker, 'htDatepickerHolder'); this.datePickerStyle = this.datePicker.style; this.datePickerStyle.position = 'absolute'; this.datePickerStyle.top = 0; this.datePickerStyle.left = 0; this.datePickerStyle.zIndex = 99; document.body.appendChild(this.datePicker); this.$datePicker = $(this.datePicker); var that = this; var defaultOptions = { dateFormat: "yy-mm-dd", showButtonPanel: true, changeMonth: true, changeYear: true, onSelect: function (dateStr) { that.setValue(dateStr); that.finishEditing(false); } }; this.$datePicker.datepicker(defaultOptions); /** * Prevent recognizing clicking on jQuery Datepicker as clicking outside of table */ this.$datePicker.on('mousedown', function (event) { event.stopPropagation(); }); this.hideDatepicker(); }; DateEditor.prototype.destroyElements = function () { this.$datePicker.datepicker('destroy'); this.$datePicker.remove(); }; DateEditor.prototype.beginEditing = function (row, col, prop, useOriginalValue, suffix) { Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments); this.showDatepicker(); }; DateEditor.prototype.finishEditing = function (isCancelled, ctrlDown) { this.hideDatepicker(); Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments); }; DateEditor.prototype.showDatepicker = function () { var $td = $(this.TD); var offset = $td.offset(); this.datePickerStyle.top = (offset.top + $td.height()) + 'px'; this.datePickerStyle.left = offset.left + 'px'; var dateOptions = { defaultDate: this.originalValue || void 0 }; $.extend(dateOptions, this.cellProperties); this.$datePicker.datepicker("option", dateOptions); if (this.originalValue) { this.$datePicker.datepicker("setDate", this.originalValue); } this.datePickerStyle.display = 'block'; }; DateEditor.prototype.hideDatepicker = function () { this.datePickerStyle.display = 'none'; }; Handsontable.editors.DateEditor = DateEditor; Handsontable.editors.registerEditor('date', DateEditor); })(Handsontable); /** * This is inception. Using Handsontable as Handsontable editor */ (function (Handsontable) { "use strict"; var HandsontableEditor = Handsontable.editors.TextEditor.prototype.extend(); HandsontableEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); var DIV = document.createElement('DIV'); DIV.className = 'handsontableEditor'; this.TEXTAREA_PARENT.appendChild(DIV); this.$htContainer = $(DIV); this.$htContainer.handsontable(); }; HandsontableEditor.prototype.prepare = function (td, row, col, prop, value, cellProperties) { Handsontable.editors.TextEditor.prototype.prepare.apply(this, arguments); var parent = this; var options = { startRows: 0, startCols: 0, minRows: 0, minCols: 0, className: 'listbox', copyPaste: false, cells: function () { return { readOnly: true } }, fillHandle: false, afterOnCellMouseDown: function () { var value = this.getValue(); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value parent.setValue(value); } parent.instance.destroyEditor(); }, beforeOnKeyDown: function (event) { var instance = this; switch (event.keyCode) { case Handsontable.helper.keyCode.ESCAPE: parent.instance.destroyEditor(true); event.stopImmediatePropagation(); event.preventDefault(); break; case Handsontable.helper.keyCode.ENTER: //enter var sel = instance.getSelected(); var value = this.getDataAtCell(sel[0], sel[1]); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value parent.setValue(value); } parent.instance.destroyEditor(); break; case Handsontable.helper.keyCode.ARROW_UP: if (instance.getSelected() && instance.getSelected()[0] == 0 && !parent.cellProperties.strict){ instance.deselectCell(); parent.instance.listen(); parent.focus(); event.preventDefault(); event.stopImmediatePropagation(); } break; } } }; if (this.cellProperties.handsontable) { options = $.extend(options, cellProperties.handsontable); } this.$htContainer.handsontable('destroy'); this.$htContainer.handsontable(options); }; var onBeforeKeyDown = function (event) { if (event.isImmediatePropagationStopped()) { return; } var editor = this.getActiveEditor(); var innerHOT = editor.$htContainer.handsontable('getInstance'); if (event.keyCode == Handsontable.helper.keyCode.ARROW_DOWN) { if (!innerHOT.getSelected()){ innerHOT.selectCell(0, 0); } else { var selectedRow = innerHOT.getSelected()[0]; var rowToSelect = selectedRow < innerHOT.countRows() - 1 ? selectedRow + 1 : selectedRow; innerHOT.selectCell(rowToSelect, 0); } event.preventDefault(); event.stopImmediatePropagation(); } }; HandsontableEditor.prototype.open = function () { this.instance.addHook('beforeKeyDown', onBeforeKeyDown); Handsontable.editors.TextEditor.prototype.open.apply(this, arguments); this.$htContainer.handsontable('render'); if (this.cellProperties.strict) { this.$htContainer.handsontable('selectCell', 0, 0); this.$textarea[0].style.visibility = 'hidden'; } else { this.$htContainer.handsontable('deselectCell'); this.$textarea[0].style.visibility = 'visible'; } this.wtDom.setCaretPosition(this.$textarea[0], 0, this.$textarea[0].value.length); }; HandsontableEditor.prototype.close = function () { this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); this.instance.listen(); Handsontable.editors.TextEditor.prototype.close.apply(this, arguments); }; HandsontableEditor.prototype.focus = function () { this.instance.listen(); Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments); }; HandsontableEditor.prototype.beginEditing = function (initialValue) { var onBeginEditing = this.instance.getSettings().onBeginEditing; if (onBeginEditing && onBeginEditing() === false) { return; } Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments); }; HandsontableEditor.prototype.finishEditing = function (isCancelled, ctrlDown) { if (this.$htContainer.handsontable('isListening')) { //if focus is still in the HOT editor this.instance.listen(); //return the focus to the parent HOT instance } if (this.$htContainer.handsontable('getSelected')) { var value = this.$htContainer.handsontable('getInstance').getValue(); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value this.setValue(value); } } return Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments); }; Handsontable.editors.HandsontableEditor = HandsontableEditor; Handsontable.editors.registerEditor('handsontable', HandsontableEditor); })(Handsontable); (function (Handsontable) { var AutocompleteEditor = Handsontable.editors.HandsontableEditor.prototype.extend(); AutocompleteEditor.prototype.init = function () { Handsontable.editors.HandsontableEditor.prototype.init.apply(this, arguments); this.query = null; }; AutocompleteEditor.prototype.createElements = function(){ Handsontable.editors.HandsontableEditor.prototype.createElements.apply(this, arguments); this.$htContainer.addClass('autocompleteEditor'); }; AutocompleteEditor.prototype.bindEvents = function(){ var that = this; this.$textarea.on('keydown.autocompleteEditor', function(event){ if(!Handsontable.helper.isMetaKey(event.keyCode) || [Handsontable.helper.keyCode.BACKSPACE, Handsontable.helper.keyCode.DELETE].indexOf(event.keyCode) != -1){ setTimeout(function () { that.queryChoices(that.$textarea.val()); }); } else if (event.keyCode == Handsontable.helper.keyCode.ENTER && that.cellProperties.strict !== true){ that.$htContainer.handsontable('deselectCell'); } }); this.$htContainer.on('mouseenter', function () { that.$htContainer.handsontable('deselectCell'); }); this.$htContainer.on('mouseleave', function () { that.queryChoices(that.query); }); Handsontable.editors.HandsontableEditor.prototype.bindEvents.apply(this, arguments); }; AutocompleteEditor.prototype.beginEditing = function () { Handsontable.editors.HandsontableEditor.prototype.beginEditing.apply(this, arguments); var that = this; setTimeout(function () { that.queryChoices(that.TEXTAREA.value); }); var hot = this.$htContainer.handsontable('getInstance'); hot.updateSettings({ 'colWidths': [this.wtDom.outerWidth(this.TEXTAREA) - 2], afterRenderer: function (TD, row, col, prop, value) { var caseSensitive = this.getCellMeta(row, col).filteringCaseSensitive === true; var indexOfMatch = caseSensitive ? value.indexOf(that.query) : value.toLowerCase().indexOf(that.query.toLowerCase()); if(indexOfMatch != -1){ var match = value.substr(indexOfMatch, that.query.length); TD.innerHTML = value.replace(match, '<strong>' + match + '</strong>'); } } }); }; var onBeforeKeyDownInner; AutocompleteEditor.prototype.open = function () { var parent = this; onBeforeKeyDownInner = function (event) { var instance = this; if (event.keyCode == Handsontable.helper.keyCode.ARROW_UP){ if (instance.getSelected() && instance.getSelected()[0] == 0){ if(!parent.cellProperties.strict){ instance.deselectCell(); } parent.instance.listen(); parent.focus(); event.preventDefault(); event.stopImmediatePropagation(); } } }; this.$htContainer.handsontable('getInstance').addHook('beforeKeyDown', onBeforeKeyDownInner); Handsontable.editors.HandsontableEditor.prototype.open.apply(this, arguments); this.$textarea[0].style.visibility = 'visible'; parent.focus(); }; AutocompleteEditor.prototype.close = function () { this.$htContainer.handsontable('getInstance').removeHook('beforeKeyDown', onBeforeKeyDownInner); Handsontable.editors.HandsontableEditor.prototype.close.apply(this, arguments); }; AutocompleteEditor.prototype.queryChoices = function(query){ this.query = query; if (typeof this.cellProperties.source == 'function'){ var that = this; this.cellProperties.source(query, function(choices){ that.updateChoicesList(choices) }); } else if (Handsontable.helper.isArray(this.cellProperties.source)) { var choices; if(!query || this.cellProperties.filter === false){ choices = this.cellProperties.source; } else { var filteringCaseSensitive = this.cellProperties.filteringCaseSensitive === true; var lowerCaseQuery = query.toLowerCase(); choices = this.cellProperties.source.filter(function(choice){ if (filteringCaseSensitive) { return choice.indexOf(query) != -1; } else { return choice.toLowerCase().indexOf(lowerCaseQuery) != -1; } }); } this.updateChoicesList(choices) } else { this.updateChoicesList([]); } }; function findItemIndexToHighlight(items, value){ var bestMatch = {}; var valueLength = value.length; var currentItem; var indexOfValue; var charsLeft; for(var i = 0, len = items.length; i < len; i++){ currentItem = items[i]; if(valueLength > 0){ indexOfValue = currentItem.indexOf(value) } else { indexOfValue = currentItem === value ? 0 : -1; } if(indexOfValue == -1) continue; charsLeft = currentItem.length - indexOfValue - valueLength; if( typeof bestMatch.indexOfValue == 'undefined' || bestMatch.indexOfValue > indexOfValue || ( bestMatch.indexOfValue == indexOfValue && bestMatch.charsLeft > charsLeft ) ){ bestMatch.indexOfValue = indexOfValue; bestMatch.charsLeft = charsLeft; bestMatch.index = i; } } return bestMatch.index; } AutocompleteEditor.prototype.updateChoicesList = function (choices) { this.$htContainer.handsontable('loadData', Handsontable.helper.pivot([choices])); var value = this.getValue(); var rowToHighlight; if(this.cellProperties.strict === true){ rowToHighlight = findItemIndexToHighlight(choices, value); if ( typeof rowToHighlight == 'undefined' && this.cellProperties.allowInvalid === false){ rowToHighlight = 0; } } if(typeof rowToHighlight == 'undefined'){ this.$htContainer.handsontable('deselectCell'); } else { this.$htContainer.handsontable('selectCell', rowToHighlight, 0); } this.focus(); }; Handsontable.editors.AutocompleteEditor = AutocompleteEditor; Handsontable.editors.registerEditor('autocomplete', AutocompleteEditor); })(Handsontable); (function(Handsontable){ var PasswordEditor = Handsontable.editors.TextEditor.prototype.extend(); var wtDom = new WalkontableDom(); PasswordEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); this.TEXTAREA = document.createElement('input'); this.TEXTAREA.setAttribute('type', 'password'); this.TEXTAREA.className = 'handsontableInput'; this.textareaStyle = this.TEXTAREA.style; this.textareaStyle.width = 0; this.textareaStyle.height = 0; this.$textarea = $(this.TEXTAREA); wtDom.empty(this.TEXTAREA_PARENT); this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); }; Handsontable.editors.PasswordEditor = PasswordEditor; Handsontable.editors.registerEditor('password', PasswordEditor); })(Handsontable); (function (Handsontable) { var SelectEditor = Handsontable.editors.BaseEditor.prototype.extend(); SelectEditor.prototype.init = function(){ this.select = $('<select />') .addClass('htSelectEditor') .hide(); this.instance.rootElement.append(this.select); }; SelectEditor.prototype.prepare = function(){ Handsontable.editors.BaseEditor.prototype.prepare.apply(this, arguments); var selectOptions = this.cellProperties.selectOptions; var options; if (typeof selectOptions == 'function'){ options = this.prepareOptions(selectOptions(this.row, this.col, this.prop)) } else { options = this.prepareOptions(selectOptions); } var optionElements = []; for (var option in options){ if (options.hasOwnProperty(option)){ var optionElement = $('<option />'); optionElement.val(option); optionElement.html(options[option]); optionElements.push(optionElement); } } this.select.empty(); this.select.append(optionElements); }; SelectEditor.prototype.prepareOptions = function(optionsToPrepare){ var preparedOptions = {}; if (Handsontable.helper.isArray(optionsToPrepare)){ for(var i = 0, len = optionsToPrepare.length; i < len; i++){ preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i]; } } else if (typeof optionsToPrepare == 'object') { preparedOptions = optionsToPrepare; } return preparedOptions; }; SelectEditor.prototype.getValue = function () { return this.select.val(); }; SelectEditor.prototype.setValue = function (value) { this.select.val(value); }; var onBeforeKeyDown = function (event) { var instance = this; var editor = instance.getActiveEditor(); switch (event.keyCode){ case Handsontable.helper.keyCode.ARROW_UP: var previousOption = editor.select.find('option:selected').prev(); if (previousOption.length == 1){ previousOption.prop('selected', true); } event.stopImmediatePropagation(); event.preventDefault(); break; case Handsontable.helper.keyCode.ARROW_DOWN: var nextOption = editor.select.find('option:selected').next(); if (nextOption.length == 1){ nextOption.prop('selected', true); } event.stopImmediatePropagation(); event.preventDefault(); break; } }; SelectEditor.prototype.open = function () { this.select.css({ height: $(this.TD).height(), 'min-width' : $(this.TD).outerWidth() }); this.select.show(); this.select.offset($(this.TD).offset()); this.instance.addHook('beforeKeyDown', onBeforeKeyDown); }; SelectEditor.prototype.close = function () { this.select.hide(); this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; SelectEditor.prototype.focus = function () { this.select.focus(); }; Handsontable.editors.SelectEditor = SelectEditor; Handsontable.editors.registerEditor('select', SelectEditor); })(Handsontable); (function (Handsontable) { var DropdownEditor = Handsontable.editors.AutocompleteEditor.prototype.extend(); DropdownEditor.prototype.prepare = function () { Handsontable.editors.AutocompleteEditor.prototype.prepare.apply(this, arguments); this.cellProperties.filter = false; this.cellProperties.strict = true; }; Handsontable.editors.DropdownEditor = DropdownEditor; Handsontable.editors.registerEditor('dropdown', DropdownEditor); })(Handsontable); /** * Numeric cell validator * @param {*} value - Value of edited cell * @param {*} callback - Callback called with validation result */ Handsontable.NumericValidator = function (value, callback) { if (value === null) { value = ''; } callback(/^-?\d*\.?\d*$/.test(value)); }; /** * Function responsible for validation of autocomplete value * @param {*} value - Value of edited cell * @param {*} calback - Callback called with validation result */ var process = function (value, callback) { var originalVal = value; var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null; return function (source) { var found = false; for (var s = 0, slen = source.length; s < slen; s++) { if (originalVal === source[s]) { found = true; //perfect match break; } else if (lowercaseVal === source[s].toLowerCase()) { // changes[i][3] = source[s]; //good match, fix the case << TODO? found = true; break; } } callback(found); } }; /** * Autocomplete cell validator * @param {*} value - Value of edited cell * @param {*} calback - Callback called with validation result */ Handsontable.AutocompleteValidator = function (value, callback) { if (this.strict && this.source) { typeof this.source === 'function' ? this.source(value, process(value, callback)) : process(value, callback)(this.source); } else { callback(true); } }; /** * Cell type is just a shortcut for setting bunch of cellProperties (used in getCellMeta) */ Handsontable.AutocompleteCell = { editor: Handsontable.editors.AutocompleteEditor, renderer: Handsontable.renderers.AutocompleteRenderer, validator: Handsontable.AutocompleteValidator }; Handsontable.CheckboxCell = { editor: Handsontable.editors.CheckboxEditor, renderer: Handsontable.renderers.CheckboxRenderer }; Handsontable.TextCell = { editor: Handsontable.editors.TextEditor, renderer: Handsontable.renderers.TextRenderer }; Handsontable.NumericCell = { editor: Handsontable.editors.TextEditor, renderer: Handsontable.renderers.NumericRenderer, validator: Handsontable.NumericValidator, dataType: 'number' }; Handsontable.DateCell = { editor: Handsontable.editors.DateEditor, renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell }; Handsontable.HandsontableCell = { editor: Handsontable.editors.HandsontableEditor, renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell }; Handsontable.PasswordCell = { editor: Handsontable.editors.PasswordEditor, renderer: Handsontable.renderers.PasswordRenderer, copyable: false }; Handsontable.DropdownCell = { editor: Handsontable.editors.DropdownEditor, renderer: Handsontable.renderers.AutocompleteRenderer, //displays small gray arrow on right side of the cell validator: Handsontable.AutocompleteValidator }; //here setup the friendly aliases that are used by cellProperties.type Handsontable.cellTypes = { text: Handsontable.TextCell, date: Handsontable.DateCell, numeric: Handsontable.NumericCell, checkbox: Handsontable.CheckboxCell, autocomplete: Handsontable.AutocompleteCell, handsontable: Handsontable.HandsontableCell, password: Handsontable.PasswordCell, dropdown: Handsontable.DropdownCell }; //here setup the friendly aliases that are used by cellProperties.renderer and cellProperties.editor Handsontable.cellLookup = { validator: { numeric: Handsontable.NumericValidator, autocomplete: Handsontable.AutocompleteValidator } }; /* * jQuery.fn.autoResize 1.1+ * -- * https://github.com/warpech/jQuery.fn.autoResize * * This fork differs from others in a way that it autoresizes textarea in 2-dimensions (horizontally and vertically). * It was originally forked from alexbardas's repo but maybe should be merged with dpashkevich's repo in future. * * originally forked from: * https://github.com/jamespadolsey/jQuery.fn.autoResize * which is now located here: * https://github.com/alexbardas/jQuery.fn.autoResize * though the mostly maintained for is here: * https://github.com/dpashkevich/jQuery.fn.autoResize/network * * -- * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://sam.zoy.org/wtfpl/COPYING for more details. */ (function($){ autoResize.defaults = { onResize: function(){}, animate: { duration: 200, complete: function(){} }, extraSpace: 50, minHeight: 'original', maxHeight: 500, minWidth: 'original', maxWidth: 500 }; autoResize.cloneCSSProperties = [ 'lineHeight', 'textDecoration', 'letterSpacing', 'fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust', 'padding' ]; autoResize.cloneCSSValues = { position: 'absolute', top: -9999, left: -9999, opacity: 0, overflow: 'hidden', overflowX: 'hidden', overflowY: 'hidden', border: '1px solid black', padding: '0.49em' //this must be about the width of caps W character }; autoResize.resizableFilterSelector = 'textarea,input:not(input[type]),input[type=text],input[type=password]'; autoResize.AutoResizer = AutoResizer; $.fn.autoResize = autoResize; function autoResize(config) { this.filter(autoResize.resizableFilterSelector).each(function(){ new AutoResizer( $(this), config ); }); return this; } function AutoResizer(el, config) { if(this.clones) return; this.config = $.extend({}, autoResize.defaults, config); this.el = el; this.nodeName = el[0].nodeName.toLowerCase(); this.previousScrollTop = null; if (config.maxWidth === 'original') config.maxWidth = el.width(); if (config.minWidth === 'original') config.minWidth = el.width(); if (config.maxHeight === 'original') config.maxHeight = el.height(); if (config.minHeight === 'original') config.minHeight = el.height(); if (this.nodeName === 'textarea') { el.css({ resize: 'none', overflowY: 'none' }); } el.data('AutoResizer', this); this.createClone(); this.injectClone(); this.bind(); } AutoResizer.prototype = { bind: function() { var check = $.proxy(function(){ this.check(); return true; }, this); this.unbind(); this.el .bind('keyup.autoResize', check) //.bind('keydown.autoResize', check) .bind('change.autoResize', check); this.check(null, true); }, unbind: function() { this.el.unbind('.autoResize'); }, createClone: function() { var el = this.el, self = this, config = this.config; this.clones = $(); if (config.minHeight !== 'original' || config.maxHeight !== 'original') { this.hClone = el.clone().height('auto'); this.clones = this.clones.add(this.hClone); } if (config.minWidth !== 'original' || config.maxWidth !== 'original') { this.wClone = $('<div/>').width('auto').css({ whiteSpace: 'nowrap', 'float': 'left' }); this.clones = this.clones.add(this.wClone); } $.each(autoResize.cloneCSSProperties, function(i, p){ self.clones.css(p, el.css(p)); }); this.clones .removeAttr('name') .removeAttr('id') .attr('tabIndex', -1) .css(autoResize.cloneCSSValues) .css('overflowY', 'scroll'); }, check: function(e, immediate) { var config = this.config, wClone = this.wClone, hClone = this.hClone, el = this.el, value = el.val(); if (wClone) { wClone.text(value); // Calculate new width + whether to change var cloneWidth = wClone.outerWidth(), newWidth = (cloneWidth + config.extraSpace) >= config.minWidth ? cloneWidth + config.extraSpace : config.minWidth, currentWidth = el.width(); newWidth = Math.min(newWidth, config.maxWidth); if ( (newWidth < currentWidth && newWidth >= config.minWidth) || (newWidth >= config.minWidth && newWidth <= config.maxWidth) ) { config.onResize.call(el); el.scrollLeft(0); config.animate && !immediate ? el.stop(1,1).animate({ width: newWidth }, config.animate) : el.width(newWidth); } } if (hClone) { if (newWidth) { hClone.width(newWidth); } hClone.height(0).val(value).scrollTop(10000); var scrollTop = hClone[0].scrollTop + config.extraSpace; // Don't do anything if scrollTop hasen't changed: if (this.previousScrollTop === scrollTop) { return; } this.previousScrollTop = scrollTop; if (scrollTop >= config.maxHeight) { scrollTop = config.maxHeight; } if (scrollTop < config.minHeight) { scrollTop = config.minHeight; } if(scrollTop == config.maxHeight && newWidth == config.maxWidth) { el.css('overflowY', 'scroll'); } else { el.css('overflowY', 'hidden'); } config.onResize.call(el); // Either animate or directly apply height: config.animate && !immediate ? el.stop(1,1).animate({ height: scrollTop }, config.animate) : el.height(scrollTop); } }, destroy: function() { this.unbind(); this.el.removeData('AutoResizer'); this.clones.remove(); delete this.el; delete this.hClone; delete this.wClone; delete this.clones; }, injectClone: function() { ( autoResize.cloneContainer || (autoResize.cloneContainer = $('<arclones/>').appendTo('body')) ).empty().append(this.clones); //this should be refactored so that a node is never cloned more than once } }; })(jQuery); /** * SheetClip - Spreadsheet Clipboard Parser * version 0.2 * * This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice, * Google Docs and Microsoft Excel. * * Copyright 2012, Marcin Warpechowski * Licensed under the MIT license. * http://github.com/warpech/sheetclip/ */ /*jslint white: true*/ (function (global) { "use strict"; function countQuotes(str) { return str.split('"').length - 1; } global.SheetClip = { parse: function (str) { var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last; rows = str.split('\n'); if (rows.length > 1 && rows[rows.length - 1] === '') { rows.pop(); } for (r = 0, rlen = rows.length; r < rlen; r += 1) { rows[r] = rows[r].split('\t'); for (c = 0, clen = rows[r].length; c < clen; c += 1) { if (!arr[a]) { arr[a] = []; } if (multiline && c === 0) { last = arr[a].length - 1; arr[a][last] = arr[a][last] + '\n' + rows[r][0]; if (multiline && (countQuotes(rows[r][0]) & 1)) { //& 1 is a bitwise way of performing mod 2 multiline = false; arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"'); } } else { if (c === clen - 1 && rows[r][c].indexOf('"') === 0) { arr[a].push(rows[r][c].substring(1).replace(/""/g, '"')); multiline = true; } else { arr[a].push(rows[r][c].replace(/""/g, '"')); multiline = false; } } } if (!multiline) { a += 1; } } return arr; }, stringify: function (arr) { var r, rlen, c, clen, str = '', val; for (r = 0, rlen = arr.length; r < rlen; r += 1) { for (c = 0, clen = arr[r].length; c < clen; c += 1) { if (c > 0) { str += '\t'; } val = arr[r][c]; if (typeof val === 'string') { if (val.indexOf('\n') > -1) { str += '"' + val.replace(/"/g, '""') + '"'; } else { str += val; } } else if (val === null || val === void 0) { //void 0 resolves to undefined str += ''; } else { str += val; } } str += '\n'; } return str; } }; }(window)); /** * CopyPaste.js * Creates a textarea that stays hidden on the page and gets focused when user presses CTRL while not having a form input focused * In future we may implement a better driver when better APIs are available * @constructor */ var CopyPaste = (function () { var instance; return { getInstance: function () { if (!instance) { instance = new CopyPasteClass(); } else if (instance.hasBeenDestroyed()){ instance.init(); } instance.refCounter++; return instance; } }; })(); function CopyPasteClass() { this.refCounter = 0; this.init(); } CopyPasteClass.prototype.init = function () { var that = this , style , parent; this.copyCallbacks = []; this.cutCallbacks = []; this.pasteCallbacks = []; this.listenerElement = document.documentElement; parent = document.body; if (document.getElementById('CopyPasteDiv')) { this.elDiv = document.getElementById('CopyPasteDiv'); this.elTextarea = this.elDiv.firstChild; } else { this.elDiv = document.createElement('DIV'); this.elDiv.id = 'CopyPasteDiv'; style = this.elDiv.style; style.position = 'fixed'; style.top = 0; style.left = 0; parent.appendChild(this.elDiv); this.elTextarea = document.createElement('TEXTAREA'); this.elTextarea.className = 'copyPaste'; style = this.elTextarea.style; style.width = '1px'; style.height = '1px'; this.elDiv.appendChild(this.elTextarea); if (typeof style.opacity !== 'undefined') { style.opacity = 0; } else { /*@cc_on @if (@_jscript) if(typeof style.filter === 'string') { style.filter = 'alpha(opacity=0)'; } @end @*/ } } this.keydownListener = function (event) { var isCtrlDown = false; if (event.metaKey) { //mac isCtrlDown = true; } else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { //pc isCtrlDown = true; } if (isCtrlDown) { if (document.activeElement !== that.elTextarea && (that.getSelectionText() != '' || ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(document.activeElement.nodeName) != -1)) { return; //this is needed by fragmentSelection in Handsontable. Ignore copypaste.js behavior if fragment of cell text is selected } that.selectNodeText(that.elTextarea); setTimeout(function () { that.selectNodeText(that.elTextarea); }, 0); } /* 67 = c * 86 = v * 88 = x */ if (isCtrlDown && (event.keyCode === 67 || event.keyCode === 86 || event.keyCode === 88)) { // that.selectNodeText(that.elTextarea); if (event.keyCode === 88) { //works in all browsers, incl. Opera < 12.12 setTimeout(function () { that.triggerCut(event); }, 0); } else if (event.keyCode === 86) { setTimeout(function () { that.triggerPaste(event); }, 0); } } } this._bindEvent(this.listenerElement, 'keydown', this.keydownListener); }; //http://jsperf.com/textara-selection //http://stackoverflow.com/questions/1502385/how-can-i-make-this-code-work-in-ie CopyPasteClass.prototype.selectNodeText = function (el) { el.select(); }; //http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text CopyPasteClass.prototype.getSelectionText = function () { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }; CopyPasteClass.prototype.copyable = function (str) { if (typeof str !== 'string' && str.toString === void 0) { throw new Error('copyable requires string parameter'); } this.elTextarea.value = str; }; /*CopyPasteClass.prototype.onCopy = function (fn) { this.copyCallbacks.push(fn); };*/ CopyPasteClass.prototype.onCut = function (fn) { this.cutCallbacks.push(fn); }; CopyPasteClass.prototype.onPaste = function (fn) { this.pasteCallbacks.push(fn); }; CopyPasteClass.prototype.removeCallback = function (fn) { var i, ilen; for (i = 0, ilen = this.copyCallbacks.length; i < ilen; i++) { if (this.copyCallbacks[i] === fn) { this.copyCallbacks.splice(i, 1); return true; } } for (i = 0, ilen = this.cutCallbacks.length; i < ilen; i++) { if (this.cutCallbacks[i] === fn) { this.cutCallbacks.splice(i, 1); return true; } } for (i = 0, ilen = this.pasteCallbacks.length; i < ilen; i++) { if (this.pasteCallbacks[i] === fn) { this.pasteCallbacks.splice(i, 1); return true; } } return false; }; CopyPasteClass.prototype.triggerCut = function (event) { var that = this; if (that.cutCallbacks) { setTimeout(function () { for (var i = 0, ilen = that.cutCallbacks.length; i < ilen; i++) { that.cutCallbacks[i](event); } }, 50); } }; CopyPasteClass.prototype.triggerPaste = function (event, str) { var that = this; if (that.pasteCallbacks) { setTimeout(function () { var val = (str || that.elTextarea.value).replace(/\n$/, ''); //remove trailing newline for (var i = 0, ilen = that.pasteCallbacks.length; i < ilen; i++) { that.pasteCallbacks[i](val, event); } }, 50); } }; CopyPasteClass.prototype.destroy = function () { if(!this.hasBeenDestroyed() && --this.refCounter == 0){ if (this.elDiv && this.elDiv.parentNode) { this.elDiv.parentNode.removeChild(this.elDiv); } this._unbindEvent(this.listenerElement, 'keydown', this.keydownListener); } }; CopyPasteClass.prototype.hasBeenDestroyed = function () { return !this.refCounter; }; //old version used this: // - http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/ // - http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization //but that cannot work with jQuery.trigger CopyPasteClass.prototype._bindEvent = (function () { if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests) return function (elem, type, cb) { $(elem).on(type + '.copypaste', cb); }; } else { return function (elem, type, cb) { elem.addEventListener(type, cb, false); //sorry, IE8 will only work with jQuery }; } })(); CopyPasteClass.prototype._unbindEvent = (function () { if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests) return function (elem, type, cb) { $(elem).off(type + '.copypaste', cb); }; } else { return function (elem, type, cb) { elem.removeEventListener(type, cb, false); //sorry, IE8 will only work with jQuery }; } })(); // json-patch-duplex.js 0.3.6 // (c) 2013 Joachim Wester // MIT license var jsonpatch; (function (jsonpatch) { var objOps = { add: function (obj, key) { obj[key] = this.value; return true; }, remove: function (obj, key) { delete obj[key]; return true; }, replace: function (obj, key) { obj[key] = this.value; return true; }, move: function (obj, key, tree) { var temp = { op: "_get", path: this.from }; apply(tree, [temp]); apply(tree, [ { op: "remove", path: this.from } ]); apply(tree, [ { op: "add", path: this.path, value: temp.value } ]); return true; }, copy: function (obj, key, tree) { var temp = { op: "_get", path: this.from }; apply(tree, [temp]); apply(tree, [ { op: "add", path: this.path, value: temp.value } ]); return true; }, test: function (obj, key) { return (JSON.stringify(obj[key]) === JSON.stringify(this.value)); }, _get: function (obj, key) { this.value = obj[key]; } }; var arrOps = { add: function (arr, i) { arr.splice(i, 0, this.value); return true; }, remove: function (arr, i) { arr.splice(i, 1); return true; }, replace: function (arr, i) { arr[i] = this.value; return true; }, move: objOps.move, copy: objOps.copy, test: objOps.test, _get: objOps._get }; var observeOps = { add: function (patches, path) { var patch = { op: "add", path: path + escapePathComponent(this.name), value: this.object[this.name] }; patches.push(patch); }, 'delete': function (patches, path) { var patch = { op: "remove", path: path + escapePathComponent(this.name) }; patches.push(patch); }, update: function (patches, path) { var patch = { op: "replace", path: path + escapePathComponent(this.name), value: this.object[this.name] }; patches.push(patch); } }; function escapePathComponent(str) { if (str.indexOf('/') === -1 && str.indexOf('~') === -1) return str; return str.replace(/~/g, '~0').replace(/\//g, '~1'); } function _getPathRecursive(root, obj) { var found; for (var key in root) { if (root.hasOwnProperty(key)) { if (root[key] === obj) { return escapePathComponent(key) + '/'; } else if (typeof root[key] === 'object') { found = _getPathRecursive(root[key], obj); if (found != '') { return escapePathComponent(key) + '/' + found; } } } } return ''; } function getPath(root, obj) { if (root === obj) { return '/'; } var path = _getPathRecursive(root, obj); if (path === '') { throw new Error("Object not found in root"); } return '/' + path; } var beforeDict = []; jsonpatch.intervals; var Mirror = (function () { function Mirror(obj) { this.observers = []; this.obj = obj; } return Mirror; })(); var ObserverInfo = (function () { function ObserverInfo(callback, observer) { this.callback = callback; this.observer = observer; } return ObserverInfo; })(); function getMirror(obj) { for (var i = 0, ilen = beforeDict.length; i < ilen; i++) { if (beforeDict[i].obj === obj) { return beforeDict[i]; } } } function getObserverFromMirror(mirror, callback) { for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) { if (mirror.observers[j].callback === callback) { return mirror.observers[j].observer; } } } function removeObserverFromMirror(mirror, observer) { for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) { if (mirror.observers[j].observer === observer) { mirror.observers.splice(j, 1); return; } } } function unobserve(root, observer) { generate(observer); if (Object.observe) { _unobserve(observer, root); } else { clearTimeout(observer.next); } var mirror = getMirror(root); removeObserverFromMirror(mirror, observer); } jsonpatch.unobserve = unobserve; function observe(obj, callback) { var patches = []; var root = obj; var observer; var mirror = getMirror(obj); if (!mirror) { mirror = new Mirror(obj); beforeDict.push(mirror); } else { observer = getObserverFromMirror(mirror, callback); } if (observer) { return observer; } if (Object.observe) { observer = function (arr) { //This "refresh" is needed to begin observing new object properties _unobserve(observer, obj); _observe(observer, obj); var a = 0, alen = arr.length; while (a < alen) { if (!(arr[a].name === 'length' && _isArray(arr[a].object)) && !(arr[a].name === '__Jasmine_been_here_before__')) { var type = arr[a].type; switch (type) { case 'new': type = 'add'; break; case 'deleted': type = 'delete'; break; case 'updated': type = 'update'; break; } observeOps[type].call(arr[a], patches, getPath(root, arr[a].object)); } a++; } if (patches) { if (callback) { callback(patches); } } observer.patches = patches; patches = []; }; } else { observer = {}; mirror.value = JSON.parse(JSON.stringify(obj)); if (callback) { //callbacks.push(callback); this has no purpose observer.callback = callback; observer.next = null; var intervals = this.intervals || [100, 1000, 10000, 60000]; var currentInterval = 0; var dirtyCheck = function () { generate(observer); }; var fastCheck = function () { clearTimeout(observer.next); observer.next = setTimeout(function () { dirtyCheck(); currentInterval = 0; observer.next = setTimeout(slowCheck, intervals[currentInterval++]); }, 0); }; var slowCheck = function () { dirtyCheck(); if (currentInterval == intervals.length) currentInterval = intervals.length - 1; observer.next = setTimeout(slowCheck, intervals[currentInterval++]); }; if (typeof window !== 'undefined') { if (window.addEventListener) { window.addEventListener('mousedown', fastCheck); window.addEventListener('mouseup', fastCheck); window.addEventListener('keydown', fastCheck); } else { window.attachEvent('onmousedown', fastCheck); window.attachEvent('onmouseup', fastCheck); window.attachEvent('onkeydown', fastCheck); } } observer.next = setTimeout(slowCheck, intervals[currentInterval++]); } } observer.patches = patches; observer.object = obj; mirror.observers.push(new ObserverInfo(callback, observer)); return _observe(observer, obj); } jsonpatch.observe = observe; /// Listen to changes on an object tree, accumulate patches function _observe(observer, obj) { if (Object.observe) { Object.observe(obj, observer); for (var key in obj) { if (obj.hasOwnProperty(key)) { var v = obj[key]; if (v && typeof (v) === "object") { _observe(observer, v); } } } } return observer; } function _unobserve(observer, obj) { if (Object.observe) { Object.unobserve(obj, observer); for (var key in obj) { if (obj.hasOwnProperty(key)) { var v = obj[key]; if (v && typeof (v) === "object") { _unobserve(observer, v); } } } } return observer; } function generate(observer) { if (Object.observe) { Object.deliverChangeRecords(observer); } else { var mirror; for (var i = 0, ilen = beforeDict.length; i < ilen; i++) { if (beforeDict[i].obj === observer.object) { mirror = beforeDict[i]; break; } } _generate(mirror.value, observer.object, observer.patches, ""); } var temp = observer.patches; if (temp.length > 0) { observer.patches = []; if (observer.callback) { observer.callback(temp); } } return temp; } jsonpatch.generate = generate; var _objectKeys; if (Object.keys) { _objectKeys = Object.keys; } else { _objectKeys = function (obj) { var keys = []; for (var o in obj) { if (obj.hasOwnProperty(o)) { keys.push(o); } } return keys; }; } // Dirty check if obj is different from mirror, generate patches and update mirror function _generate(mirror, obj, patches, path) { var newKeys = _objectKeys(obj); var oldKeys = _objectKeys(mirror); var changed = false; var deleted = false; for (var t = oldKeys.length - 1; t >= 0; t--) { var key = oldKeys[t]; var oldVal = mirror[key]; if (obj.hasOwnProperty(key)) { var newVal = obj[key]; if (oldVal instanceof Object) { _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key)); } else { if (oldVal != newVal) { changed = true; patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: newVal }); mirror[key] = newVal; } } } else { patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) }); delete mirror[key]; deleted = true; } } if (!deleted && newKeys.length == oldKeys.length) { return; } for (var t = 0; t < newKeys.length; t++) { var key = newKeys[t]; if (!mirror.hasOwnProperty(key)) { patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: obj[key] }); mirror[key] = JSON.parse(JSON.stringify(obj[key])); } } } var _isArray; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (obj) { return obj.push && typeof obj.length === 'number'; }; } /// Apply a json-patch operation on an object tree function apply(tree, patches) { var result = false, p = 0, plen = patches.length, patch; while (p < plen) { patch = patches[p]; // Find the object var keys = patch.path.split('/'); var obj = tree; var t = 1; var len = keys.length; while (true) { if (_isArray(obj)) { var index = parseInt(keys[t], 10); t++; if (t >= len) { result = arrOps[patch.op].call(patch, obj, index, tree); break; } obj = obj[index]; } else { var key = keys[t]; if (key.indexOf('~') != -1) key = key.replace(/~1/g, '/').replace(/~0/g, '~'); t++; if (t >= len) { result = objOps[patch.op].call(patch, obj, key, tree); break; } obj = obj[key]; } } p++; } return result; } jsonpatch.apply = apply; })(jsonpatch || (jsonpatch = {})); if (typeof exports !== "undefined") { exports.apply = jsonpatch.apply; exports.observe = jsonpatch.observe; exports.unobserve = jsonpatch.unobserve; exports.generate = jsonpatch.generate; } Handsontable.PluginHookClass = (function () { var Hooks = function () { return { // Hooks beforeInitWalkontable: [], beforeInit: [], beforeRender: [], beforeChange: [], beforeRemoveCol: [], beforeRemoveRow: [], beforeValidate: [], beforeGet: [], beforeSet: [], beforeGetCellMeta: [], beforeAutofill: [], beforeKeyDown: [], beforeColumnSort: [], afterInit : [], afterLoadData : [], afterUpdateSettings: [], afterRender : [], afterRenderer : [], afterChange : [], afterValidate: [], afterGetCellMeta: [], afterGetColHeader: [], afterGetColWidth: [], afterDestroy: [], afterRemoveRow: [], afterCreateRow: [], afterRemoveCol: [], afterCreateCol: [], afterColumnResize: [], afterColumnMove: [], afterColumnSort: [], afterDeselect: [], afterSelection: [], afterSelectionByProp: [], afterSelectionEnd: [], afterSelectionEndByProp: [], afterCopyLimit: [], afterOnCellMouseDown: [], afterOnCellMouseOver: [], afterOnCellCornerMouseDown: [], afterScrollVertically: [], afterScrollHorizontally: [], // Modifiers modifyCol: [] } }; var legacy = { onBeforeChange: "beforeChange", onChange: "afterChange", onCreateRow: "afterCreateRow", onCreateCol: "afterCreateCol", onSelection: "afterSelection", onCopyLimit: "afterCopyLimit", onSelectionEnd: "afterSelectionEnd", onSelectionByProp: "afterSelectionByProp", onSelectionEndByProp: "afterSelectionEndByProp" }; function PluginHookClass() { this.hooks = Hooks(); this.legacy = legacy; } PluginHookClass.prototype.add = function (key, fn) { //if fn is array, run this for all the array items if (Handsontable.helper.isArray(fn)) { for (var i = 0, len = fn.length; i < len; i++) { this.add(key, fn[i]); } } else { // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } if (typeof this.hooks[key] === "undefined") { this.hooks[key] = []; } if (this.hooks[key].indexOf(fn) == -1) { this.hooks[key].push(fn); //only add a hook if it has not already be added (adding the same hook twice is now silently ignored) } } return this; }; PluginHookClass.prototype.once = function(key, fn){ if(Handsontable.helper.isArray(fn)){ for(var i = 0, len = fn.length; i < len; i++){ fn[i].runOnce = true; this.add(key, fn[i]); } } else { fn.runOnce = true; this.add(key, fn); } }; PluginHookClass.prototype.remove = function (key, fn) { var status = false; // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } if (typeof this.hooks[key] !== 'undefined') { for (var i = 0, leni = this.hooks[key].length; i < leni; i++) { if (this.hooks[key][i] == fn) { delete this.hooks[key][i].runOnce; this.hooks[key].splice(i, 1); status = true; break; } } } return status; }; PluginHookClass.prototype.run = function (instance, key, p1, p2, p3, p4, p5) { // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } //performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture if (typeof this.hooks[key] !== 'undefined') { //Make a copy of handler array var handlers = Array.prototype.slice.call(this.hooks[key]); for (var i = 0, leni = handlers.length; i < leni; i++) { handlers[i].call(instance, p1, p2, p3, p4, p5); if(handlers[i].runOnce){ this.remove(key, handlers[i]); } } } }; PluginHookClass.prototype.execute = function (instance, key, p1, p2, p3, p4, p5) { var res, handlers; // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } //performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture if (typeof this.hooks[key] !== 'undefined') { handlers = Array.prototype.slice.call(this.hooks[key]); for (var i = 0, leni = handlers.length; i < leni; i++) { res = handlers[i].call(instance, p1, p2, p3, p4, p5); if (res !== void 0) { p1 = res; } if(handlers[i].runOnce){ this.remove(key, handlers[i]); } if(res === false){ //if any handler returned false return false; //event has been cancelled and further execution of handler queue is being aborted } } } return p1; }; return PluginHookClass; })(); Handsontable.PluginHooks = new Handsontable.PluginHookClass(); (function (Handsontable) { function HandsontableAutoColumnSize() { var plugin = this , sampleCount = 5; //number of samples to take of each value length this.beforeInit = function () { var instance = this; instance.autoColumnWidths = []; if (instance.getSettings().autoColumnSize !== false) { if (!instance.autoColumnSizeTmp) { instance.autoColumnSizeTmp = { table: null, tableStyle: null, theadTh: null, tbody: null, container: null, containerStyle: null, determineBeforeNextRender: true }; instance.addHook('beforeRender', htAutoColumnSize.determineIfChanged); instance.addHook('afterGetColWidth', htAutoColumnSize.getColWidth); instance.addHook('afterDestroy', htAutoColumnSize.afterDestroy); instance.determineColumnWidth = plugin.determineColumnWidth; } } else { if (instance.autoColumnSizeTmp) { instance.removeHook('beforeRender', htAutoColumnSize.determineIfChanged); instance.removeHook('afterGetColWidth', htAutoColumnSize.getColWidth); instance.removeHook('afterDestroy', htAutoColumnSize.afterDestroy); delete instance.determineColumnWidth; plugin.afterDestroy.call(instance); } } }; this.determineIfChanged = function (force) { if (force) { htAutoColumnSize.determineColumnsWidth.apply(this, arguments); } }; this.determineColumnWidth = function (col) { var instance = this , tmp = instance.autoColumnSizeTmp; if (!tmp.container) { createTmpContainer.call(tmp, instance); } tmp.container.className = instance.rootElement[0].className + ' htAutoColumnSize'; tmp.table.className = instance.$table[0].className; var rows = instance.countRows(); var samples = {}; var maxLen = 0; for (var r = 0; r < rows; r++) { var value = Handsontable.helper.stringify(instance.getDataAtCell(r, col)); var len = value.length; if (len > maxLen) { maxLen = len; } if (!samples[len]) { samples[len] = { needed: sampleCount, strings: [] }; } if (samples[len].needed) { samples[len].strings.push({value: value, row: r}); samples[len].needed--; } } var settings = instance.getSettings(); if (settings.colHeaders) { instance.view.appendColHeader(col, tmp.theadTh); //TH innerHTML } instance.view.wt.wtDom.empty(tmp.tbody); for (var i in samples) { if (samples.hasOwnProperty(i)) { for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) { var row = samples[i].strings[j].row; var cellProperties = instance.getCellMeta(row, col); cellProperties.col = col; cellProperties.row = row; var renderer = instance.getCellRenderer(cellProperties); var tr = document.createElement('tr'); var td = document.createElement('td'); renderer(instance, td, row, col, instance.colToProp(col), samples[i].strings[j].value, cellProperties); r++; tr.appendChild(td); tmp.tbody.appendChild(tr); } } } var parent = instance.rootElement[0].parentNode; parent.appendChild(tmp.container); var width = instance.view.wt.wtDom.outerWidth(tmp.table); parent.removeChild(tmp.container); if (!settings.nativeScrollbars) { //with native scrollbars a cell size can safely exceed the width of the viewport var maxWidth = instance.view.wt.wtViewport.getViewportWidth() - 2; //2 is some overhead for cell border if (width > maxWidth) { width = maxWidth; } } 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.getColWidth = function (col, response) { if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > response.width) { response.width = this.autoColumnWidths[col]; } }; this.afterDestroy = function () { var instance = this; if (instance.autoColumnSizeTmp && instance.autoColumnSizeTmp.container && instance.autoColumnSizeTmp.container.parentNode) { instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container); } instance.autoColumnSizeTmp = null; }; function createTmpContainer(instance) { var d = document , tmp = this; tmp.table = d.createElement('table'); tmp.theadTh = d.createElement('th'); tmp.table.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(tmp.theadTh); tmp.tableStyle = tmp.table.style; tmp.tableStyle.tableLayout = 'auto'; tmp.tableStyle.width = 'auto'; tmp.tbody = d.createElement('tbody'); tmp.table.appendChild(tmp.tbody); tmp.container = d.createElement('div'); tmp.container.className = instance.rootElement[0].className + ' hidden'; tmp.containerStyle = tmp.container.style; tmp.container.appendChild(tmp.table); } } var htAutoColumnSize = new HandsontableAutoColumnSize(); Handsontable.PluginHooks.add('beforeInit', htAutoColumnSize.beforeInit); Handsontable.PluginHooks.add('afterUpdateSettings', htAutoColumnSize.beforeInit); })(Handsontable); /** * This plugin sorts the view by a column (but does not sort the data source!) * @constructor */ function HandsontableColumnSorting() { var plugin = this; this.init = function (source) { var instance = this; var sortingSettings = instance.getSettings().columnSorting; var sortingColumn, sortingOrder; instance.sortingEnabled = !!(sortingSettings); if (instance.sortingEnabled) { instance.sortIndex = []; var loadedSortingState = loadSortingState.call(instance); if (typeof loadedSortingState != 'undefined') { sortingColumn = loadedSortingState.sortColumn; sortingOrder = loadedSortingState.sortOrder; } else { sortingColumn = sortingSettings.column; sortingOrder = sortingSettings.sortOrder; } plugin.sortByColumn.call(instance, sortingColumn, sortingOrder); instance.sort = function(){ var args = Array.prototype.slice.call(arguments); return plugin.sortByColumn.apply(instance, args) }; if (typeof instance.getSettings().observeChanges == 'undefined'){ enableObserveChangesPlugin.call(instance); } if (source == 'afterInit') { bindColumnSortingAfterClick.call(instance); instance.addHook('afterCreateRow', plugin.afterCreateRow); instance.addHook('afterRemoveRow', plugin.afterRemoveRow); instance.addHook('afterLoadData', plugin.init); } } else { delete instance.sort; instance.removeHook('afterCreateRow', plugin.afterCreateRow); instance.removeHook('afterRemoveRow', plugin.afterRemoveRow); instance.removeHook('afterLoadData', plugin.init); } }; this.setSortingColumn = function (col, order) { var instance = this; if (typeof col == 'undefined') { delete instance.sortColumn; delete instance.sortOrder; return; } else if (instance.sortColumn === col && typeof order == 'undefined') { instance.sortOrder = !instance.sortOrder; } else { instance.sortOrder = typeof order != 'undefined' ? order : true; } instance.sortColumn = col; }; this.sortByColumn = function (col, order) { var instance = this; plugin.setSortingColumn.call(instance, col, order); if(typeof instance.sortColumn == 'undefined'){ return; } instance.PluginHooks.run('beforeColumnSort', instance.sortColumn, instance.sortOrder); plugin.sort.call(instance); instance.render(); saveSortingState.call(instance); instance.PluginHooks.run('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')) { instance.PluginHooks.run('persistentStateSave', 'columnSorting', sortingState); } }; var loadSortingState = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'columnSorting', storedState); return storedState.value; }; var bindColumnSortingAfterClick = function () { var instance = this; instance.rootElement.on('click.handsontable', '.columnSorting', function (e) { if (instance.view.wt.wtDom.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 = instance.view.wt.wtDom.closest(target, 'TH'); return instance.view.wt.wtDom.index(TH) - countRowHeaders(); } }; function enableObserveChangesPlugin () { var instance = this; instance.registerTimeout('enableObserveChanges', function(){ instance.updateSettings({ observeChanges: true }); }, 0); } function defaultSort(sortOrder) { return function (a, b) { if (a[1] === b[1]) { return 0; } if (a[1] === null) { return 1; } if (b[1] === null) { return -1; } if (a[1] < b[1]) return sortOrder ? -1 : 1; if (a[1] > b[1]) return sortOrder ? 1 : -1; return 0; } } function dateSort(sortOrder) { return function (a, b) { if (a[1] === b[1]) { return 0; } if (a[1] === null) { return 1; } if (b[1] === null) { return -1; } var aDate = new Date(a[1]); var bDate = new Date(b[1]); if (aDate < bDate) return sortOrder ? -1 : 1; if (aDate > bDate) return sortOrder ? 1 : -1; return 0; } } this.sort = function () { var instance = this; if (typeof instance.sortOrder == 'undefined') { return; } instance.sortingEnabled = false; //this is required by translateRow plugin hook instance.sortIndex.length = 0; var colOffset = this.colOffset(); for (var i = 0, ilen = this.countRows() - instance.getSettings()['minSpareRows']; i < ilen; i++) { this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]); } var colMeta = instance.getCellMeta(0, instance.sortColumn); var sortFunction; switch (colMeta.type) { case 'date': sortFunction = dateSort; break; default: sortFunction = defaultSort; } this.sortIndex.sort(sortFunction(instance.sortOrder)); //Append spareRows for(var i = this.sortIndex.length; i < instance.countRows(); i++){ this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]); } instance.sortingEnabled = true; //this is required by translateRow plugin hook }; this.translateRow = function (row) { var instance = this; if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length && instance.sortIndex[row]) { return instance.sortIndex[row][0]; } return row; }; this.onBeforeGetSet = function (getVars) { var instance = this; getVars.row = plugin.translateRow.call(instance, getVars.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) { this.view.wt.wtDom.addClass(TH.querySelector('.colHeader'), 'columnSorting'); } }; function isSorted(instance){ return typeof instance.sortColumn != 'undefined'; } this.afterCreateRow = function(index, amount){ var instance = this; if(!isSorted(instance)){ return; } for(var i = 0; i < instance.sortIndex.length; i++){ if (instance.sortIndex[i][0] >= index){ instance.sortIndex[i][0] += amount; } } for(var i=0; i < amount; i++){ instance.sortIndex.splice(index+i, 0, [index+i, instance.getData()[index+i][instance.sortColumn + instance.colOffset()]]); } saveSortingState.call(instance); }; this.afterRemoveRow = function(index, amount){ var instance = this; if(!isSorted(instance)){ return; } var physicalRemovedIndex = plugin.translateRow.call(instance, index); instance.sortIndex.splice(index, amount); for(var i = 0; i < instance.sortIndex.length; i++){ if (instance.sortIndex[i][0] > physicalRemovedIndex){ instance.sortIndex[i][0] -= amount; } } saveSortingState.call(instance); }; this.afterChangeSort = function (changes/*, source*/) { var instance = this; var sortColumnChanged = false; var selection = {}; if (!changes) { return; } for (var i = 0; i < changes.length; i++) { if (changes[i][1] == instance.sortColumn) { sortColumnChanged = true; selection.row = plugin.translateRow.call(instance, changes[i][0]); selection.col = changes[i][1]; break; } } if (sortColumnChanged) { setTimeout(function () { plugin.sort.call(instance); instance.render(); instance.selectCell(plugin.untranslateRow.call(instance, selection.row), selection.col); }, 0); } }; } var htSortColumn = new HandsontableColumnSorting(); Handsontable.PluginHooks.add('afterInit', function () { htSortColumn.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htSortColumn.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('beforeGet', htSortColumn.onBeforeGetSet); Handsontable.PluginHooks.add('beforeSet', htSortColumn.onBeforeGetSet); Handsontable.PluginHooks.add('afterGetColHeader', htSortColumn.getColHeader); (function (Handsontable) { 'use strict'; function ContextMenu(instance, customOptions){ this.instance = instance; var contextMenu = this; this.menu = createMenu(); this.enabled = true; this.bindMouseEvents(); this.bindTableEvents(); this.instance.addHook('afterDestroy', function () { contextMenu.destroy(); }); this.defaultOptions = { items: { 'row_above': { name: 'Insert row above', callback: function(key, selection){ this.alter("insert_row", selection.start.row()); }, disabled: function () { return this.countRows() >= this.getSettings().maxRows; } }, 'row_below': { name: 'Insert row below', callback: function(key, selection){ this.alter("insert_row", selection.end.row() + 1); }, disabled: function () { return this.countRows() >= this.getSettings().maxRows; } }, "hsep1": ContextMenu.SEPARATOR, 'col_left': { name: 'Insert column on the left', callback: function(key, selection){ this.alter("insert_col", selection.start.col()); }, disabled: function () { return this.countCols() >= this.getSettings().maxCols; } }, 'col_right': { name: 'Insert column on the right', callback: function(key, selection){ this.alter("insert_col", selection.end.col() + 1); }, disabled: function () { return this.countCols() >= this.getSettings().maxCols; } }, "hsep2": ContextMenu.SEPARATOR, 'remove_row': { name: 'Remove row', callback: function(key, selection){ var amount = selection.end.row() - selection.start.row() + 1; this.alter("remove_row", selection.start.row(), amount); } }, '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); } }, "hsep3": ContextMenu.SEPARATOR, 'undo': { name: 'Undo', callback: function(){ this.undo(); }, disabled: function () { return this.undoRedo && !this.undoRedo.isUndoAvailable(); } }, 'redo': { name: 'Redo', callback: function(){ this.redo(); }, disabled: function () { return this.undoRedo && !this.undoRedo.isRedoAvailable(); } } } }; this.options = {}; Handsontable.helper.extend(this.options, this.defaultOptions); this.updateOptions(customOptions); function createMenu(){ var menu = $('body > .htContextMenu')[0]; if(!menu){ menu = document.createElement('DIV'); Handsontable.Dom.addClass(menu, 'htContextMenu'); document.getElementsByTagName('body')[0].appendChild(menu); } return menu; } } ContextMenu.prototype.bindMouseEvents = function (){ function contextMenuOpenListener(event){ event.preventDefault(); if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){ return; } this.show(event.pageY, event.pageX); $(document).on('mousedown.htContextMenu', Handsontable.helper.proxy(ContextMenu.prototype.close, this)); } this.instance.rootElement.on('contextmenu.htContextMenu', Handsontable.helper.proxy(contextMenuOpenListener, this)); }; ContextMenu.prototype.bindTableEvents = function () { var that = this; this._afterScrollCallback = function () { that.close(); }; this.instance.addHook('afterScrollVertically', this._afterScrollCallback); this.instance.addHook('afterScrollHorizontally', this._afterScrollCallback); }; ContextMenu.prototype.unbindTableEvents = function () { var that = this; if(this._afterScrollCallback){ this.instance.removeHook('afterScrollVertically', this._afterScrollCallback); this.instance.removeHook('afterScrollHorizontally', this._afterScrollCallback); this._afterScrollCallback = null; } }; ContextMenu.prototype.performAction = function (){ var hot = $(this.menu).handsontable('getInstance'); var selectedItemIndex = hot.getSelected()[0]; var selectedItem = hot.getData()[selectedItemIndex]; if (selectedItem.disabled === true || (typeof selectedItem.disabled == 'function' && selectedItem.disabled.call(this.instance) === true)){ return; } if(typeof selectedItem.callback != 'function'){ return; } var corners = this.instance.getSelected(); var normalizedSelection = ContextMenu.utils.normalizeSelection(corners); selectedItem.callback.call(this.instance, selectedItem.key, normalizedSelection); }; ContextMenu.prototype.unbindMouseEvents = function () { this.instance.rootElement.off('contextmenu.htContextMenu'); $(document).off('mousedown.htContextMenu'); }; ContextMenu.prototype.show = function(top, left){ this.menu.style.display = 'block'; $(this.menu) .off('mousedown.htContextMenu') .on('mousedown.htContextMenu', Handsontable.helper.proxy(this.performAction, this)); $(this.menu).handsontable({ data: ContextMenu.utils.convertItemsToArray(this.getItems()), colHeaders: false, colWidths: [160], readOnly: true, copyPaste: false, columns: [ { data: 'name', renderer: Handsontable.helper.proxy(this.renderer, this) } ], beforeKeyDown: Handsontable.helper.proxy(this.onBeforeKeyDown, this) }); this.bindTableEvents(); this.setMenuPosition(top, left); $(this.menu).handsontable('listen'); }; ContextMenu.prototype.close = function () { this.hide(); $(document).off('mousedown.htContextMenu'); this.unbindTableEvents(); this.instance.listen(); }; ContextMenu.prototype.hide = function(){ this.menu.style.display = 'none'; $(this.menu).handsontable('destroy'); }; ContextMenu.prototype.renderer = function(instance, TD, row, col, prop, value, cellProperties){ var contextMenu = this; var item = instance.getData()[row]; var wrapper = document.createElement('DIV'); Handsontable.Dom.empty(TD); TD.appendChild(wrapper); if(itemIsSeparator(item)){ Handsontable.Dom.addClass(TD, 'htSeparator'); } else { Handsontable.Dom.fastInnerText(wrapper, value); } if (itemIsDisabled(item, contextMenu.instance)){ Handsontable.Dom.addClass(TD, 'htDisabled'); $(wrapper).on('mouseenter', function () { instance.deselectCell(); }); } else { Handsontable.Dom.removeClass(TD, 'htDisabled'); $(wrapper).on('mouseenter', function () { instance.selectCell(row, col); }); } function itemIsSeparator(item){ return new RegExp(ContextMenu.SEPARATOR, 'i').test(item.name); } function itemIsDisabled(item, instance){ return item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(contextMenu.instance) === true); } }; ContextMenu.prototype.onBeforeKeyDown = function (event) { var contextMenu = this; var instance = $(contextMenu.menu).handsontable('getInstance'); var selection = instance.getSelected(); switch(event.keyCode){ case Handsontable.helper.keyCode.ESCAPE: contextMenu.close(); event.preventDefault(); event.stopImmediatePropagation(); break; case Handsontable.helper.keyCode.ENTER: if(instance.getSelected()){ contextMenu.performAction(); contextMenu.close(); } break; case Handsontable.helper.keyCode.ARROW_DOWN: if(!selection){ selectFirstCell(instance); } else { selectNextCell(selection[0], selection[1], instance); } event.preventDefault(); event.stopImmediatePropagation(); break; case Handsontable.helper.keyCode.ARROW_UP: if(!selection){ selectLastCell(instance); } else { selectPrevCell(selection[0], selection[1], instance); } event.preventDefault(); event.stopImmediatePropagation(); break; } function selectFirstCell(instance) { var firstCell = instance.getCell(0, 0); if(ContextMenu.utils.isSeparator(firstCell) || ContextMenu.utils.isDisabled(firstCell)){ selectNextCell(0, 0, instance); } else { instance.selectCell(0, 0); } } function selectLastCell(instance) { var lastRow = instance.countRows() - 1; var lastCell = instance.getCell(lastRow, 0); if(ContextMenu.utils.isSeparator(lastCell) || ContextMenu.utils.isDisabled(lastCell)){ selectPrevCell(lastRow, 0, instance); } else { instance.selectCell(lastRow, 0); } } function selectNextCell(row, col, instance){ var nextRow = row + 1; var nextCell = nextRow < instance.countRows() ? instance.getCell(nextRow, col) : null; if(!nextCell){ return; } if(ContextMenu.utils.isSeparator(nextCell) || ContextMenu.utils.isDisabled(nextCell)){ selectNextCell(nextRow, col, instance); } else { instance.selectCell(nextRow, col); } } function selectPrevCell(row, col, instance) { var prevRow = row - 1; var prevCell = prevRow >= 0 ? instance.getCell(prevRow, col) : null; if (!prevCell) { return; } if(ContextMenu.utils.isSeparator(prevCell) || ContextMenu.utils.isDisabled(prevCell)){ selectPrevCell(prevRow, col, instance); } else { instance.selectCell(prevRow, col); } } }; ContextMenu.prototype.getItems = function () { var items = {}; function Item(rawItem){ if(typeof rawItem == 'string'){ this.name = rawItem; } else { Handsontable.helper.extend(this, rawItem); } } Item.prototype = this.options; for(var itemName in this.options.items){ if(this.options.items.hasOwnProperty(itemName) && (!this.itemsFilter || this.itemsFilter.indexOf(itemName) != -1)){ items[itemName] = new Item(this.options.items[itemName]); } } return items; }; ContextMenu.prototype.updateOptions = function(newOptions){ newOptions = newOptions || {}; if(newOptions.items){ for(var itemName in newOptions.items){ var item = {}; if(newOptions.items.hasOwnProperty(itemName)) { if(this.defaultOptions.items.hasOwnProperty(itemName) && Handsontable.helper.isObject(newOptions.items[itemName])){ Handsontable.helper.extend(item, this.defaultOptions.items[itemName]); Handsontable.helper.extend(item, newOptions.items[itemName]); newOptions.items[itemName] = item; } } } } Handsontable.helper.extend(this.options, newOptions); }; ContextMenu.prototype.setMenuPosition = function (cursorY, cursorX) { var cursor = { top: cursorY, topRelative: cursorY - document.documentElement.scrollTop, left: cursorX, leftRelative:cursorX - document.documentElement.scrollLeft }; if(this.menuFitsBelowCursor(cursor)){ this.positionMenuBelowCursor(cursor); } else { this.positionMenuAboveCursor(cursor); } if(this.menuFitsOnRightOfCursor(cursor)){ this.positionMenuOnRightOfCursor(cursor); } else { this.positionMenuOnLeftOfCursor(cursor); } }; ContextMenu.prototype.menuFitsBelowCursor = function (cursor) { return cursor.topRelative + this.menu.offsetHeight <= document.documentElement.scrollTop + document.documentElement.clientHeight; }; ContextMenu.prototype.menuFitsOnRightOfCursor = function (cursor) { return cursor.leftRelative + this.menu.offsetWidth <= document.documentElement.scrollLeft + document.documentElement.clientWidth; }; ContextMenu.prototype.positionMenuBelowCursor = function (cursor) { this.menu.style.top = cursor.top + 'px'; }; ContextMenu.prototype.positionMenuAboveCursor = function (cursor) { this.menu.style.top = (cursor.top - this.menu.offsetHeight) + 'px'; }; ContextMenu.prototype.positionMenuOnRightOfCursor = function (cursor) { this.menu.style.left = cursor.left + 'px'; }; ContextMenu.prototype.positionMenuOnLeftOfCursor = function (cursor) { this.menu.style.left = (cursor.left - this.menu.offsetWidth) + 'px'; }; ContextMenu.utils = {}; ContextMenu.utils.convertItemsToArray = function (items) { var itemArray = []; var item; for(var itemName in items){ if(items.hasOwnProperty(itemName)){ if(typeof items[itemName] == 'string'){ item = {name: items[itemName]}; } else if (items[itemName].visible !== false) { item = items[itemName]; } else { continue; } item.key = itemName; itemArray.push(item); } } return itemArray; }; ContextMenu.utils.normalizeSelection = function(corners){ var selection = { start: new Handsontable.SelectionPoint(), end: new Handsontable.SelectionPoint() }; selection.start.row(Math.min(corners[0], corners[2])); selection.start.col(Math.min(corners[1], corners[3])); selection.end.row(Math.max(corners[0], corners[2])); selection.end.col(Math.max(corners[1], corners[3])); return selection; }; ContextMenu.utils.isSeparator = function (cell) { return Handsontable.Dom.hasClass(cell, 'htSeparator'); }; ContextMenu.utils.isDisabled = function (cell) { return Handsontable.Dom.hasClass(cell, 'htDisabled'); }; ContextMenu.prototype.enable = function () { if(!this.enabled){ this.enabled = true; this.bindMouseEvents(); } }; ContextMenu.prototype.disable = function () { if(this.enabled){ this.enabled = false; this.close(); this.unbindMouseEvents(); this.unbindTableEvents(); } }; ContextMenu.prototype.destroy = function () { this.close(); this.unbindMouseEvents(); this.unbindTableEvents(); if(!this.isMenuEnabledByOtherHotInstance()){ this.removeMenu(); } }; ContextMenu.prototype.isMenuEnabledByOtherHotInstance = function () { var hotContainers = $('.handsontable'); var menuEnabled = false; for(var i = 0, len = hotContainers.length; i < len; i++){ var instance = $(hotContainers[i]).handsontable('getInstance'); if(instance && instance.getSettings().contextMenu){ menuEnabled = true; break; } } return menuEnabled; }; ContextMenu.prototype.removeMenu = function () { if(this.menu.parentNode){ this.menu.parentNode.removeChild(this.menu); } } ContextMenu.prototype.filterItems = function(itemsToLeave){ this.itemsFilter = itemsToLeave; }; ContextMenu.SEPARATOR = "---------"; function init(){ var instance = this; var contextMenuSetting = instance.getSettings().contextMenu; var customOptions = Handsontable.helper.isObject(contextMenuSetting) ? contextMenuSetting : {}; if(contextMenuSetting){ if(!instance.contextMenu){ instance.contextMenu = new ContextMenu(instance, customOptions); } instance.contextMenu.enable(); if(Handsontable.helper.isArray(contextMenuSetting)){ instance.contextMenu.filterItems(contextMenuSetting); } } else if(instance.contextMenu){ instance.contextMenu.destroy(); delete instance.contextMenu; } } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); Handsontable.ContextMenu = ContextMenu; })(Handsontable); /** * This plugin adds support for legacy features, deprecated APIs, etc. */ /** * Support for old autocomplete syntax * For old syntax, see: https://github.com/warpech/jquery-handsontable/blob/8c9e701d090ea4620fe08b6a1a048672fadf6c7e/README.md#defining-autocomplete */ Handsontable.PluginHooks.add('beforeGetCellMeta', function (row, col, cellProperties) { //isWritable - deprecated since 0.8.0 cellProperties.isWritable = !cellProperties.readOnly; //autocomplete - deprecated since 0.7.1 (see CHANGELOG.md) if (cellProperties.autoComplete) { throw new Error("Support for legacy autocomplete syntax was removed in Handsontable 0.10.0. Please remove the property named 'autoComplete' from your config. For replacement instructions, see wiki page https://github.com/warpech/jquery-handsontable/wiki/Migration-guide-to-0.10.x"); } }); function HandsontableManualColumnMove() { var pressed , startCol , endCol , startX , startOffset; var ghost = document.createElement('DIV') , ghostStyle = ghost.style; ghost.className = 'ghost'; ghostStyle.position = 'absolute'; ghostStyle.top = '25px'; ghostStyle.left = 0; ghostStyle.width = '10px'; ghostStyle.height = '10px'; ghostStyle.backgroundColor = '#CCC'; ghostStyle.opacity = 0.7; var saveManualColumnPositions = function () { var instance = this; instance.PluginHooks.run('persistentStateSave', 'manualColumnPositions', instance.manualColumnPositions); }; var loadManualColumnPositions = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'manualColumnPositions', storedState); return storedState.value; }; var bindMoveColEvents = function () { var instance = this; instance.rootElement.on('mousemove.manualColumnMove', function (e) { if (pressed) { ghostStyle.left = startOffset + e.pageX - startX + 6 + 'px'; if (ghostStyle.display === 'none') { ghostStyle.display = 'block'; } } }); instance.rootElement.on('mouseup.manualColumnMove', function () { if (pressed) { if (startCol < endCol) { endCol--; } if (instance.getSettings().rowHeaders) { startCol--; endCol--; } instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]); $('.manualColumnMover.active').removeClass('active'); pressed = false; instance.forceFullRender = true; instance.view.render(); //updates all ghostStyle.display = 'none'; saveManualColumnPositions.call(instance); instance.PluginHooks.run('afterColumnMove', startCol, endCol); } }); instance.rootElement.on('mousedown.manualColumnMove', '.manualColumnMover', function (e) { var mover = e.currentTarget; var TH = instance.view.wt.wtDom.closest(mover, 'TH'); startCol = instance.view.wt.wtDom.index(TH) + instance.colOffset(); endCol = startCol; pressed = true; startX = e.pageX; var TABLE = instance.$table[0]; TABLE.parentNode.appendChild(ghost); ghostStyle.width = instance.view.wt.wtDom.outerWidth(TH) + 'px'; ghostStyle.height = instance.view.wt.wtDom.outerHeight(TABLE) + 'px'; startOffset = parseInt(instance.view.wt.wtDom.offset(TH).left - instance.view.wt.wtDom.offset(TABLE).left, 10); ghostStyle.left = startOffset + 6 + 'px'; }); instance.rootElement.on('mouseenter.manualColumnMove', 'td, th', function () { if (pressed) { var active = instance.view.THEAD.querySelector('.manualColumnMover.active'); if (active) { instance.view.wt.wtDom.removeClass(active, 'active'); } endCol = instance.view.wt.wtDom.index(this) + instance.colOffset(); var THs = instance.view.THEAD.querySelectorAll('th'); var mover = THs[endCol].querySelector('.manualColumnMover'); instance.view.wt.wtDom.addClass(mover, 'active'); } }); instance.addHook('afterDestroy', unbindMoveColEvents); }; var unbindMoveColEvents = function(){ var instance = this; instance.rootElement.off('mouseup.manualColumnMove'); instance.rootElement.off('mousemove.manualColumnMove'); instance.rootElement.off('mousedown.manualColumnMove'); instance.rootElement.off('mouseenter.manualColumnMove'); }; this.beforeInit = function () { this.manualColumnPositions = []; }; this.init = function (source) { var instance = this; var manualColMoveEnabled = !!(this.getSettings().manualColumnMove); if (manualColMoveEnabled) { var initialManualColumnPositions = this.getSettings().manualColumnMove; var loadedManualColumnPositions = loadManualColumnPositions.call(instance); if (typeof loadedManualColumnPositions != 'undefined') { this.manualColumnPositions = loadedManualColumnPositions; } else if (initialManualColumnPositions instanceof Array) { this.manualColumnPositions = initialManualColumnPositions; } else { this.manualColumnPositions = []; } instance.forceFullRender = true; if (source == 'afterInit') { bindMoveColEvents.call(this); if (this.manualColumnPositions.length > 0) { this.forceFullRender = true; this.render(); } } } else { unbindMoveColEvents.call(this); this.manualColumnPositions = []; } }; this.modifyCol = function (col) { //TODO test performance: http://jsperf.com/object-wrapper-vs-primitive/2 if (this.getSettings().manualColumnMove) { if (typeof this.manualColumnPositions[col] === 'undefined') { this.manualColumnPositions[col] = col; } return this.manualColumnPositions[col]; } return col; }; this.getColHeader = function (col, TH) { if (this.getSettings().manualColumnMove) { var DIV = document.createElement('DIV'); DIV.className = 'manualColumnMover'; TH.firstChild.appendChild(DIV); } }; } var htManualColumnMove = new HandsontableManualColumnMove(); Handsontable.PluginHooks.add('beforeInit', htManualColumnMove.beforeInit); Handsontable.PluginHooks.add('afterInit', function () { htManualColumnMove.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htManualColumnMove.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('afterGetColHeader', htManualColumnMove.getColHeader); Handsontable.PluginHooks.add('modifyCol', htManualColumnMove.modifyCol); function HandsontableManualColumnResize() { var pressed , currentTH , currentCol , currentWidth , instance , newSize , startX , startWidth , startOffset , resizer = document.createElement('DIV') , handle = document.createElement('DIV') , line = document.createElement('DIV') , lineStyle = line.style; resizer.className = 'manualColumnResizer'; handle.className = 'manualColumnResizerHandle'; resizer.appendChild(handle); line.className = 'manualColumnResizerLine'; resizer.appendChild(line); var $document = $(document); $document.mousemove(function (e) { if (pressed) { currentWidth = startWidth + (e.pageX - startX); newSize = setManualSize(currentCol, currentWidth); //save col width resizer.style.left = startOffset + currentWidth + 'px'; } }); $document.mouseup(function () { if (pressed) { instance.view.wt.wtDom.removeClass(resizer, 'active'); pressed = false; if(newSize != startWidth){ instance.forceFullRender = true; instance.view.render(); //updates all saveManualColumnWidths.call(instance); instance.PluginHooks.run('afterColumnResize', currentCol, newSize); } refreshResizerPosition.call(instance, currentTH); } }); var saveManualColumnWidths = function () { var instance = this; instance.PluginHooks.run('persistentStateSave', 'manualColumnWidths', instance.manualColumnWidths); }; var loadManualColumnWidths = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'manualColumnWidths', storedState); return storedState.value; }; function refreshResizerPosition(TH) { instance = this; currentTH = TH; var col = this.view.wt.wtTable.getCoords(TH)[1]; //getCoords returns array [row, col] if (col >= 0) { //if not row header currentCol = col; var rootOffset = this.view.wt.wtDom.offset(this.rootElement[0]).left; var thOffset = this.view.wt.wtDom.offset(TH).left; startOffset = (thOffset - rootOffset) - 6; resizer.style.left = startOffset + parseInt(this.view.wt.wtDom.outerWidth(TH), 10) + 'px'; this.rootElement[0].appendChild(resizer); } } function refreshLinePosition() { var instance = this; startWidth = parseInt(this.view.wt.wtDom.outerWidth(currentTH), 10); instance.view.wt.wtDom.addClass(resizer, 'active'); lineStyle.height = instance.view.wt.wtDom.outerHeight(instance.$table[0]) + 'px'; pressed = instance; } var bindManualColumnWidthEvents = function () { var instance = this; var dblclick = 0; var autoresizeTimeout = null; this.rootElement.on('mouseenter.handsontable', 'th', function (e) { if (!pressed) { refreshResizerPosition.call(instance, e.currentTarget); } }); this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function () { if (autoresizeTimeout == null) { autoresizeTimeout = setTimeout(function () { if (dblclick >= 2) { newSize = instance.determineColumnWidth.call(instance, currentCol); setManualSize(currentCol, newSize); instance.forceFullRender = true; instance.view.render(); //updates all instance.PluginHooks.run('afterColumnResize', currentCol, newSize); } dblclick = 0; autoresizeTimeout = null; }, 500); } dblclick++; }); this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) { startX = e.pageX; refreshLinePosition.call(instance); newSize = startWidth; }); }; this.beforeInit = function () { this.manualColumnWidths = []; }; this.init = function (source) { var instance = this; var manualColumnWidthEnabled = !!(this.getSettings().manualColumnResize); if (manualColumnWidthEnabled) { var initialColumnWidths = this.getSettings().manualColumnResize; var loadedManualColumnWidths = loadManualColumnWidths.call(instance); if (typeof loadedManualColumnWidths != 'undefined') { this.manualColumnWidths = loadedManualColumnWidths; } else if (initialColumnWidths instanceof Array) { this.manualColumnWidths = initialColumnWidths; } else { this.manualColumnWidths = []; } if (source == 'afterInit') { bindManualColumnWidthEvents.call(this); instance.forceFullRender = true; instance.render(); } } }; var setManualSize = function (col, width) { width = Math.max(width, 20); /** * We need to run col through modifyCol hook, in case the order of displayed columns is different than the order * in data source. For instance, this order can be modified by manualColumnMove plugin. */ col = instance.PluginHooks.execute('modifyCol', col); instance.manualColumnWidths[col] = width; return width; }; this.getColWidth = function (col, response) { if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) { response.width = this.manualColumnWidths[col]; } }; } var htManualColumnResize = new HandsontableManualColumnResize(); Handsontable.PluginHooks.add('beforeInit', htManualColumnResize.beforeInit); Handsontable.PluginHooks.add('afterInit', function () { htManualColumnResize.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htManualColumnResize.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('afterGetColWidth', htManualColumnResize.getColWidth); (function HandsontableObserveChanges() { Handsontable.PluginHooks.add('afterLoadData', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); function init() { var instance = this; var pluginEnabled = instance.getSettings().observeChanges; if (pluginEnabled) { if(instance.observer) { destroy.call(instance); //destroy observer for old data object } createObserver.call(instance); bindEvents.call(instance); } else if (!pluginEnabled){ destroy.call(instance); } } function createObserver(){ var instance = this; instance.observeChangesActive = true; instance.pauseObservingChanges = function(){ instance.observeChangesActive = false; }; instance.resumeObservingChanges = function(){ instance.observeChangesActive = true; }; instance.observedData = instance.getData(); instance.observer = jsonpatch.observe(instance.observedData, function (patches) { if(instance.observeChangesActive){ runHookForOperation.call(instance, patches); instance.render(); } instance.runHooks('afterChangesObserved'); }); } function runHookForOperation(rawPatches){ var instance = this; var patches = cleanPatches(rawPatches); for(var i = 0, len = patches.length; i < len; i++){ var patch = patches[i]; var parsedPath = parsePath(patch.path); switch(patch.op){ case 'add': if(isNaN(parsedPath.col)){ instance.runHooks('afterCreateRow', parsedPath.row); } else { instance.runHooks('afterCreateCol', parsedPath.col); } break; case 'remove': if(isNaN(parsedPath.col)){ instance.runHooks('afterRemoveRow', parsedPath.row, 1); } else { instance.runHooks('afterRemoveCol', parsedPath.col, 1); } break; case 'replace': instance.runHooks('afterChange', [parsedPath.row, parsedPath.col, null, patch.value], 'external'); break; } } function cleanPatches(rawPatches){ var patches; patches = removeLengthRelatedPatches(rawPatches); patches = removeMultipleAddOrRemoveColPatches(patches); return patches; } /** * Removing or adding column will produce one patch for each table row. * This function leaves only one patch for each column add/remove operation */ function removeMultipleAddOrRemoveColPatches(rawPatches){ var newOrRemovedColumns = []; return rawPatches.filter(function(patch){ var parsedPath = parsePath(patch.path); if(['add', 'remove'].indexOf(patch.op) != -1 && !isNaN(parsedPath.col)){ if(newOrRemovedColumns.indexOf(parsedPath.col) != -1){ return false; } else { newOrRemovedColumns.push(parsedPath.col); } } return true; }); } /** * If observeChanges uses native Object.observe method, then it produces patches for length property. * This function removes them. */ function removeLengthRelatedPatches(rawPatches){ return rawPatches.filter(function(patch){ return !/[/]length/ig.test(patch.path); }) } function parsePath(path){ var match = path.match(/^\/(\d+)\/?(.*)?$/); return { row: parseInt(match[1], 10), col: /^\d*$/.test(match[2]) ? parseInt(match[2], 10) : match[2] } } } function destroy(){ var instance = this; if (instance.observer){ destroyObserver.call(instance); unbindEvents.call(instance); } } function destroyObserver(){ var instance = this; jsonpatch.unobserve(instance.observedData, instance.observer); delete instance.observeChangesActive; delete instance.pauseObservingChanges; delete instance.resumeObservingChanges; } function bindEvents(){ var instance = this; instance.addHook('afterDestroy', destroy); instance.addHook('afterCreateRow', afterTableAlter); instance.addHook('afterRemoveRow', afterTableAlter); instance.addHook('afterCreateCol', afterTableAlter); instance.addHook('afterRemoveCol', afterTableAlter); instance.addHook('afterChange', function(changes, source){ if(source != 'loadData'){ afterTableAlter.call(this); } }); } function unbindEvents(){ var instance = this; instance.removeHook('afterDestroy', destroy); instance.removeHook('afterCreateRow', afterTableAlter); instance.removeHook('afterRemoveRow', afterTableAlter); instance.removeHook('afterCreateCol', afterTableAlter); instance.removeHook('afterRemoveCol', afterTableAlter); instance.removeHook('afterChange', afterTableAlter); } function afterTableAlter(){ var instance = this; instance.pauseObservingChanges(); instance.addHookOnce('afterChangesObserved', function(){ instance.resumeObservingChanges(); }); } })(); /* * * Plugin enables saving table state * * */ function Storage(prefix) { var savedKeys; var saveSavedKeys = function () { window.localStorage[prefix + '__' + 'persistentStateKeys'] = JSON.stringify(savedKeys); }; var loadSavedKeys = function () { var keysJSON = window.localStorage[prefix + '__' + 'persistentStateKeys']; var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0; savedKeys = keys ? keys : []; }; var clearSavedKeys = function () { savedKeys = []; saveSavedKeys(); }; loadSavedKeys(); this.saveValue = function (key, value) { window.localStorage[prefix + '_' + key] = JSON.stringify(value); if (savedKeys.indexOf(key) == -1) { savedKeys.push(key); saveSavedKeys(); } }; this.loadValue = function (key, defaultValue) { key = typeof key != 'undefined' ? key : defaultValue; var value = window.localStorage[prefix + '_' + key]; return typeof value == "undefined" ? void 0 : JSON.parse(value); }; this.reset = function (key) { window.localStorage.removeItem(prefix + '_' + key); }; this.resetAll = function () { for (var index = 0; index < savedKeys.length; index++) { window.localStorage.removeItem(prefix + '_' + savedKeys[index]); } clearSavedKeys(); }; } (function (StorageClass) { function HandsontablePersistentState() { var plugin = this; this.init = function () { var instance = this, pluginSettings = instance.getSettings()['persistentState']; plugin.enabled = !!(pluginSettings); if (!plugin.enabled) { removeHooks.call(instance); return; } if (!instance.storage) { instance.storage = new StorageClass(instance.rootElement[0].id); } instance.resetState = plugin.resetValue; addHooks.call(instance); }; this.saveValue = function (key, value) { var instance = this; instance.storage.saveValue(key, value); }; this.loadValue = function (key, saveTo) { var instance = this; saveTo.value = instance.storage.loadValue(key); }; this.resetValue = function (key) { var instance = this; if (typeof key != 'undefined') { instance.storage.reset(key); } else { instance.storage.resetAll(); } }; var hooks = { 'persistentStateSave': plugin.saveValue, 'persistentStateLoad': plugin.loadValue, 'persistentStateReset': plugin.resetValue }; function addHooks() { var instance = this; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName) && !hookExists.call(instance, hookName)) { instance.PluginHooks.add(hookName, hooks[hookName]); } } } function removeHooks() { var instance = this; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName) && hookExists.call(instance, hookName)) { instance.PluginHooks.remove(hookName, hooks[hookName]); } } } function hookExists(hookName) { var instance = this; return instance.PluginHooks.hooks.hasOwnProperty(hookName); } } var htPersistentState = new HandsontablePersistentState(); Handsontable.PluginHooks.add('beforeInit', htPersistentState.init); Handsontable.PluginHooks.add('afterUpdateSettings', htPersistentState.init); })(Storage); /** * Handsontable UndoRedo class */ (function(Handsontable){ Handsontable.UndoRedo = function (instance) { var plugin = this; this.instance = instance; this.doneActions = []; this.undoneActions = []; this.ignoreNewActions = false; instance.addHook("afterChange", function (changes, origin) { if(changes){ var action = new Handsontable.UndoRedo.ChangeAction(changes); plugin.done(action); } }); instance.addHook("afterCreateRow", function (index, amount, createdAutomatically) { if (createdAutomatically) { return; } var action = new Handsontable.UndoRedo.CreateRowAction(index, amount); plugin.done(action); }); instance.addHook("beforeRemoveRow", function (index, amount) { var originalData = plugin.instance.getData(); index = ( originalData.length + index ) % originalData.length; var removedData = originalData.slice(index, index + amount); var action = new Handsontable.UndoRedo.RemoveRowAction(index, removedData); plugin.done(action); }); instance.addHook("afterCreateCol", function (index, amount, createdAutomatically) { if (createdAutomatically) { return; } var action = new Handsontable.UndoRedo.CreateColumnAction(index, amount); plugin.done(action); }); instance.addHook("beforeRemoveCol", function (index, amount) { var originalData = plugin.instance.getData(); index = ( plugin.instance.countCols() + index ) % plugin.instance.countCols(); var removedData = []; for (var i = 0, len = originalData.length; i < len; i++) { removedData[i] = originalData[i].slice(index, index + amount); } var headers; if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ headers = instance.getSettings().colHeaders.slice(index, index + removedData.length); } var action = new Handsontable.UndoRedo.RemoveColumnAction(index, removedData, headers); plugin.done(action); }); }; Handsontable.UndoRedo.prototype.done = function (action) { if (!this.ignoreNewActions) { this.doneActions.push(action); this.undoneActions.length = 0; } }; /** * Undo operation from current revision */ Handsontable.UndoRedo.prototype.undo = function () { if (this.isUndoAvailable()) { var action = this.doneActions.pop(); this.ignoreNewActions = true; action.undo(this.instance); this.ignoreNewActions = false; this.undoneActions.push(action); } }; /** * Redo operation from current revision */ Handsontable.UndoRedo.prototype.redo = function () { if (this.isRedoAvailable()) { var action = this.undoneActions.pop(); this.ignoreNewActions = true; action.redo(this.instance); this.ignoreNewActions = true; this.doneActions.push(action); } }; /** * Returns true if undo point is available * @return {Boolean} */ Handsontable.UndoRedo.prototype.isUndoAvailable = function () { return this.doneActions.length > 0; }; /** * Returns true if redo point is available * @return {Boolean} */ Handsontable.UndoRedo.prototype.isRedoAvailable = function () { return this.undoneActions.length > 0; }; /** * Clears undo history */ Handsontable.UndoRedo.prototype.clear = function () { this.doneActions.length = 0; this.undoneActions.length = 0; }; Handsontable.UndoRedo.Action = function () { }; Handsontable.UndoRedo.Action.prototype.undo = function () { }; Handsontable.UndoRedo.Action.prototype.redo = function () { }; Handsontable.UndoRedo.ChangeAction = function (changes) { this.changes = changes; }; Handsontable.helper.inherit(Handsontable.UndoRedo.ChangeAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.ChangeAction.prototype.undo = function (instance) { var data = $.extend(true, [], this.changes); for (var i = 0, len = data.length; i < len; i++) { data[i].splice(3, 1); } instance.setDataAtRowProp(data, null, null, 'undo'); }; Handsontable.UndoRedo.ChangeAction.prototype.redo = function (instance) { var data = $.extend(true, [], this.changes); for (var i = 0, len = data.length; i < len; i++) { data[i].splice(2, 1); } instance.setDataAtRowProp(data, null, null, 'redo'); }; Handsontable.UndoRedo.CreateRowAction = function (index, amount) { this.index = index; this.amount = amount; }; Handsontable.helper.inherit(Handsontable.UndoRedo.CreateRowAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.CreateRowAction.prototype.undo = function (instance) { instance.alter('remove_row', this.index, this.amount); }; Handsontable.UndoRedo.CreateRowAction.prototype.redo = function (instance) { instance.alter('insert_row', this.index + 1, this.amount); }; Handsontable.UndoRedo.RemoveRowAction = function (index, data) { this.index = index; this.data = data; }; Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveRowAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.RemoveRowAction.prototype.undo = function (instance) { var spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.data); Array.prototype.splice.apply(instance.getData(), spliceArgs); instance.render(); }; Handsontable.UndoRedo.RemoveRowAction.prototype.redo = function (instance) { instance.alter('remove_row', this.index, this.data.length); }; Handsontable.UndoRedo.CreateColumnAction = function (index, amount) { this.index = index; this.amount = amount; }; Handsontable.helper.inherit(Handsontable.UndoRedo.CreateColumnAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.CreateColumnAction.prototype.undo = function (instance) { instance.alter('remove_col', this.index, this.amount); }; Handsontable.UndoRedo.CreateColumnAction.prototype.redo = function (instance) { instance.alter('insert_col', this.index + 1, this.amount); }; Handsontable.UndoRedo.RemoveColumnAction = function (index, data, headers) { this.index = index; this.data = data; this.amount = this.data[0].length; this.headers = headers; }; Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveColumnAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.RemoveColumnAction.prototype.undo = function (instance) { var row, spliceArgs; for (var i = 0, len = instance.getData().length; i < len; i++) { row = instance.getDataAtRow(i); spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.data[i]); Array.prototype.splice.apply(row, spliceArgs); } if(typeof this.headers != 'undefined'){ spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.headers); Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArgs); } instance.render(); }; Handsontable.UndoRedo.RemoveColumnAction.prototype.redo = function (instance) { instance.alter('remove_col', this.index, this.amount); }; })(Handsontable); (function(Handsontable){ function init(){ var instance = this; var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo; if(pluginEnabled){ if(!instance.undoRedo){ instance.undoRedo = new Handsontable.UndoRedo(instance); exposeUndoRedoMethods(instance); instance.addHook('beforeKeyDown', onBeforeKeyDown); instance.addHook('afterChange', onAfterChange); } } else { if(instance.undoRedo){ delete instance.undoRedo; removeExposedUndoRedoMethods(instance); instance.removeHook('beforeKeyDown', onBeforeKeyDown); instance.removeHook('afterChange', onAfterChange); } } } function onBeforeKeyDown(event){ var instance = this; var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; if(ctrlDown){ if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { //CTRL + Y or CTRL + SHIFT + Z instance.undoRedo.redo(); event.stopImmediatePropagation(); } else if (event.keyCode === 90) { //CTRL + Z instance.undoRedo.undo(); event.stopImmediatePropagation(); } } } function onAfterChange(changes, source){ var instance = this; if (source == 'loadData'){ return instance.undoRedo.clear(); } } function exposeUndoRedoMethods(instance){ instance.undo = function(){ return instance.undoRedo.undo(); }; instance.redo = function(){ return instance.undoRedo.redo(); }; instance.isUndoAvailable = function(){ return instance.undoRedo.isUndoAvailable(); }; instance.isRedoAvailable = function(){ return instance.undoRedo.isRedoAvailable(); }; instance.clearUndo = function(){ return instance.undoRedo.clear(); }; } function removeExposedUndoRedoMethods(instance){ delete instance.undo; delete instance.redo; delete instance.isUndoAvailable; delete instance.isRedoAvailable; delete instance.clearUndo; } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); })(Handsontable); /** * Plugin used to scroll Handsontable by selecting a cell and dragging outside of visible viewport * @constructor */ function DragToScroll() { this.boundaries = null; this.callback = null; } /** * @param boundaries {Object} compatible with getBoundingClientRect */ DragToScroll.prototype.setBoundaries = function (boundaries) { this.boundaries = boundaries; }; /** * @param callback {Function} */ DragToScroll.prototype.setCallback = function (callback) { this.callback = callback; }; /** * Check if mouse position (x, y) is outside of the viewport * @param x * @param y */ DragToScroll.prototype.check = function (x, y) { var diffX = 0; var diffY = 0; if (y < this.boundaries.top) { //y is less than top diffY = y - this.boundaries.top; } else if (y > this.boundaries.bottom) { //y is more than bottom diffY = y - this.boundaries.bottom; } if (x < this.boundaries.left) { //x is less than left diffX = x - this.boundaries.left; } else if (x > this.boundaries.right) { //x is more than right diffX = x - this.boundaries.right; } this.callback(diffX, diffY); }; var listening = false; var dragToScroll; var instance; if (typeof Handsontable !== 'undefined') { var setupListening = function (instance) { var scrollHandler = instance.view.wt.wtScrollbars.vertical.scrollHandler; //native scroll dragToScroll = new DragToScroll(); if (scrollHandler === window) { //not much we can do currently return; } else if (scrollHandler) { dragToScroll.setBoundaries(scrollHandler.getBoundingClientRect()); } else { dragToScroll.setBoundaries(instance.$table[0].getBoundingClientRect()); } dragToScroll.setCallback(function (scrollX, scrollY) { if (scrollX < 0) { if (scrollHandler) { scrollHandler.scrollLeft -= 50; } else { instance.view.wt.scrollHorizontal(-1).draw(); } } else if (scrollX > 0) { if (scrollHandler) { scrollHandler.scrollLeft += 50; } else { instance.view.wt.scrollHorizontal(1).draw(); } } if (scrollY < 0) { if (scrollHandler) { scrollHandler.scrollTop -= 20; } else { instance.view.wt.scrollVertical(-1).draw(); } } else if (scrollY > 0) { if (scrollHandler) { scrollHandler.scrollTop += 20; } else { instance.view.wt.scrollVertical(1).draw(); } } }); listening = true; }; Handsontable.PluginHooks.add('afterInit', function () { $(document).on('mouseup.' + this.guid, function () { listening = false; }); $(document).on('mousemove.' + this.guid, function (event) { if (listening) { dragToScroll.check(event.clientX, event.clientY); } }); }); Handsontable.PluginHooks.add('destroy', function () { $(document).off('.' + this.guid); }); Handsontable.PluginHooks.add('afterOnCellMouseDown', function () { setupListening(this); }); Handsontable.PluginHooks.add('afterOnCellCornerMouseDown', function () { setupListening(this); }); } (function (Handsontable, CopyPaste, SheetClip) { function CopyPastePlugin(instance) { this.copyPasteInstance = CopyPaste.getInstance(); this.copyPasteInstance.onCut(onCut); this.copyPasteInstance.onPaste(onPaste); var plugin = this; instance.addHook('beforeKeyDown', onBeforeKeyDown); function onCut() { if (!instance.isListening()) { return; } instance.selection.empty(); } function onPaste(str) { if (!instance.isListening() || !instance.selection.isSelected()) { return; } var input = str.replace(/^[\r\n]*/g, '').replace(/[\r\n]*$/g, '') //remove newline from the start and the end of the input , inputArray = SheetClip.parse(input) , selected = instance.getSelected() , coords = instance.getCornerCoords([{row: selected[0], col: selected[1]}, {row: selected[2], col: selected[3]}]) , areaStart = coords.TL , areaEnd = { row: Math.max(coords.BR.row, inputArray.length - 1 + coords.TL.row), col: Math.max(coords.BR.col, inputArray[0].length - 1 + coords.TL.col) }; instance.PluginHooks.once('afterChange', function (changes, source) { if (changes && changes.length) { this.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col); } }); instance.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'paste', instance.getSettings().pasteMode); }; function onBeforeKeyDown (event) { if (Handsontable.helper.isCtrlKey(event.keyCode) && instance.getSelected()) { //when CTRL is pressed, prepare selectable text in textarea //http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript plugin.setCopyableText(); event.stopImmediatePropagation(); return; } var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) if (event.keyCode == Handsontable.helper.keyCode.A && ctrlDown) { setTimeout(Handsontable.helper.proxy(plugin.setCopyableText, plugin)); } } this.destroy = function () { this.copyPasteInstance.removeCallback(onCut); this.copyPasteInstance.removeCallback(onPaste); this.copyPasteInstance.destroy(); instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; instance.addHook('afterDestroy', Handsontable.helper.proxy(this.destroy, this)); this.triggerPaste = Handsontable.helper.proxy(this.copyPasteInstance.triggerPaste, this.copyPasteInstance); this.triggerCut = Handsontable.helper.proxy(this.copyPasteInstance.triggerCut, this.copyPasteInstance); /** * Prepares copyable text in the invisible textarea */ this.setCopyableText = function () { var selection = instance.getSelected(); var settings = instance.getSettings(); var copyRowsLimit = settings.copyRowsLimit; var copyColsLimit = settings.copyColsLimit; var startRow = Math.min(selection[0], selection[2]); var startCol = Math.min(selection[1], selection[3]); var endRow = Math.max(selection[0], selection[2]); var endCol = Math.max(selection[1], selection[3]); 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) { instance.PluginHooks.run("afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, copyRowsLimit, copyColsLimit); } }; } function init() { var instance = this; var pluginEnabled = instance.getSettings().copyPaste !== false; if(pluginEnabled && !instance.copyPaste){ instance.copyPaste = new CopyPastePlugin(instance); } else if (!pluginEnabled && instance.copyPaste) { instance.copyPaste.destroy(); delete instance.copyPaste; } } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); })(Handsontable, CopyPaste, SheetClip); /** * Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable * and (optionally) implements behavior needed for native horizontal and vertical scrolling */ function WalkontableOverlay() { this.maxOuts = 10; //max outs in one direction (before and after table) } /* Possible optimizations: [x] don't rerender if scroll delta is smaller than the fragment outside of the viewport [ ] move .style.top change before .draw() [ ] put .draw() in requestAnimationFrame [ ] don't rerender rows that remain visible after the scroll */ WalkontableOverlay.prototype.init = function () { this.TABLE = this.instance.wtTable.TABLE; this.fixed = this.instance.wtTable.hider; this.fixedContainer = this.instance.wtTable.holder; this.fixed.style.position = 'absolute'; this.fixed.style.left = '0'; this.scrollHandler = this.getScrollableElement(this.TABLE); this.$scrollHandler = $(this.scrollHandler); //in future remove jQuery from here }; WalkontableOverlay.prototype.makeClone = function (direction) { var clone = document.createElement('DIV'); clone.className = 'ht_clone_' + direction + ' handsontable'; clone.style.position = 'fixed'; clone.style.overflow = 'hidden'; var table2 = document.createElement('TABLE'); table2.className = this.instance.wtTable.TABLE.className; clone.appendChild(table2); this.instance.wtTable.holder.parentNode.appendChild(clone); return new Walkontable({ cloneSource: this.instance, cloneOverlay: this, table: table2 }); }; WalkontableOverlay.prototype.getScrollableElement = function (TABLE) { var el = TABLE.parentNode; while (el && el.style) { if (el.style.overflow !== 'visible' && el.style.overflow !== '') { return el; } if (this instanceof WalkontableHorizontalScrollbarNative && el.style.overflowX !== 'visible' && el.style.overflowX !== '') { return el; } el = el.parentNode; } return window; }; WalkontableOverlay.prototype.prepare = function () { }; WalkontableOverlay.prototype.onScroll = function (forcePosition) { this.windowScrollPosition = this.getScrollPosition(); this.readSettings(); //read window scroll position if (forcePosition) { this.windowScrollPosition = forcePosition; } this.resetFixedPosition(); //may be redundant }; WalkontableOverlay.prototype.availableSize = function () { var availableSize; if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table if (this.instance.wtTable.getLastVisibleRow() === this.total - 1) { availableSize = this.instance.wtDom.outerHeight(this.TABLE); } else { availableSize = this.windowSize; } } else { availableSize = this.windowSize - (this.tableParentOffset); } return availableSize; }; WalkontableOverlay.prototype.refresh = function (selectionsOnly) { var last = this.getLastCell(); this.measureBefore = this.sumCellSizes(0, this.offset); if (last === -1) { //last -1 means that viewport is scrolled behind the table this.measureAfter = 0; } else { this.measureAfter = this.sumCellSizes(last, this.total - last); } this.applyToDOM(); this.clone && this.clone.draw(selectionsOnly); }; WalkontableOverlay.prototype.destroy = function () { this.$scrollHandler.off('.' + this.instance.guid); $(window).off('.' + this.instance.guid); $(document).off('.' + this.instance.guid); }; function WalkontableBorder(instance, settings) { var style; //reference to instance this.instance = instance; this.settings = settings; this.wtDom = this.instance.wtDom; this.main = document.createElement("div"); style = this.main.style; style.position = 'absolute'; style.top = 0; style.left = 0; // style.visibility = 'hidden'; for (var i = 0; i < 5; i++) { var DIV = document.createElement('DIV'); DIV.className = 'wtBorder ' + (settings.className || ''); style = DIV.style; style.backgroundColor = settings.border.color; style.height = settings.border.width + 'px'; style.width = settings.border.width + 'px'; this.main.appendChild(DIV); } this.top = this.main.childNodes[0]; this.left = this.main.childNodes[1]; this.bottom = this.main.childNodes[2]; this.right = this.main.childNodes[3]; /*$(this.top).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.left).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.bottom).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.right).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); });*/ this.topStyle = this.top.style; this.leftStyle = this.left.style; this.bottomStyle = this.bottom.style; this.rightStyle = this.right.style; this.corner = this.main.childNodes[4]; this.corner.className += ' corner'; this.cornerStyle = this.corner.style; this.cornerStyle.width = '5px'; this.cornerStyle.height = '5px'; this.cornerStyle.border = '2px solid #FFF'; this.disappear(); if (!instance.wtTable.bordersHolder) { instance.wtTable.bordersHolder = document.createElement('div'); instance.wtTable.bordersHolder.className = 'htBorders'; instance.wtTable.hider.appendChild(instance.wtTable.bordersHolder); } instance.wtTable.bordersHolder.appendChild(this.main); var down = false; var $body = $(document.body); $body.on('mousedown.walkontable.' + instance.guid, function () { down = true; }); $body.on('mouseup.walkontable.' + instance.guid, function () { down = false }); $(this.main.childNodes).on('mouseenter', function (event) { if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) { return; } event.preventDefault(); event.stopImmediatePropagation(); var bounds = this.getBoundingClientRect(); var $this = $(this); $this.hide(); var isOutside = function (event) { if (event.clientY < Math.floor(bounds.top)) { return true; } if (event.clientY > Math.ceil(bounds.top + bounds.height)) { return true; } if (event.clientX < Math.floor(bounds.left)) { return true; } if (event.clientX > Math.ceil(bounds.left + bounds.width)) { return true; } }; $body.on('mousemove.border.' + instance.guid, function (event) { if (isOutside(event)) { $body.off('mousemove.border.' + instance.guid); $this.show(); } }); }); } /** * Show border around one or many cells * @param {Array} corners */ WalkontableBorder.prototype.appear = function (corners) { var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width; if (this.disabled) { return; } var instance = this.instance , fromRow , fromColumn , toRow , toColumn , hideTop = false , hideLeft = false , hideBottom = false , hideRight = false , i , ilen , s; if (!instance.wtTable.isRowInViewport(corners[0])) { hideTop = true; } if (!instance.wtTable.isRowInViewport(corners[2])) { hideBottom = true; } ilen = instance.wtTable.rowStrategy.countVisible(); for (i = 0; i < ilen; i++) { s = instance.wtTable.rowFilter.visibleToSource(i); if (s >= corners[0] && s <= corners[2]) { fromRow = s; break; } } for (i = ilen - 1; i >= 0; i--) { s = instance.wtTable.rowFilter.visibleToSource(i); if (s >= corners[0] && s <= corners[2]) { toRow = s; break; } } if (hideTop && hideBottom) { hideLeft = true; hideRight = true; } else { if (!instance.wtTable.isColumnInViewport(corners[1])) { hideLeft = true; } if (!instance.wtTable.isColumnInViewport(corners[3])) { hideRight = true; } ilen = instance.wtTable.columnStrategy.countVisible(); for (i = 0; i < ilen; i++) { s = instance.wtTable.columnFilter.visibleToSource(i); if (s >= corners[1] && s <= corners[3]) { fromColumn = s; break; } } for (i = ilen - 1; i >= 0; i--) { s = instance.wtTable.columnFilter.visibleToSource(i); if (s >= corners[1] && s <= corners[3]) { toColumn = s; break; } } } if (fromRow !== void 0 && fromColumn !== void 0) { isMultiple = (fromRow !== toRow || fromColumn !== toColumn); fromTD = instance.wtTable.getCell([fromRow, fromColumn]); toTD = isMultiple ? instance.wtTable.getCell([toRow, toColumn]) : fromTD; fromOffset = this.wtDom.offset(fromTD); toOffset = isMultiple ? this.wtDom.offset(toTD) : fromOffset; containerOffset = this.wtDom.offset(instance.wtTable.TABLE); minTop = fromOffset.top; height = toOffset.top + this.wtDom.outerHeight(toTD) - minTop; minLeft = fromOffset.left; width = toOffset.left + this.wtDom.outerWidth(toTD) - minLeft; top = minTop - containerOffset.top - 1; left = minLeft - containerOffset.left - 1; var style = this.wtDom.getComputedStyle(fromTD); if (parseInt(style['borderTopWidth'], 10) > 0) { top += 1; height = height > 0 ? height - 1 : 0; } if (parseInt(style['borderLeftWidth'], 10) > 0) { left += 1; width = width > 0 ? width - 1 : 0; } } else { this.disappear(); return; } if (hideTop) { this.topStyle.display = 'none'; } else { this.topStyle.top = top + 'px'; this.topStyle.left = left + 'px'; this.topStyle.width = width + 'px'; this.topStyle.display = 'block'; } if (hideLeft) { this.leftStyle.display = 'none'; } else { this.leftStyle.top = top + 'px'; this.leftStyle.left = left + 'px'; this.leftStyle.height = height + 'px'; this.leftStyle.display = 'block'; } var delta = Math.floor(this.settings.border.width / 2); if (hideBottom) { this.bottomStyle.display = 'none'; } else { this.bottomStyle.top = top + height - delta + 'px'; this.bottomStyle.left = left + 'px'; this.bottomStyle.width = width + 'px'; this.bottomStyle.display = 'block'; } if (hideRight) { this.rightStyle.display = 'none'; } else { this.rightStyle.top = top + 'px'; this.rightStyle.left = left + width - delta + 'px'; this.rightStyle.height = height + 1 + 'px'; this.rightStyle.display = 'block'; } if (hideBottom || hideRight || !this.hasSetting(this.settings.border.cornerVisible)) { this.cornerStyle.display = 'none'; } else { this.cornerStyle.top = top + height - 4 + 'px'; this.cornerStyle.left = left + width - 4 + 'px'; this.cornerStyle.display = 'block'; } }; /** * Hide border */ WalkontableBorder.prototype.disappear = function () { this.topStyle.display = 'none'; this.leftStyle.display = 'none'; this.bottomStyle.display = 'none'; this.rightStyle.display = 'none'; this.cornerStyle.display = 'none'; }; WalkontableBorder.prototype.hasSetting = function (setting) { if (typeof setting === 'function') { return setting(); } return !!setting; }; /** * WalkontableCellFilter * @constructor */ function WalkontableCellFilter() { this.offset = 0; this.total = 0; this.fixedCount = 0; } WalkontableCellFilter.prototype.source = function (n) { return n; }; WalkontableCellFilter.prototype.offsetted = function (n) { return n + this.offset; }; WalkontableCellFilter.prototype.unOffsetted = function (n) { return n - this.offset; }; WalkontableCellFilter.prototype.fixed = function (n) { if (n < this.fixedCount) { return n - this.offset; } else { return n; } }; WalkontableCellFilter.prototype.unFixed = function (n) { if (n < this.fixedCount) { return n + this.offset; } else { return n; } }; WalkontableCellFilter.prototype.visibleToSource = function (n) { return this.source(this.offsetted(this.fixed(n))); }; WalkontableCellFilter.prototype.sourceToVisible = function (n) { return this.source(this.unOffsetted(this.unFixed(n))); }; /** * WalkontableCellStrategy * @constructor */ function WalkontableCellStrategy(instance) { this.instance = instance; } WalkontableCellStrategy.prototype.getSize = function (index) { return this.cellSizes[index]; }; WalkontableCellStrategy.prototype.getContainerSize = function (proposedSize) { return typeof this.containerSizeFn === 'function' ? this.containerSizeFn(proposedSize) : this.containerSizeFn; }; WalkontableCellStrategy.prototype.countVisible = function () { return this.cellCount; }; WalkontableCellStrategy.prototype.isLastIncomplete = function () { if(this.instance.getSetting('nativeScrollbars')){ var nativeScrollbar = this.instance.cloneFrom ? this.instance.cloneFrom.wtScrollbars.vertical : this.instance.wtScrollbars.vertical; return this.remainingSize > nativeScrollbar.sumCellSizes(nativeScrollbar.offset, nativeScrollbar.offset + nativeScrollbar.curOuts + 1); } else { return this.remainingSize > 0; } }; /** * WalkontableClassNameList * @constructor */ function WalkontableClassNameCache() { this.cache = []; } WalkontableClassNameCache.prototype.add = function (r, c, cls) { if (!this.cache[r]) { this.cache[r] = []; } if (!this.cache[r][c]) { this.cache[r][c] = []; } this.cache[r][c][cls] = true; }; WalkontableClassNameCache.prototype.test = function (r, c, cls) { return (this.cache[r] && this.cache[r][c] && this.cache[r][c][cls]); }; /** * WalkontableColumnFilter * @constructor */ function WalkontableColumnFilter() { this.countTH = 0; } WalkontableColumnFilter.prototype = new WalkontableCellFilter(); WalkontableColumnFilter.prototype.readSettings = function (instance) { this.offset = instance.wtSettings.settings.offsetColumn; this.total = instance.getSetting('totalColumns'); this.fixedCount = instance.getSetting('fixedColumnsLeft'); this.countTH = instance.getSetting('rowHeaders').length; }; WalkontableColumnFilter.prototype.offsettedTH = function (n) { return n - this.countTH; }; WalkontableColumnFilter.prototype.unOffsettedTH = function (n) { return n + this.countTH; }; WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function (n) { return this.visibleToSource(this.offsettedTH(n)); }; WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function (n) { return this.unOffsettedTH(this.sourceToVisible(n)); }; /** * WalkontableColumnStrategy * @param containerSizeFn * @param sizeAtIndex * @param strategy - all, last, none * @constructor */ function WalkontableColumnStrategy(instance, containerSizeFn, sizeAtIndex, strategy) { var size , i = 0; WalkontableCellStrategy.apply(this, arguments); this.containerSizeFn = containerSizeFn; this.cellSizesSum = 0; this.cellSizes = []; this.cellStretch = []; this.cellCount = 0; this.remainingSize = 0; this.strategy = strategy; //step 1 - determine cells that fit containerSize and cache their widths while (true) { size = sizeAtIndex(i); if (size === void 0) { break; //total columns exceeded } if (this.cellSizesSum >= this.getContainerSize(this.cellSizesSum + size)) { break; //total width exceeded } this.cellSizes.push(size); this.cellSizesSum += size; this.cellCount++; i++; } var containerSize = this.getContainerSize(this.cellSizesSum); this.remainingSize = this.cellSizesSum - containerSize; //negative value means the last cell is fully visible and there is some space left for stretching //positive value means the last cell is not fully visible } WalkontableColumnStrategy.prototype = new WalkontableCellStrategy(); WalkontableColumnStrategy.prototype.getSize = function (index) { return this.cellSizes[index] + (this.cellStretch[index] || 0); }; WalkontableColumnStrategy.prototype.stretch = function () { //step 2 - apply stretching strategy var containerSize = this.getContainerSize(this.cellSizesSum) , i = 0; this.remainingSize = this.cellSizesSum - containerSize; this.cellStretch.length = 0; //clear previous stretch if (this.strategy === 'all') { if (this.remainingSize < 0) { var ratio = containerSize / this.cellSizesSum; var newSize; while (i < this.cellCount - 1) { //"i < this.cellCount - 1" is needed because last cellSize is adjusted after the loop newSize = Math.floor(ratio * this.cellSizes[i]); this.remainingSize += newSize - this.cellSizes[i]; this.cellStretch[i] = newSize - this.cellSizes[i]; i++; } this.cellStretch[this.cellCount - 1] = -this.remainingSize; this.remainingSize = 0; } } else if (this.strategy === 'last') { if (this.remainingSize < 0 && containerSize !== Infinity) { //Infinity is with native scroll when the table is wider than the viewport (TODO: test) this.cellStretch[this.cellCount - 1] = -this.remainingSize; this.remainingSize = 0; } } }; function Walkontable(settings) { var that = this, originalHeaders = []; this.guid = 'wt_' + walkontableRandomString(); //this is the namespace for global events //bootstrap from settings this.wtDom = new WalkontableDom(); if (settings.cloneSource) { this.cloneSource = settings.cloneSource; this.cloneOverlay = settings.cloneOverlay; this.wtSettings = settings.cloneSource.wtSettings; this.wtTable = new WalkontableTable(this, settings.table); this.wtScroll = new WalkontableScroll(this); this.wtViewport = settings.cloneSource.wtViewport; } 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.wtScrollbars = new WalkontableScrollbars(this); this.wtWheel = new WalkontableWheel(this); this.wtEvent = new WalkontableEvent(this); } //find original headers if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) { for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) { originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML); } if (!this.getSetting('columnHeaders').length) { this.update('columnHeaders', [function (column, TH) { that.wtDom.fastInnerText(TH, originalHeaders[column]); }]); } } //initialize selections this.selections = {}; var selectionsSettings = this.getSetting('selections'); if (selectionsSettings) { for (var i in selectionsSettings) { if (selectionsSettings.hasOwnProperty(i)) { this.selections[i] = new WalkontableSelection(this, selectionsSettings[i]); } } } this.drawn = false; this.drawInterrupted = false; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table /*if (window.Handsontable) { Handsontable.PluginHooks.add('beforeChange', function () { if (that.rowHeightCache) { that.rowHeightCache.length = 0; } }); }*/ } Walkontable.prototype.draw = function (selectionsOnly) { this.drawInterrupted = false; if (!selectionsOnly && !this.wtDom.isVisible(this.wtTable.TABLE)) { this.drawInterrupted = true; //draw interrupted because TABLE is not visible return; } this.getSetting('beforeDraw', !selectionsOnly); selectionsOnly = selectionsOnly && this.getSetting('offsetRow') === this.lastOffsetRow && this.getSetting('offsetColumn') === this.lastOffsetColumn; if (this.drawn) { //fix offsets that might have changed this.scrollVertical(0); this.scrollHorizontal(0); } this.lastOffsetRow = this.getSetting('offsetRow'); this.lastOffsetColumn = this.getSetting('offsetColumn'); this.wtTable.draw(selectionsOnly); if (!this.cloneSource) { this.getSetting('onDraw', !selectionsOnly); } return this; }; Walkontable.prototype.update = function (settings, value) { return this.wtSettings.update(settings, value); }; Walkontable.prototype.scrollVertical = function (delta) { var result = this.wtScroll.scrollVertical(delta); this.getSetting('onScrollVertically'); return result; }; Walkontable.prototype.scrollHorizontal = function (delta) { var result = this.wtScroll.scrollHorizontal(delta); this.getSetting('onScrollHorizontally'); return result; }; Walkontable.prototype.scrollViewport = function (coords) { this.wtScroll.scrollViewport(coords); return this; }; Walkontable.prototype.getViewport = function () { return [ this.wtTable.rowFilter.visibleToSource(0), this.wtTable.columnFilter.visibleToSource(0), this.wtTable.getLastVisibleRow(), this.wtTable.getLastVisibleColumn() ]; }; Walkontable.prototype.getSetting = function (key, param1, param2, param3) { return this.wtSettings.getSetting(key, param1, param2, param3); }; Walkontable.prototype.hasSetting = function (key) { return this.wtSettings.has(key); }; Walkontable.prototype.destroy = function () { $(document.body).off('.' + this.guid); this.wtScrollbars.destroy(); clearTimeout(this.wheelTimeout); this.wtEvent && this.wtEvent.destroy(); }; /** * A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays. * Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly * @param instance * @constructor */ function WalkontableDebugOverlay(instance) { this.instance = instance; this.init(); this.clone = this.makeClone('debug'); this.clone.wtTable.holder.style.opacity = 0.4; this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000'; var that = this; var lastTimeout; var lastX = 0; var lastY = 0; var overlayContainer = that.clone.wtTable.holder.parentNode; $(document.body).on('mousemove.' + this.instance.guid, function (event) { if (!that.instance.wtTable.holder.parentNode) { return; //removed from DOM } if ((event.clientX - lastX > -5 && event.clientX - lastX < 5) && (event.clientY - lastY > -5 && event.clientY - lastY < 5)) { return; //ignore minor mouse movement } lastX = event.clientX; lastY = event.clientY; WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugHidden'); WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugVisible'); clearTimeout(lastTimeout); lastTimeout = setTimeout(function () { WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugHidden'); WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugVisible'); }, 1000); }); } WalkontableDebugOverlay.prototype = new WalkontableOverlay(); WalkontableDebugOverlay.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box = this.instance.wtTable.holder.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; }; WalkontableDebugOverlay.prototype.prepare = function () { }; WalkontableDebugOverlay.prototype.refresh = function (selectionsOnly) { this.clone && this.clone.draw(selectionsOnly); }; WalkontableDebugOverlay.prototype.getScrollPosition = function () { }; WalkontableDebugOverlay.prototype.getLastCell = function () { }; WalkontableDebugOverlay.prototype.applyToDOM = function () { }; WalkontableDebugOverlay.prototype.scrollTo = function () { }; WalkontableDebugOverlay.prototype.readWindowSize = function () { }; WalkontableDebugOverlay.prototype.readSettings = function () { }; function WalkontableDom() { } //goes up the DOM tree (including given element) until it finds an element that matches the nodeName WalkontableDom.prototype.closest = function (elem, nodeNames, until) { while (elem != null && elem !== until) { if (elem.nodeType === 1 && nodeNames.indexOf(elem.nodeName) > -1) { return elem; } elem = elem.parentNode; } return null; }; //goes up the DOM tree and checks if element is child of another element WalkontableDom.prototype.isChildOf = function (child, parent) { var node = child.parentNode; while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; }; /** * Counts index of element within its parent * WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable * Otherwise would need to check for nodeType or use previousElementSibling * @see http://jsperf.com/sibling-index/10 * @param {Element} elem * @return {Number} */ WalkontableDom.prototype.index = function (elem) { var i = 0; while (elem = elem.previousSibling) { ++i } return i; }; if (document.documentElement.classList) { // HTML5 classList API WalkontableDom.prototype.hasClass = function (ele, cls) { return ele.classList.contains(cls); }; WalkontableDom.prototype.addClass = function (ele, cls) { ele.classList.add(cls); }; WalkontableDom.prototype.removeClass = function (ele, cls) { ele.classList.remove(cls); }; } else { //http://snipplr.com/view/3561/addclass-removeclass-hasclass/ WalkontableDom.prototype.hasClass = function (ele, cls) { return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); }; WalkontableDom.prototype.addClass = function (ele, cls) { if (!this.hasClass(ele, cls)) ele.className += " " + cls; }; WalkontableDom.prototype.removeClass = function (ele, cls) { if (this.hasClass(ele, cls)) { //is this really needed? var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); ele.className = ele.className.replace(reg, ' ').trim(); //String.prototype.trim is defined in polyfill.js } }; } /*//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/ WalkontableDom.prototype.addEvent = (function () { var that = this; if (document.addEventListener) { return function (elem, type, cb) { if ((elem && !elem.length) || elem === window) { elem.addEventListener(type, cb, false); } else if (elem && elem.length) { var len = elem.length; for (var i = 0; i < len; i++) { that.addEvent(elem[i], type, cb); } } }; } else { return function (elem, type, cb) { if ((elem && !elem.length) || elem === window) { elem.attachEvent('on' + type, function () { //normalize //http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization var e = window['event']; e.target = e.srcElement; //e.offsetX = e.layerX; //e.offsetY = e.layerY; e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement; if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug return cb.call(elem, e) }); } else if (elem.length) { var len = elem.length; for (var i = 0; i < len; i++) { that.addEvent(elem[i], type, cb); } } }; } })(); WalkontableDom.prototype.triggerEvent = function (element, eventName, target) { var event; if (document.createEvent) { event = document.createEvent("MouseEvents"); event.initEvent(eventName, true, true); } else { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; event.target = target; if (document.createEvent) { target.dispatchEvent(event); } else { target.fireEvent("on" + event.eventType, event); } };*/ WalkontableDom.prototype.removeTextNodes = function (elem, parent) { if (elem.nodeType === 3) { parent.removeChild(elem); //bye text nodes! } else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) { var childs = elem.childNodes; for (var i = childs.length - 1; i >= 0; i--) { this.removeTextNodes(childs[i], elem); } } }; /** * Remove childs function * WARNING - this doesn't unload events and data attached by jQuery * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9 * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method * @param element * @returns {void} */ // WalkontableDom.prototype.empty = function (element) { var child; while (child = element.lastChild) { element.removeChild(child); } }; WalkontableDom.prototype.HTML_CHARACTERS = /(<(.*)>|&(.*);)/; /** * Insert content into element trying avoid innerHTML method. * @return {void} */ WalkontableDom.prototype.fastInnerHTML = function (element, content) { if (this.HTML_CHARACTERS.test(content)) { element.innerHTML = content; } else { this.fastInnerText(element, content); } }; /** * Insert text content into element * @return {void} */ if (document.createTextNode('test').textContent) { //STANDARDS WalkontableDom.prototype.fastInnerText = function (element, content) { var child = element.firstChild; if (child && child.nodeType === 3 && child.nextSibling === null) { //fast lane - replace existing text node //http://jsperf.com/replace-text-vs-reuse child.textContent = content; } else { //slow lane - empty element and insert a text node this.empty(element); element.appendChild(document.createTextNode(content)); } }; } else { //IE8 WalkontableDom.prototype.fastInnerText = function (element, content) { var child = element.firstChild; if (child && child.nodeType === 3 && child.nextSibling === null) { //fast lane - replace existing text node //http://jsperf.com/replace-text-vs-reuse child.data = content; } else { //slow lane - empty element and insert a text node this.empty(element); element.appendChild(document.createTextNode(content)); } }; } /** * Returns true/false depending if element has offset parent * @param elem * @returns {boolean} */ /*if (document.createTextNode('test').textContent) { //STANDARDS WalkontableDom.prototype.hasOffsetParent = function (elem) { return !!elem.offsetParent; } } else { WalkontableDom.prototype.hasOffsetParent = function (elem) { try { if (!elem.offsetParent) { return false; } } catch (e) { return false; //IE8 throws "Unspecified error" when offsetParent is not found - we catch it here } return true; } }*/ /** * Returns true if element is attached to the DOM and visible, false otherwise * @param elem * @returns {boolean} */ WalkontableDom.prototype.isVisible = function (elem) { //fast method according to benchmarks, but requires layout so slow in our case /* if (!WalkontableDom.prototype.hasOffsetParent(elem)) { return false; //fixes problem with UI Bootstrap <tabs> directive } // if (elem.offsetWidth > 0 || (elem.parentNode && elem.parentNode.offsetWidth > 0)) { //IE10 was mistaken here if (elem.offsetWidth > 0) { return true; } */ //slow method var next = elem; while (next !== document.documentElement) { //until <html> reached if (next === null) { //parent detached from DOM return false; } else if (next.nodeType === 11) { //nodeType == 1 -> DOCUMENT_FRAGMENT_NODE if (next.host) { //this is Web Components Shadow DOM //see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation //according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet if (next.host.impl) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled return WalkontableDom.prototype.isVisible(next.host.impl); } else if (next.host) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled return WalkontableDom.prototype.isVisible(next.host); } else { throw new Error("Lost in Web Components world"); } } else { return false; //this is a node detached from document in IE8 } } else if (next.style.display === 'none') { return false; } next = next.parentNode; } return true; }; /** * Returns elements top and left offset relative to the document. In our usage case compatible with jQuery but 2x faster * @param {HTMLElement} elem * @return {Object} */ WalkontableDom.prototype.offset = function (elem) { if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { //fixes problem with Firefox ignoring <caption> in TABLE offset (see also WalkontableDom.prototype.outerHeight) //http://jsperf.com/offset-vs-getboundingclientrect/8 var box = elem.getBoundingClientRect(); return { top: box.top + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0), left: box.left + (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0) }; } var offsetLeft = elem.offsetLeft , offsetTop = elem.offsetTop , lastElem = elem; while (elem = elem.offsetParent) { if (elem === document.body) { //from my observation, document.body always has scrollLeft/scrollTop == 0 break; } offsetLeft += elem.offsetLeft; offsetTop += elem.offsetTop; lastElem = elem; } if (lastElem && lastElem.style.position === 'fixed') { //slow - http://jsperf.com/offset-vs-getboundingclientrect/6 //if(lastElem !== document.body) { //faster but does gives false positive in Firefox offsetLeft += window.pageXOffset || document.documentElement.scrollLeft; offsetTop += window.pageYOffset || document.documentElement.scrollTop; } return { left: offsetLeft, top: offsetTop }; }; WalkontableDom.prototype.getComputedStyle = function (elem) { return elem.currentStyle || document.defaultView.getComputedStyle(elem); }; WalkontableDom.prototype.outerWidth = function (elem) { return elem.offsetWidth; }; WalkontableDom.prototype.outerHeight = function (elem) { if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { //fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight //jQuery (1.10.1) still has this unsolved //may be better to just switch to getBoundingClientRect //http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/ //http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html //http://bugs.jquery.com/ticket/2196 //http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140 return elem.offsetHeight + elem.firstChild.offsetHeight; } else { return elem.offsetHeight; } }; (function () { var hasCaptionProblem; function detectCaptionProblem() { var TABLE = document.createElement('TABLE'); TABLE.style.borderSpacing = 0; TABLE.style.borderWidth = 0; TABLE.style.padding = 0; var TBODY = document.createElement('TBODY'); TABLE.appendChild(TBODY); TBODY.appendChild(document.createElement('TR')); TBODY.firstChild.appendChild(document.createElement('TD')); TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>'; var CAPTION = document.createElement('CAPTION'); CAPTION.innerHTML = 'c<br>c<br>c<br>c'; CAPTION.style.padding = 0; CAPTION.style.margin = 0; TABLE.insertBefore(CAPTION, TBODY); document.body.appendChild(TABLE); hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); //boolean document.body.removeChild(TABLE); } WalkontableDom.prototype.hasCaptionProblem = function () { if (hasCaptionProblem === void 0) { detectCaptionProblem(); } return hasCaptionProblem; }; /** * Returns caret position in text input * @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea * @return {Number} */ WalkontableDom.prototype.getCaretPosition = function (el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { //IE8 el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }; /** * Sets caret position in text input * @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ * @param {Element} el * @param {Number} pos * @param {Number} endPos */ WalkontableDom.prototype.setCaretPosition = function (el, pos, endPos) { if (endPos === void 0) { endPos = pos; } if (el.setSelectionRange) { el.focus(); el.setSelectionRange(pos, endPos); } else if (el.createTextRange) { //IE8 var range = el.createTextRange(); range.collapse(true); range.moveEnd('character', endPos); range.moveStart('character', pos); range.select(); } }; var cachedScrollbarWidth; //http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes function walkontableCalculateScrollbarWidth() { var inner = document.createElement('p'); inner.style.width = "100%"; inner.style.height = "200px"; var outer = document.createElement('div'); outer.style.position = "absolute"; outer.style.top = "0px"; outer.style.left = "0px"; outer.style.visibility = "hidden"; outer.style.width = "200px"; outer.style.height = "150px"; outer.style.overflow = "hidden"; outer.appendChild(inner); (document.body || document.documentElement).appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 == w2) w2 = outer.clientWidth; (document.body || document.documentElement).removeChild(outer); return (w1 - w2); } /** * Returns the computed width of the native browser scroll bar * @return {Number} width */ WalkontableDom.prototype.getScrollbarWidth = function () { if (cachedScrollbarWidth === void 0) { cachedScrollbarWidth = walkontableCalculateScrollbarWidth(); } return cachedScrollbarWidth; } })(); function WalkontableEvent(instance) { var that = this; //reference to instance this.instance = instance; this.wtDom = this.instance.wtDom; var dblClickOrigin = [null, null]; var dblClickTimeout = [null, null]; var onMouseDown = function (event) { var cell = that.parentCell(event.target); if (that.wtDom.hasClass(event.target, 'corner')) { that.instance.getSetting('onCellCornerMouseDown', event, event.target); } else if (cell.TD && cell.TD.nodeName === 'TD') { if (that.instance.hasSetting('onCellMouseDown')) { that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD); } } if (event.button !== 2) { //if not right mouse button if (cell.TD && cell.TD.nodeName === 'TD') { dblClickOrigin[0] = cell.TD; clearTimeout(dblClickTimeout[0]); dblClickTimeout[0] = setTimeout(function () { dblClickOrigin[0] = null; }, 1000); } } }; var lastMouseOver; var onMouseOver = function (event) { if (that.instance.hasSetting('onCellMouseOver')) { var TABLE = that.instance.wtTable.TABLE; var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE); if (TD && TD !== lastMouseOver && that.wtDom.isChildOf(TD, TABLE)) { lastMouseOver = TD; if (TD.nodeName === 'TD') { that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(TD), TD); } } } }; /* var lastMouseOut; var onMouseOut = function (event) { if (that.instance.hasSetting('onCellMouseOut')) { var TABLE = that.instance.wtTable.TABLE; var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE); if (TD && TD !== lastMouseOut && that.wtDom.isChildOf(TD, TABLE)) { lastMouseOut = TD; if (TD.nodeName === 'TD') { that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(TD), TD); } } } };*/ var onMouseUp = function (event) { if (event.button !== 2) { //if not right mouse button var cell = that.parentCell(event.target); if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) { if (that.wtDom.hasClass(event.target, 'corner')) { that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD); } else if (cell.TD) { that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD); } dblClickOrigin[0] = null; dblClickOrigin[1] = null; } else if (cell.TD === dblClickOrigin[0]) { dblClickOrigin[1] = cell.TD; clearTimeout(dblClickTimeout[1]); dblClickTimeout[1] = setTimeout(function () { dblClickOrigin[1] = null; }, 500); } } }; $(this.instance.wtTable.holder).on('mousedown', onMouseDown); $(this.instance.wtTable.TABLE).on('mouseover', onMouseOver); // $(this.instance.wtTable.TABLE).on('mouseout', onMouseOut); $(this.instance.wtTable.holder).on('mouseup', onMouseUp); } WalkontableEvent.prototype.parentCell = function (elem) { var cell = {}; var TABLE = this.instance.wtTable.TABLE; var TD = this.wtDom.closest(elem, ['TD', 'TH'], TABLE); if (TD && this.wtDom.isChildOf(TD, TABLE)) { cell.coords = this.instance.wtTable.getCoords(TD); cell.TD = TD; } else if (this.wtDom.hasClass(elem, 'wtBorder') && this.wtDom.hasClass(elem, 'current')) { cell.coords = this.instance.selections.current.selected[0]; cell.TD = this.instance.wtTable.getCell(cell.coords); } return cell; }; WalkontableEvent.prototype.destroy = function () { clearTimeout(this.dblClickTimeout0); clearTimeout(this.dblClickTimeout1); }; function walkontableRangesIntersect() { var from = arguments[0]; var to = arguments[1]; for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) { if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) { return true; } } return false; } /** * Generates a random hex string. Used as namespace for Walkontable instance events. * @return {String} - 16 character random string: "92b1bfc74ec4" */ function walkontableRandomString() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + s4() + s4(); } /** * http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html */ window.requestAnimFrame = (function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (/* function */ callback, /* DOMElement */ element) { return window.setTimeout(callback, 1000 / 60); }; })(); window.cancelRequestAnimFrame = (function () { return window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || clearTimeout })(); //http://snipplr.com/view/13523/ //modified for speed //http://jsperf.com/getcomputedstyle-vs-style-vs-css/8 if (!window.getComputedStyle) { (function () { var elem; var styleObj = { getPropertyValue: function getPropertyValue(prop) { if (prop == 'float') prop = 'styleFloat'; return elem.currentStyle[prop.toUpperCase()] || null; } }; window.getComputedStyle = function (el) { elem = el; return styleObj; } })(); } /** * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim */ if (!String.prototype.trim) { var trimRegex = /^\s+|\s+$/g; String.prototype.trim = function () { return this.replace(trimRegex, ''); }; } /** * WalkontableRowFilter * @constructor */ function WalkontableRowFilter() { } WalkontableRowFilter.prototype = new WalkontableCellFilter(); WalkontableRowFilter.prototype.readSettings = function (instance) { if (instance.cloneOverlay instanceof WalkontableDebugOverlay) { this.offset = 0; } else { this.offset = instance.wtSettings.settings.offsetRow; } this.total = instance.getSetting('totalRows'); this.fixedCount = instance.getSetting('fixedRowsTop'); }; /** * WalkontableRowStrategy * @param containerSizeFn * @param sizeAtIndex * @constructor */ function WalkontableRowStrategy(instance, containerSizeFn, sizeAtIndex) { WalkontableCellStrategy.apply(this, arguments); this.containerSizeFn = containerSizeFn; this.sizeAtIndex = sizeAtIndex; this.cellSizesSum = 0; this.cellSizes = []; this.cellCount = 0; this.remainingSize = -Infinity; } WalkontableRowStrategy.prototype = new WalkontableCellStrategy(); WalkontableRowStrategy.prototype.add = function (i, TD, reverse) { if (!this.isLastIncomplete() && this.remainingSize != 0) { var size = this.sizeAtIndex(i, TD); if (size === void 0) { return false; //total rows exceeded } var containerSize = this.getContainerSize(this.cellSizesSum + size); if (reverse) { this.cellSizes.unshift(size); } else { this.cellSizes.push(size); } this.cellSizesSum += size; this.cellCount++; this.remainingSize = this.cellSizesSum - containerSize; if (reverse && this.isLastIncomplete()) { //something is outside of the screen, maybe even some full rows? return false; } return true; } return false; }; WalkontableRowStrategy.prototype.remove = function () { var size = this.cellSizes.pop(); this.cellSizesSum -= size; this.cellCount--; this.remainingSize -= size; }; WalkontableRowStrategy.prototype.removeOutstanding = function () { while (this.cellCount > 0 && this.cellSizes[this.cellCount - 1] < this.remainingSize) { //this row is completely off screen! this.remove(); } }; function WalkontableScroll(instance) { this.instance = instance; } WalkontableScroll.prototype.scrollVertical = function (delta) { if (!this.instance.drawn) { throw new Error('scrollVertical can only be called after table was drawn to DOM'); } var instance = this.instance , newOffset , offset = instance.getSetting('offsetRow') , fixedCount = instance.getSetting('fixedRowsTop') , total = instance.getSetting('totalRows') , maxSize = instance.wtViewport.getViewportHeight(); if (total > 0) { newOffset = this.scrollLogicVertical(delta, offset, total, fixedCount, maxSize, function (row) { if (row - offset < fixedCount && row - offset >= 0) { return instance.getSetting('rowHeight', row - offset); } else { return instance.getSetting('rowHeight', row); } }, function (isReverse) { instance.wtTable.verticalRenderReverse = isReverse; }); } else { newOffset = 0; } if (newOffset !== offset) { this.instance.wtScrollbars.vertical.scrollTo(newOffset); } return instance; }; WalkontableScroll.prototype.scrollHorizontal = function (delta) { if (!this.instance.drawn) { throw new Error('scrollHorizontal can only be called after table was drawn to DOM'); } var instance = this.instance , newOffset , offset = instance.getSetting('offsetColumn') , fixedCount = instance.getSetting('fixedColumnsLeft') , total = instance.getSetting('totalColumns') , maxSize = instance.wtViewport.getViewportWidth(); if (total > 0) { newOffset = this.scrollLogicHorizontal(delta, offset, total, fixedCount, maxSize, function (col) { if (col - offset < fixedCount && col - offset >= 0) { return instance.getSetting('columnWidth', col - offset); } else { return instance.getSetting('columnWidth', col); } }); } else { newOffset = 0; } if (newOffset !== offset) { this.instance.wtScrollbars.horizontal.scrollTo(newOffset); } return instance; }; WalkontableScroll.prototype.scrollLogicVertical = function (delta, offset, total, fixedCount, maxSize, cellSizeFn, setReverseRenderFn) { var newOffset = offset + delta; if (newOffset >= total - fixedCount) { newOffset = total - fixedCount - 1; setReverseRenderFn(true); } if (newOffset < 0) { newOffset = 0; } return newOffset; }; WalkontableScroll.prototype.scrollLogicHorizontal = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) { var newOffset = offset + delta , sum = 0 , col; if (newOffset > fixedCount) { if (newOffset >= total - fixedCount) { newOffset = total - fixedCount - 1; } col = newOffset; while (sum < maxSize && col < total) { sum += cellSizeFn(col); col++; } if (sum < maxSize) { while (newOffset > 0) { //if sum still less than available width, we cannot scroll that far (must move offset to the left) sum += cellSizeFn(newOffset - 1); if (sum < maxSize) { newOffset--; } else { break; } } } } else if (newOffset < 0) { newOffset = 0; } return newOffset; }; /** * Scrolls viewport to a cell by minimum number of cells */ WalkontableScroll.prototype.scrollViewport = function (coords) { if (!this.instance.drawn) { return; } var offsetRow = this.instance.getSetting('offsetRow') , offsetColumn = this.instance.getSetting('offsetColumn') , lastVisibleRow = this.instance.wtTable.getLastVisibleRow() , totalRows = this.instance.getSetting('totalRows') , totalColumns = this.instance.getSetting('totalColumns') , fixedRowsTop = this.instance.getSetting('fixedRowsTop') , fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft'); if (this.instance.getSetting('nativeScrollbars')) { var TD = this.instance.wtTable.getCell(coords); if (typeof TD === 'object') { var offset = WalkontableDom.prototype.offset(TD); var outerWidth = WalkontableDom.prototype.outerWidth(TD); var outerHeight = WalkontableDom.prototype.outerHeight(TD); var scrollX = this.instance.wtScrollbars.horizontal.getScrollPosition(); var scrollY = this.instance.wtScrollbars.vertical.getScrollPosition(); var clientWidth = WalkontableDom.prototype.outerWidth(this.instance.wtScrollbars.horizontal.scrollHandler); var clientHeight = WalkontableDom.prototype.outerHeight(this.instance.wtScrollbars.vertical.scrollHandler); if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) { offset.left = offset.left - WalkontableDom.prototype.offset(this.instance.wtScrollbars.horizontal.scrollHandler).left; } if (this.instance.wtScrollbars.vertical.scrollHandler !== window) { offset.top = offset.top - WalkontableDom.prototype.offset(this.instance.wtScrollbars.vertical.scrollHandler).top; } clientWidth -= 20; clientHeight -= 20; if (outerWidth < clientWidth) { if (offset.left < scrollX) { this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left); } else if (offset.left + outerWidth > scrollX + clientWidth) { this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left - clientWidth + outerWidth); } } if (outerHeight < clientHeight) { if (offset.top < scrollY) { this.instance.wtScrollbars.vertical.setScrollPosition(offset.top); } else if (offset.top + outerHeight > scrollY + clientHeight) { this.instance.wtScrollbars.vertical.setScrollPosition(offset.top - clientHeight + outerHeight); } } return; } } if (coords[0] < 0 || coords[0] > totalRows - 1) { throw new Error('row ' + coords[0] + ' does not exist'); } else if (coords[1] < 0 || coords[1] > totalColumns - 1) { throw new Error('column ' + coords[1] + ' does not exist'); } if (coords[0] > lastVisibleRow) { // this.scrollVertical(coords[0] - lastVisibleRow + 1); this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); this.instance.wtTable.verticalRenderReverse = true; } else if (coords[0] === lastVisibleRow && this.instance.wtTable.rowStrategy.isLastIncomplete()) { // this.scrollVertical(coords[0] - lastVisibleRow + 1); this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); this.instance.wtTable.verticalRenderReverse = true; } else if (coords[0] - fixedRowsTop < offsetRow) { this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); } else { this.scrollVertical(0); //Craig's issue: remove row from the last scroll page should scroll viewport a row up if needed } if (this.instance.wtTable.isColumnBeforeViewport(coords[1])) { //scroll left this.instance.wtScrollbars.horizontal.scrollTo(coords[1] - fixedColumnsLeft); } else if (this.instance.wtTable.isColumnAfterViewport(coords[1]) || (this.instance.wtTable.getLastVisibleColumn() === coords[1] && !this.instance.wtTable.isLastColumnFullyVisible())) { //scroll right var sum = 0; for (var i = 0; i < fixedColumnsLeft; i++) { sum += this.instance.getSetting('columnWidth', i); } var scrollTo = coords[1]; sum += this.instance.getSetting('columnWidth', scrollTo); var available = this.instance.wtViewport.getViewportWidth(); if (sum < available) { var next = this.instance.getSetting('columnWidth', scrollTo - 1); while (sum + next <= available && scrollTo >= fixedColumnsLeft) { scrollTo--; sum += next; next = this.instance.getSetting('columnWidth', scrollTo - 1); } } this.instance.wtScrollbars.horizontal.scrollTo(scrollTo - fixedColumnsLeft); } /*else { //no scroll }*/ return this.instance; }; function WalkontableScrollbar() { } WalkontableScrollbar.prototype.init = function () { var that = this; //reference to instance this.$table = $(this.instance.wtTable.TABLE); //create elements this.slider = document.createElement('DIV'); this.sliderStyle = this.slider.style; this.sliderStyle.position = 'absolute'; this.sliderStyle.top = '0'; this.sliderStyle.left = '0'; this.sliderStyle.display = 'none'; this.slider.className = 'dragdealer ' + this.type; this.handle = document.createElement('DIV'); this.handleStyle = this.handle.style; this.handle.className = 'handle'; this.slider.appendChild(this.handle); this.container = this.instance.wtTable.holder; this.container.appendChild(this.slider); var firstRun = true; this.dragTimeout = null; var dragDelta; var dragRender = function () { that.onScroll(dragDelta); }; this.dragdealer = new Dragdealer(this.slider, { vertical: (this.type === 'vertical'), horizontal: (this.type === 'horizontal'), slide: false, speed: 100, animationCallback: function (x, y) { if (firstRun) { firstRun = false; return; } that.skipRefresh = true; dragDelta = that.type === 'vertical' ? y : x; if (that.dragTimeout === null) { that.dragTimeout = setInterval(dragRender, 100); dragRender(); } }, callback: function (x, y) { that.skipRefresh = false; clearInterval(that.dragTimeout); that.dragTimeout = null; dragDelta = that.type === 'vertical' ? y : x; that.onScroll(dragDelta); } }); this.skipRefresh = false; }; WalkontableScrollbar.prototype.onScroll = function (delta) { if (this.instance.drawn) { this.readSettings(); if (this.total > this.visibleCount) { var newOffset = Math.round(this.handlePosition * this.total / this.sliderSize); if (delta === 1) { if (this.type === 'vertical') { this.instance.scrollVertical(Infinity).draw(); } else { this.instance.scrollHorizontal(Infinity).draw(); } } else if (newOffset !== this.offset) { //is new offset different than old offset if (this.type === 'vertical') { this.instance.scrollVertical(newOffset - this.offset).draw(); } else { this.instance.scrollHorizontal(newOffset - this.offset).draw(); } } else { this.refresh(); } } } }; /** * Returns what part of the scroller should the handle take * @param viewportCount {Number} number of visible rows or columns * @param totalCount {Number} total number of rows or columns * @return {Number} 0..1 */ WalkontableScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) { if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) { return 1; } return 1 / totalCount; }; WalkontableScrollbar.prototype.prepare = function () { if (this.skipRefresh) { return; } var ratio = this.getHandleSizeRatio(this.visibleCount, this.total); if (((ratio === 1 || isNaN(ratio)) && this.scrollMode === 'auto') || this.scrollMode === 'none') { //isNaN is needed because ratio equals NaN when totalRows/totalColumns equals 0 this.visible = false; } else { this.visible = true; } }; WalkontableScrollbar.prototype.refresh = function () { if (this.skipRefresh) { return; } else if (!this.visible) { this.sliderStyle.display = 'none'; return; } var ratio , sliderSize , handleSize , handlePosition , visibleCount = this.visibleCount , tableWidth = this.instance.wtViewport.getWorkspaceWidth() , tableHeight = this.instance.wtViewport.getWorkspaceHeight(); if (tableWidth === Infinity) { tableWidth = this.instance.wtViewport.getWorkspaceActualWidth(); } if (tableHeight === Infinity) { tableHeight = this.instance.wtViewport.getWorkspaceActualHeight(); } if (this.type === 'vertical') { if (this.instance.wtTable.rowStrategy.isLastIncomplete()) { visibleCount--; } sliderSize = tableHeight - 2; //2 is sliders border-width this.sliderStyle.top = this.instance.wtDom.offset(this.$table[0]).top - this.instance.wtDom.offset(this.container).top + 'px'; this.sliderStyle.left = tableWidth - 1 + 'px'; //1 is sliders border-width this.sliderStyle.height = Math.max(sliderSize, 0) + 'px'; } else { //horizontal sliderSize = tableWidth - 2; //2 is sliders border-width this.sliderStyle.left = this.instance.wtDom.offset(this.$table[0]).left - this.instance.wtDom.offset(this.container).left + 'px'; this.sliderStyle.top = tableHeight - 1 + 'px'; //1 is sliders border-width this.sliderStyle.width = Math.max(sliderSize, 0) + 'px'; } ratio = this.getHandleSizeRatio(visibleCount, this.total); handleSize = Math.round(sliderSize * ratio); if (handleSize < 10) { handleSize = 15; } handlePosition = Math.floor(sliderSize * (this.offset / this.total)); if (handleSize + handlePosition > sliderSize) { handlePosition = sliderSize - handleSize; } if (this.type === 'vertical') { this.handleStyle.height = handleSize + 'px'; this.handleStyle.top = handlePosition + 'px'; } else { //horizontal this.handleStyle.width = handleSize + 'px'; this.handleStyle.left = handlePosition + 'px'; } this.sliderStyle.display = 'block'; }; WalkontableScrollbar.prototype.destroy = function () { clearInterval(this.dragdealer.interval); }; /// var WalkontableVerticalScrollbar = function (instance) { this.instance = instance; this.type = 'vertical'; this.init(); }; WalkontableVerticalScrollbar.prototype = new WalkontableScrollbar(); WalkontableVerticalScrollbar.prototype.scrollTo = function (cell) { this.instance.update('offsetRow', cell); }; WalkontableVerticalScrollbar.prototype.readSettings = function () { this.scrollMode = this.instance.getSetting('scrollV'); this.offset = this.instance.getSetting('offsetRow'); this.total = this.instance.getSetting('totalRows'); this.visibleCount = this.instance.wtTable.rowStrategy.countVisible(); if(this.visibleCount > 1 && this.instance.wtTable.rowStrategy.isLastIncomplete()) { this.visibleCount--; } this.handlePosition = parseInt(this.handleStyle.top, 10); this.sliderSize = parseInt(this.sliderStyle.height, 10); this.fixedCount = this.instance.getSetting('fixedRowsTop'); }; /// var WalkontableHorizontalScrollbar = function (instance) { this.instance = instance; this.type = 'horizontal'; this.init(); }; WalkontableHorizontalScrollbar.prototype = new WalkontableScrollbar(); WalkontableHorizontalScrollbar.prototype.scrollTo = function (cell) { this.instance.update('offsetColumn', cell); }; WalkontableHorizontalScrollbar.prototype.readSettings = function () { this.scrollMode = this.instance.getSetting('scrollH'); this.offset = this.instance.getSetting('offsetColumn'); this.total = this.instance.getSetting('totalColumns'); this.visibleCount = this.instance.wtTable.columnStrategy.countVisible(); if(this.visibleCount > 1 && this.instance.wtTable.columnStrategy.isLastIncomplete()) { this.visibleCount--; } this.handlePosition = parseInt(this.handleStyle.left, 10); this.sliderSize = parseInt(this.sliderStyle.width, 10); this.fixedCount = this.instance.getSetting('fixedColumnsLeft'); }; WalkontableHorizontalScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) { if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) { return 1; } return viewportCount / totalCount; }; function WalkontableCornerScrollbarNative(instance) { this.instance = instance; this.init(); this.clone = this.makeClone('corner'); } WalkontableCornerScrollbarNative.prototype = new WalkontableOverlay(); WalkontableCornerScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var top = Math.ceil(box.top, 10); var bottom = Math.ceil(box.bottom, 10); if (top < 0 && bottom > 0) { elem.style.top = '0'; } else { elem.style.top = top + 'px'; } var left = Math.ceil(box.left, 10); var right = Math.ceil(box.right, 10); if (left < 0 && right > 0) { elem.style.left = '0'; } else { elem.style.left = left + 'px'; } } else { box = this.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } elem.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px'; }; WalkontableCornerScrollbarNative.prototype.prepare = function () { }; WalkontableCornerScrollbarNative.prototype.refresh = function (selectionsOnly) { this.measureBefore = 0; this.measureAfter = 0; this.clone && this.clone.draw(selectionsOnly); }; WalkontableCornerScrollbarNative.prototype.getScrollPosition = function () { }; WalkontableCornerScrollbarNative.prototype.getLastCell = function () { }; WalkontableCornerScrollbarNative.prototype.applyToDOM = function () { }; WalkontableCornerScrollbarNative.prototype.scrollTo = function () { }; WalkontableCornerScrollbarNative.prototype.readWindowSize = function () { }; WalkontableCornerScrollbarNative.prototype.readSettings = function () { }; function WalkontableHorizontalScrollbarNative(instance) { this.instance = instance; this.type = 'horizontal'; this.cellSize = 50; this.init(); this.clone = this.makeClone('left'); } WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay(); //resetFixedPosition (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var left = Math.ceil(box.left, 10); var right = Math.ceil(box.right, 10); if (left < 0 && right > 0) { elem.style.left = '0'; } else { elem.style.left = left + 'px'; } } else { box = this.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } }; //react on movement of the other dimension scrollbar (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.react = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var overlayContainer = this.clone.wtTable.holder.parentNode; if (this.instance.wtScrollbars.vertical.scrollHandler === window) { var box = this.instance.wtTable.hider.getBoundingClientRect(); overlayContainer.style.top = Math.ceil(box.top, 10) + 'px'; overlayContainer.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 'px'; } else { this.clone.wtTable.holder.style.top = -(this.instance.wtScrollbars.vertical.windowScrollPosition - this.instance.wtScrollbars.vertical.measureBefore) + 'px'; overlayContainer.style.height = this.instance.wtViewport.getWorkspaceHeight() + 'px' } overlayContainer.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; //4 is for the box shadow }; WalkontableHorizontalScrollbarNative.prototype.prepare = function () { }; WalkontableHorizontalScrollbarNative.prototype.refresh = function (selectionsOnly) { this.measureBefore = 0; this.measureAfter = 0; this.clone && this.clone.draw(selectionsOnly); }; WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function () { if (this.scrollHandler === window) { return this.scrollHandler.scrollX; } else { return this.scrollHandler.scrollLeft; } }; WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function (pos) { this.scrollHandler.scrollLeft = pos; }; WalkontableHorizontalScrollbarNative.prototype.onScroll = function () { WalkontableOverlay.prototype.onScroll.apply(this, arguments); this.instance.getSetting('onScrollHorizontally'); }; WalkontableHorizontalScrollbarNative.prototype.getLastCell = function () { return this.instance.wtTable.getLastVisibleColumn(); }; //applyToDOM (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () { this.fixedContainer.style.paddingLeft = this.measureBefore + 'px'; this.fixedContainer.style.paddingRight = this.measureAfter + 'px'; }; WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (cell) { this.$scrollHandler.scrollLeft(this.tableParentOffset + cell * this.cellSize); }; //readWindowSize (in future merge it with this.prepare?) WalkontableHorizontalScrollbarNative.prototype.readWindowSize = function () { if (this.scrollHandler === window) { this.windowSize = document.documentElement.clientWidth; this.tableParentOffset = this.instance.wtTable.holderOffset.left; } else { this.windowSize = WalkontableDom.prototype.outerWidth(this.scrollHandler); this.tableParentOffset = 0; } this.windowScrollPosition = this.getScrollPosition(); }; //readSettings (in future merge it with this.prepare?) WalkontableHorizontalScrollbarNative.prototype.readSettings = function () { this.offset = this.instance.getSetting('offsetColumn'); this.total = this.instance.getSetting('totalColumns'); }; function WalkontableVerticalScrollbarNative(instance) { this.instance = instance; this.type = 'vertical'; this.cellSize = 23; this.init(); this.clone = this.makeClone('top'); } WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay(); //resetFixedPosition (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var top = Math.ceil(box.top, 10); var bottom = Math.ceil(box.bottom, 10); if (top < 0 && bottom > 0) { elem.style.top = '0'; } else { elem.style.top = top + 'px'; } } else { box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } if (this.instance.wtScrollbars.horizontal.scrollHandler === window) { elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px'; } else { elem.style.width = WalkontableDom.prototype.outerWidth(this.instance.wtTable.holder.parentNode) + 'px'; } elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px'; }; //react on movement of the other dimension scrollbar (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.react = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) { var elem = this.clone.wtTable.holder.parentNode; elem.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px'; } }; WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () { if (this.scrollHandler === window) { return this.scrollHandler.scrollY; } else { return this.scrollHandler.scrollTop; } }; WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) { this.scrollHandler.scrollTop = pos; }; WalkontableVerticalScrollbarNative.prototype.onScroll = function (forcePosition) { WalkontableOverlay.prototype.onScroll.apply(this, arguments); var scrollDelta; var newOffset = 0; if (1 == 1 || this.windowScrollPosition > this.tableParentOffset) { scrollDelta = this.windowScrollPosition - this.tableParentOffset; partialOffset = 0; if (scrollDelta > 0) { var sum = 0; var last; for (var i = 0; i < this.total; i++) { last = this.instance.getSetting('rowHeight', i); sum += last; if (sum > scrollDelta) { break; } } if (this.offset > 0) { partialOffset = (sum - scrollDelta); } newOffset = i; newOffset = Math.min(newOffset, this.total); } } this.curOuts = newOffset > this.maxOuts ? this.maxOuts : newOffset; newOffset -= this.curOuts; this.instance.update('offsetRow', newOffset); this.readSettings(); //read new offset this.instance.draw(); this.instance.getSetting('onScrollVertically'); }; WalkontableVerticalScrollbarNative.prototype.getLastCell = function () { return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1; }; var partialOffset = 0; WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) { var sum = 0; while (from < length) { sum += this.instance.getSetting('rowHeight', from); from++; } return sum; }; //applyToDOM (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () { var headerSize = this.instance.wtViewport.getColumnHeaderHeight(); this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow this.fixed.style.top = this.measureBefore + 'px'; this.fixed.style.bottom = ''; }; WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) { var newY = this.tableParentOffset + cell * this.cellSize; this.$scrollHandler.scrollTop(newY); this.onScroll(newY); }; //readWindowSize (in future merge it with this.prepare?) WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () { if (this.scrollHandler === window) { this.windowSize = document.documentElement.clientHeight; this.tableParentOffset = this.instance.wtTable.holderOffset.top; } else { //this.windowSize = WalkontableDom.prototype.outerHeight(this.scrollHandler); this.windowSize = this.scrollHandler.clientHeight; //returns height without DIV scrollbar this.tableParentOffset = 0; } this.windowScrollPosition = this.getScrollPosition(); }; //readSettings (in future merge it with this.prepare?) WalkontableVerticalScrollbarNative.prototype.readSettings = function () { this.offset = this.instance.getSetting('offsetRow'); this.total = this.instance.getSetting('totalRows'); }; function WalkontableScrollbars(instance) { this.instance = instance; if (instance.getSetting('nativeScrollbars')) { instance.update('scrollbarWidth', instance.wtDom.getScrollbarWidth()); instance.update('scrollbarHeight', instance.wtDom.getScrollbarWidth()); this.vertical = new WalkontableVerticalScrollbarNative(instance); this.horizontal = new WalkontableHorizontalScrollbarNative(instance); this.corner = new WalkontableCornerScrollbarNative(instance); if (instance.getSetting('debug')) { this.debug = new WalkontableDebugOverlay(instance); } this.registerListeners(); } else { this.vertical = new WalkontableVerticalScrollbar(instance); this.horizontal = new WalkontableHorizontalScrollbar(instance); } } WalkontableScrollbars.prototype.registerListeners = function () { var that = this; var oldVerticalScrollPosition , oldHorizontalScrollPosition , oldBoxTop , oldBoxLeft , oldBoxWidth , oldBoxHeight; function refreshAll() { if (!that.instance.wtTable.holder.parentNode) { //Walkontable was detached from DOM, but this handler was not removed that.destroy(); return; } that.vertical.windowScrollPosition = that.vertical.getScrollPosition(); that.horizontal.windowScrollPosition = that.horizontal.getScrollPosition(); that.box = that.instance.wtTable.hider.getBoundingClientRect(); if((that.box.width !== oldBoxWidth || that.box.height !== oldBoxHeight) && that.instance.rowHeightCache) { //that.instance.rowHeightCache.length = 0; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table oldBoxWidth = that.box.width; oldBoxHeight = that.box.height; that.instance.draw(); } if (that.vertical.windowScrollPosition !== oldVerticalScrollPosition || that.horizontal.windowScrollPosition !== oldHorizontalScrollPosition || that.box.top !== oldBoxTop || that.box.left !== oldBoxLeft) { that.vertical.onScroll(); that.horizontal.onScroll(); //it's done here to make sure that all onScroll's are executed before changing styles that.vertical.react(); that.horizontal.react(); //it's done here to make sure that all onScroll's are executed before changing styles oldVerticalScrollPosition = that.vertical.windowScrollPosition; oldHorizontalScrollPosition = that.horizontal.windowScrollPosition; oldBoxTop = that.box.top; oldBoxLeft = that.box.left; } } var $window = $(window); this.vertical.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll); if (this.vertical.scrollHandler !== this.horizontal.scrollHandler) { this.horizontal.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll); } if (this.vertical.scrollHandler !== window && this.horizontal.scrollHandler !== window) { $window.on('scroll.' + this.instance.guid, refreshAll); } $window.on('load.' + this.instance.guid, refreshAll); $window.on('resize.' + this.instance.guid, refreshAll); $(document).on('ready.' + this.instance.guid, refreshAll); setInterval(refreshAll, 100); //Marcin - only idea I have to reposition scrollbars on CSS change of the container (container was moved using some styles after page was loaded) }; WalkontableScrollbars.prototype.destroy = function () { this.vertical && this.vertical.destroy(); this.horizontal && this.horizontal.destroy(); }; WalkontableScrollbars.prototype.refresh = function (selectionsOnly) { this.horizontal && this.horizontal.readSettings(); this.vertical && this.vertical.readSettings(); this.horizontal && this.horizontal.prepare(); this.vertical && this.vertical.prepare(); this.horizontal && this.horizontal.refresh(selectionsOnly); this.vertical && this.vertical.refresh(selectionsOnly); this.corner && this.corner.refresh(selectionsOnly); this.debug && this.debug.refresh(selectionsOnly); }; function WalkontableSelection(instance, settings) { this.instance = instance; this.settings = settings; this.selected = []; if (settings.border) { this.border = new WalkontableBorder(instance, settings); } } WalkontableSelection.prototype.add = function (coords) { this.selected.push(coords); }; WalkontableSelection.prototype.clear = function () { this.selected.length = 0; //http://jsperf.com/clear-arrayxxx }; /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @returns {Object} */ WalkontableSelection.prototype.getCorners = function () { var minRow , minColumn , maxRow , maxColumn , i , ilen = this.selected.length; if (ilen > 0) { minRow = maxRow = this.selected[0][0]; minColumn = maxColumn = this.selected[0][1]; if (ilen > 1) { for (i = 1; i < ilen; i++) { if (this.selected[i][0] < minRow) { minRow = this.selected[i][0]; } else if (this.selected[i][0] > maxRow) { maxRow = this.selected[i][0]; } if (this.selected[i][1] < minColumn) { minColumn = this.selected[i][1]; } else if (this.selected[i][1] > maxColumn) { maxColumn = this.selected[i][1]; } } } } return [minRow, minColumn, maxRow, maxColumn]; }; WalkontableSelection.prototype.draw = function () { var corners, r, c, source_r, source_c; var visibleRows = this.instance.wtTable.rowStrategy.countVisible() , visibleColumns = this.instance.wtTable.columnStrategy.countVisible(); if (this.selected.length) { corners = this.getCorners(); for (r = 0; r < visibleRows; r++) { for (c = 0; c < visibleColumns; c++) { source_r = this.instance.wtTable.rowFilter.visibleToSource(r); source_c = this.instance.wtTable.columnFilter.visibleToSource(c); if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) { //selected cell this.instance.wtTable.currentCellCache.add(r, c, this.settings.className); } else if (source_r >= corners[0] && source_r <= corners[2]) { //selection is in this row this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName); } else if (source_c >= corners[1] && source_c <= corners[3]) { //selection is in this column this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName); } } } this.border && this.border.appear(corners); //warning! border.appear modifies corners! } else { this.border && this.border.disappear(); } }; function WalkontableSettings(instance, settings) { var that = this; this.instance = instance; //default settings. void 0 means it is required, null means it can be empty this.defaults = { table: void 0, debug: false, //shows WalkontableDebugOverlay //presentation mode scrollH: 'auto', //values: scroll (always show scrollbar), auto (show scrollbar if table does not fit in the container), none (never show scrollbar) scrollV: 'auto', //values: see above nativeScrollbars: false, //values: false (dragdealer), true (native) stretchH: 'hybrid', //values: hybrid, all, last, none currentRowClassName: null, currentColumnClassName: null, //data source data: void 0, offsetRow: 0, offsetColumn: 0, fixedColumnsLeft: 0, fixedRowsTop: 0, rowHeaders: function () { return [] }, //this must be array of functions: [function (row, TH) {}] columnHeaders: function () { return [] }, //this must be array of functions: [function (column, TH) {}] totalRows: void 0, totalColumns: void 0, width: null, height: null, cellRenderer: function (row, column, TD) { var cellData = that.getSetting('data', row, column); that.instance.wtDom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData); }, columnWidth: 50, selections: null, hideBorderOnMouseDownOver: false, //callbacks onCellMouseDown: null, onCellMouseOver: null, // onCellMouseOut: null, onCellDblClick: null, onCellCornerMouseDown: null, onCellCornerDblClick: null, beforeDraw: null, onDraw: null, onScrollVertically: null, onScrollHorizontally: null, //constants scrollbarWidth: 10, scrollbarHeight: 10 }; //reference to settings this.settings = {}; for (var i in this.defaults) { if (this.defaults.hasOwnProperty(i)) { if (settings[i] !== void 0) { this.settings[i] = settings[i]; } else if (this.defaults[i] === void 0) { throw new Error('A required setting "' + i + '" was not provided'); } else { this.settings[i] = this.defaults[i]; } } } } /** * generic methods */ WalkontableSettings.prototype.update = function (settings, value) { if (value === void 0) { //settings is object for (var i in settings) { if (settings.hasOwnProperty(i)) { this.settings[i] = settings[i]; } } } else { //if value is defined then settings is the key this.settings[settings] = value; } return this.instance; }; WalkontableSettings.prototype.getSetting = function (key, param1, param2, param3) { if (this[key]) { return this[key](param1, param2, param3); } else { return this._getSetting(key, param1, param2, param3); } }; WalkontableSettings.prototype._getSetting = function (key, param1, param2, param3) { if (typeof this.settings[key] === 'function') { return this.settings[key](param1, param2, param3); } else if (param1 !== void 0 && Object.prototype.toString.call(this.settings[key]) === '[object Array]') { return this.settings[key][param1]; } else { return this.settings[key]; } }; WalkontableSettings.prototype.has = function (key) { return !!this.settings[key] }; /** * specific methods */ WalkontableSettings.prototype.rowHeight = function (row, TD) { if (!this.instance.rowHeightCache) { this.instance.rowHeightCache = []; //hack. This cache is being invalidated in WOT core.js } if (this.instance.rowHeightCache[row] === void 0) { var size = 23; //guess if (TD) { size = this.instance.wtDom.outerHeight(TD); //measure this.instance.rowHeightCache[row] = size; //cache only something we measured } return size; } else { return this.instance.rowHeightCache[row]; } }; function WalkontableTable(instance, table) { //reference to instance this.instance = instance; this.TABLE = table; this.wtDom = this.instance.wtDom; this.wtDom.removeTextNodes(this.TABLE); //wtSpreader var parent = this.TABLE.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var spreader = document.createElement('DIV'); spreader.className = 'wtSpreader'; if (parent) { parent.insertBefore(spreader, this.TABLE); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } spreader.appendChild(this.TABLE); } this.spreader = this.TABLE.parentNode; //wtHider parent = this.spreader.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var hider = document.createElement('DIV'); hider.className = 'wtHider'; if (parent) { parent.insertBefore(hider, this.spreader); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } hider.appendChild(this.spreader); } this.hider = this.spreader.parentNode; this.hiderStyle = this.hider.style; this.hiderStyle.position = 'relative'; //wtHolder parent = this.hider.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var holder = document.createElement('DIV'); holder.style.position = 'relative'; holder.className = 'wtHolder'; if (parent) { parent.insertBefore(holder, this.hider); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } holder.appendChild(this.hider); } this.holder = this.hider.parentNode; //bootstrap from settings this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0]; if (!this.TBODY) { this.TBODY = document.createElement('TBODY'); this.TABLE.appendChild(this.TBODY); } this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0]; if (!this.THEAD) { this.THEAD = document.createElement('THEAD'); this.TABLE.insertBefore(this.THEAD, this.TBODY); } this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0]; if (!this.COLGROUP) { this.COLGROUP = document.createElement('COLGROUP'); this.TABLE.insertBefore(this.COLGROUP, this.THEAD); } if (this.instance.getSetting('columnHeaders').length) { if (!this.THEAD.childNodes.length) { var TR = document.createElement('TR'); this.THEAD.appendChild(TR); } } this.colgroupChildrenLength = this.COLGROUP.childNodes.length; this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0; this.tbodyChildrenLength = this.TBODY.childNodes.length; this.oldCellCache = new WalkontableClassNameCache(); this.currentCellCache = new WalkontableClassNameCache(); this.rowFilter = new WalkontableRowFilter(); this.columnFilter = new WalkontableColumnFilter(); this.verticalRenderReverse = false; } WalkontableTable.prototype.refreshHiderDimensions = function () { var height = this.instance.wtViewport.getWorkspaceHeight(); var width = this.instance.wtViewport.getWorkspaceWidth(); var spreaderStyle = this.spreader.style; if ((height !== Infinity || width !== Infinity) && !this.instance.getSetting('nativeScrollbars')) { if (height === Infinity) { height = this.instance.wtViewport.getWorkspaceActualHeight(); } if (width === Infinity) { width = this.instance.wtViewport.getWorkspaceActualWidth(); } this.hiderStyle.overflow = 'hidden'; spreaderStyle.position = 'absolute'; spreaderStyle.top = '0'; spreaderStyle.left = '0'; if (!this.instance.getSetting('nativeScrollbars')) { spreaderStyle.height = '4000px'; spreaderStyle.width = '4000px'; } if (height < 0) { //this happens with WalkontableOverlay and causes "Invalid argument" error in IE8 height = 0; } this.hiderStyle.height = height + 'px'; this.hiderStyle.width = width + 'px'; } else { spreaderStyle.position = 'relative'; spreaderStyle.width = 'auto'; spreaderStyle.height = 'auto'; } }; WalkontableTable.prototype.refreshStretching = function () { if (this.instance.cloneSource) { return; } var instance = this.instance , stretchH = instance.getSetting('stretchH') , totalRows = instance.getSetting('totalRows') , totalColumns = instance.getSetting('totalColumns') , offsetColumn = instance.getSetting('offsetColumn'); var containerWidthFn = function (cacheWidth) { var viewportWidth = that.instance.wtViewport.getViewportWidth(cacheWidth); if (viewportWidth < cacheWidth && that.instance.getSetting('nativeScrollbars')) { return Infinity; //disable stretching when viewport is bigger than sum of the cell widths } return viewportWidth; }; var that = this; var columnWidthFn = function (i) { var source_c = that.columnFilter.visibleToSource(i); if (source_c < totalColumns) { return instance.getSetting('columnWidth', source_c); } }; if (stretchH === 'hybrid') { if (offsetColumn > 0) { stretchH = 'last'; } else { stretchH = 'none'; } } var containerHeightFn = function (cacheHeight) { if (that.instance.getSetting('nativeScrollbars')) { if (that.instance.cloneOverlay instanceof WalkontableDebugOverlay) { return Infinity; } else { return 2 * that.instance.wtViewport.getViewportHeight(cacheHeight); } } return that.instance.wtViewport.getViewportHeight(cacheHeight); }; var rowHeightFn = function (i, TD) { if (that.instance.getSetting('nativeScrollbars')) { return 20; } var source_r = that.rowFilter.visibleToSource(i); if (source_r < totalRows) { if (that.verticalRenderReverse && i === 0) { return that.instance.getSetting('rowHeight', source_r, TD) - 1; } else { return that.instance.getSetting('rowHeight', source_r, TD); } } }; this.columnStrategy = new WalkontableColumnStrategy(instance, containerWidthFn, columnWidthFn, stretchH); this.rowStrategy = new WalkontableRowStrategy(instance, containerHeightFn, rowHeightFn); }; WalkontableTable.prototype.adjustAvailableNodes = function () { var displayTds , rowHeaders = this.instance.getSetting('rowHeaders') , displayThs = rowHeaders.length , columnHeaders = this.instance.getSetting('columnHeaders') , TR , TD , c; //adjust COLGROUP while (this.colgroupChildrenLength < displayThs) { this.COLGROUP.appendChild(document.createElement('COL')); this.colgroupChildrenLength++; } this.refreshStretching(); //actually it is wrong position because it assumes rowHeader would be always 50px wide (because we measure before it is filled with text). TODO: debug if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) { displayTds = this.instance.getSetting('fixedColumnsLeft'); } else { displayTds = this.columnStrategy.cellCount; } //adjust COLGROUP while (this.colgroupChildrenLength < displayTds + displayThs) { this.COLGROUP.appendChild(document.createElement('COL')); this.colgroupChildrenLength++; } while (this.colgroupChildrenLength > displayTds + displayThs) { this.COLGROUP.removeChild(this.COLGROUP.lastChild); this.colgroupChildrenLength--; } //adjust THEAD TR = this.THEAD.firstChild; if (columnHeaders.length) { if (!TR) { TR = document.createElement('TR'); this.THEAD.appendChild(TR); } this.theadChildrenLength = TR.childNodes.length; while (this.theadChildrenLength < displayTds + displayThs) { TR.appendChild(document.createElement('TH')); this.theadChildrenLength++; } while (this.theadChildrenLength > displayTds + displayThs) { TR.removeChild(TR.lastChild); this.theadChildrenLength--; } } else if (TR) { this.wtDom.empty(TR); } //draw COLGROUP for (c = 0; c < this.colgroupChildrenLength; c++) { if (c < displayThs) { this.wtDom.addClass(this.COLGROUP.childNodes[c], 'rowHeader'); } else { this.wtDom.removeClass(this.COLGROUP.childNodes[c], 'rowHeader'); } } //draw THEAD if (columnHeaders.length) { TR = this.THEAD.firstChild; if (displayThs) { TD = TR.firstChild; //actually it is TH but let's reuse single variable for (c = 0; c < displayThs; c++) { rowHeaders[c](-displayThs + c, TD); TD = TD.nextSibling; } } } for (c = 0; c < displayTds; c++) { if (columnHeaders.length) { columnHeaders[0](this.columnFilter.visibleToSource(c), TR.childNodes[displayThs + c]); } } }; WalkontableTable.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--; } }; WalkontableTable.prototype.draw = function (selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { this.verticalRenderReverse = false; //this is only supported in dragdealer mode, not in native } this.rowFilter.readSettings(this.instance); this.columnFilter.readSettings(this.instance); if (!selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { if (this.instance.cloneSource) { this.tableOffset = this.instance.cloneSource.wtTable.tableOffset; } else { this.holderOffset = this.wtDom.offset(this.holder); this.tableOffset = this.wtDom.offset(this.TABLE); this.instance.wtScrollbars.vertical.readWindowSize(); this.instance.wtScrollbars.horizontal.readWindowSize(); this.instance.wtViewport.resetSettings(); } } else { this.tableOffset = this.wtDom.offset(this.TABLE); this.instance.wtViewport.resetSettings(); } this._doDraw(); } else { this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(true); } this.refreshPositions(selectionsOnly); if (!selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { if (!this.instance.cloneSource) { this.instance.wtScrollbars.vertical.resetFixedPosition(); this.instance.wtScrollbars.horizontal.resetFixedPosition(); this.instance.wtScrollbars.corner.resetFixedPosition(); this.instance.wtScrollbars.debug && this.instance.wtScrollbars.debug.resetFixedPosition(); } } } this.instance.drawn = true; return this; }; WalkontableTable.prototype._doDraw = function () { var r = 0 , source_r , c , source_c , offsetRow = this.instance.getSetting('offsetRow') , totalRows = this.instance.getSetting('totalRows') , totalColumns = this.instance.getSetting('totalColumns') , displayTds , rowHeaders = this.instance.getSetting('rowHeaders') , displayThs = rowHeaders.length , TR , TD , TH , adjusted = false , workspaceWidth , mustBeInViewport , res; if (this.verticalRenderReverse) { mustBeInViewport = offsetRow; } var noPartial = false; if (this.verticalRenderReverse) { if (offsetRow === totalRows - this.rowFilter.fixedCount - 1) { noPartial = true; } else { this.instance.update('offsetRow', offsetRow + 1); //if we are scrolling reverse this.rowFilter.readSettings(this.instance); } } if (this.instance.cloneSource) { this.columnStrategy = this.instance.cloneSource.wtTable.columnStrategy; this.rowStrategy = this.instance.cloneSource.wtTable.rowStrategy; } //draw TBODY if (totalColumns > 0) { source_r = this.rowFilter.visibleToSource(r); var fixedRowsTop = this.instance.getSetting('fixedRowsTop'); var cloneLimit; if (this.instance.cloneSource) { //must be run after adjustAvailableNodes because otherwise this.rowStrategy is not yet defined if (this.instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) { cloneLimit = fixedRowsTop; } else if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative) { cloneLimit = this.rowStrategy.countVisible(); } //else if WalkontableDebugOverlay do nothing. No cloneLimit means render ALL rows } this.adjustAvailableNodes(); adjusted = true; if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) { displayTds = this.instance.getSetting('fixedColumnsLeft'); } else { displayTds = this.columnStrategy.cellCount; } if (!this.instance.cloneSource) { workspaceWidth = this.instance.wtViewport.getWorkspaceWidth(); this.columnStrategy.stretch(); } for (c = 0; c < displayTds; c++) { this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px'; } while (source_r < totalRows && source_r >= 0) { if (r > 1000) { throw new Error('Security brake: Too much TRs. Please define height for your table, which will enforce scrollbars.'); } if (cloneLimit !== void 0 && r === cloneLimit) { break; //we have as much rows as needed for this clone } if (r >= this.tbodyChildrenLength || (this.verticalRenderReverse && r >= this.rowFilter.fixedCount)) { TR = document.createElement('TR'); for (c = 0; c < displayThs; c++) { TR.appendChild(document.createElement('TH')); } if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) { this.TBODY.insertBefore(TR, this.TBODY.childNodes[this.rowFilter.fixedCount] || this.TBODY.firstChild); } else { this.TBODY.appendChild(TR); } this.tbodyChildrenLength++; } else if (r === 0) { TR = this.TBODY.firstChild; } else { TR = TR.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } //TH TH = TR.firstChild; for (c = 0; c < displayThs; c++) { //If the number of row headers increased we need to replace TD with TH if (TH.nodeName == 'TD') { TD = TH; TH = document.createElement('TH'); TR.insertBefore(TH, TD); TR.removeChild(TD); } rowHeaders[c](source_r, TH); //actually TH TH = TH.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } this.adjustColumns(TR, displayTds + displayThs); for (c = 0; c < displayTds; c++) { source_c = this.columnFilter.visibleToSource(c); if (c === 0) { TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(source_c)]; } else { TD = TD.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } //If the number of headers has been reduced, we need to replace excess TH with TD if (TD.nodeName == 'TH') { TH = TD; TD = document.createElement('TD'); TR.insertBefore(TD, TH); TR.removeChild(TH); } TD.className = ''; TD.removeAttribute('style'); this.instance.getSetting('cellRenderer', source_r, source_c, TD); } offsetRow = this.instance.getSetting('offsetRow'); //refresh the value //after last column is rendered, check if last cell is fully displayed if (this.verticalRenderReverse && noPartial) { if (-this.wtDom.outerHeight(TR.firstChild) < this.rowStrategy.remainingSize) { this.TBODY.removeChild(TR); this.instance.update('offsetRow', offsetRow + 1); this.tbodyChildrenLength--; this.rowFilter.readSettings(this.instance); break; } else if (!this.instance.cloneSource) { res = this.rowStrategy.add(r, TD, this.verticalRenderReverse); if (res === false) { this.rowStrategy.removeOutstanding(); } } } else if (!this.instance.cloneSource) { res = this.rowStrategy.add(r, TD, this.verticalRenderReverse); if (res === false) { if (!this.instance.getSetting('nativeScrollbars')) { this.rowStrategy.removeOutstanding(); } } if (this.rowStrategy.isLastIncomplete()) { if (this.verticalRenderReverse && !this.isRowInViewport(mustBeInViewport)) { //we failed because one of the cells was by far too large. Recover by rendering from top this.verticalRenderReverse = false; this.instance.update('offsetRow', mustBeInViewport); this.draw(); return; } break; } } if (this.instance.getSetting('nativeScrollbars')) { if (this.instance.cloneSource) { TR.style.height = this.instance.getSetting('rowHeight', source_r) + 'px'; //if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is the way to make sure that the overlay will has same row height } else { this.instance.getSetting('rowHeight', source_r, TD); //this trick saves rowHeight in rowHeightCache. It is then read in WalkontableVerticalScrollbarNative.prototype.sumCellSizes and reset in Walkontable constructor } } if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) { if (offsetRow === 0) { break; } this.instance.update('offsetRow', offsetRow - 1); this.rowFilter.readSettings(this.instance); } else { r++; } source_r = this.rowFilter.visibleToSource(r); } } if (!adjusted) { this.adjustAvailableNodes(); } if (!(this.instance.cloneOverlay instanceof WalkontableDebugOverlay)) { r = this.rowStrategy.countVisible(); while (this.tbodyChildrenLength > r) { this.TBODY.removeChild(this.TBODY.lastChild); this.tbodyChildrenLength--; } } this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(false); if (!this.instance.cloneSource) { if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) { //workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching this.columnStrategy.stretch(); for (c = 0; c < this.columnStrategy.cellCount; c++) { this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px'; } } } this.verticalRenderReverse = false; }; WalkontableTable.prototype.refreshPositions = function (selectionsOnly) { this.refreshHiderDimensions(); this.refreshSelections(selectionsOnly); }; WalkontableTable.prototype.refreshSelections = function (selectionsOnly) { var vr , r , vc , c , s , slen , classNames = [] , visibleRows = this.rowStrategy.countVisible() , visibleColumns = this.columnStrategy.countVisible(); this.oldCellCache = this.currentCellCache; this.currentCellCache = new WalkontableClassNameCache(); if (this.instance.selections) { for (r in this.instance.selections) { if (this.instance.selections.hasOwnProperty(r)) { this.instance.selections[r].draw(); if (this.instance.selections[r].settings.className) { classNames.push(this.instance.selections[r].settings.className); } if (this.instance.selections[r].settings.highlightRowClassName) { classNames.push(this.instance.selections[r].settings.highlightRowClassName); } if (this.instance.selections[r].settings.highlightColumnClassName) { classNames.push(this.instance.selections[r].settings.highlightColumnClassName); } } } } slen = classNames.length; for (vr = 0; vr < visibleRows; vr++) { for (vc = 0; vc < visibleColumns; vc++) { r = this.rowFilter.visibleToSource(vr); c = this.columnFilter.visibleToSource(vc); for (s = 0; s < slen; s++) { if (this.currentCellCache.test(vr, vc, classNames[s])) { this.wtDom.addClass(this.getCell([r, c]), classNames[s]); } else if (selectionsOnly && this.oldCellCache.test(vr, vc, classNames[s])) { this.wtDom.removeClass(this.getCell([r, c]), classNames[s]); } } } } }; /** * getCell * @param {Array} coords * @return {Object} HTMLElement on success or {Number} one of the exit codes on error: * -1 row before viewport * -2 row after viewport * -3 column before viewport * -4 column after viewport * */ WalkontableTable.prototype.getCell = function (coords) { if (this.isRowBeforeViewport(coords[0])) { return -1; //row before viewport } else if (this.isRowAfterViewport(coords[0])) { return -2; //row after viewport } else { if (this.isColumnBeforeViewport(coords[1])) { return -3; //column before viewport } else if (this.isColumnAfterViewport(coords[1])) { return -4; //column after viewport } else { return this.TBODY.childNodes[this.rowFilter.sourceToVisible(coords[0])].childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords[1])]; } } }; WalkontableTable.prototype.getCoords = function (TD) { return [ this.rowFilter.visibleToSource(this.wtDom.index(TD.parentNode)), this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex) ]; }; //returns -1 if no row is visible WalkontableTable.prototype.getLastVisibleRow = function () { return this.rowFilter.visibleToSource(this.rowStrategy.cellCount - 1); }; //returns -1 if no column is visible WalkontableTable.prototype.getLastVisibleColumn = function () { return this.columnFilter.visibleToSource(this.columnStrategy.cellCount - 1); }; WalkontableTable.prototype.isRowBeforeViewport = function (r) { return (this.rowFilter.sourceToVisible(r) < this.rowFilter.fixedCount && r >= this.rowFilter.fixedCount); }; WalkontableTable.prototype.isRowAfterViewport = function (r) { return (r > this.getLastVisibleRow()); }; WalkontableTable.prototype.isColumnBeforeViewport = function (c) { return (this.columnFilter.sourceToVisible(c) < this.columnFilter.fixedCount && c >= this.columnFilter.fixedCount); }; WalkontableTable.prototype.isColumnAfterViewport = function (c) { return (c > this.getLastVisibleColumn()); }; WalkontableTable.prototype.isRowInViewport = function (r) { return (!this.isRowBeforeViewport(r) && !this.isRowAfterViewport(r)); }; WalkontableTable.prototype.isColumnInViewport = function (c) { return (!this.isColumnBeforeViewport(c) && !this.isColumnAfterViewport(c)); }; WalkontableTable.prototype.isLastRowFullyVisible = function () { return (this.getLastVisibleRow() === this.instance.getSetting('totalRows') - 1 && !this.rowStrategy.isLastIncomplete()); }; WalkontableTable.prototype.isLastColumnFullyVisible = function () { return (this.getLastVisibleColumn() === this.instance.getSetting('totalColumns') - 1 && !this.columnStrategy.isLastIncomplete()); }; function WalkontableViewport(instance) { this.instance = instance; this.resetSettings(); if (this.instance.getSetting('nativeScrollbars')) { var that = this; $(window).on('resize', function () { that.clientHeight = that.getWorkspaceHeight(); }); } } /*WalkontableViewport.prototype.isInSightVertical = function () { //is table outside viewport bottom edge if (tableTop > windowHeight + scrollTop) { return -1; } //is table outside viewport top edge else if (scrollTop > tableTop + tableFakeHeight) { return -2; } //table is in viewport but how much exactly? else { } };*/ //used by scrollbar WalkontableViewport.prototype.getWorkspaceHeight = function (proposedHeight) { if (this.instance.getSetting('nativeScrollbars')) { return this.instance.wtScrollbars.vertical.windowSize; } var height = this.instance.getSetting('height'); if (height === Infinity || height === void 0 || height === null || height < 1) { if (this.instance.wtScrollbars.vertical instanceof WalkontableOverlay) { height = this.instance.wtScrollbars.vertical.availableSize(); } else { height = Infinity; } } if (height !== Infinity) { if (proposedHeight >= height) { height -= this.instance.getSetting('scrollbarHeight'); } else if (this.instance.wtScrollbars.horizontal.visible) { height -= this.instance.getSetting('scrollbarHeight'); } } return height; }; WalkontableViewport.prototype.getWorkspaceWidth = function (proposedWidth) { var width = this.instance.getSetting('width'); if (width === Infinity || width === void 0 || width === null || width < 1) { if (this.instance.wtScrollbars.horizontal instanceof WalkontableOverlay) { width = this.instance.wtScrollbars.horizontal.availableSize(); } else { width = Infinity; } } if (width !== Infinity) { if (proposedWidth >= width) { width -= this.instance.getSetting('scrollbarWidth'); } else if (this.instance.wtScrollbars.vertical.visible) { width -= this.instance.getSetting('scrollbarWidth'); } } return width; }; WalkontableViewport.prototype.getWorkspaceActualHeight = function () { return this.instance.wtDom.outerHeight(this.instance.wtTable.TABLE); }; WalkontableViewport.prototype.getWorkspaceActualWidth = function () { return this.instance.wtDom.outerWidth(this.instance.wtTable.TABLE) || this.instance.wtDom.outerWidth(this.instance.wtTable.TBODY) || this.instance.wtDom.outerWidth(this.instance.wtTable.THEAD); //IE8 reports 0 as <table> offsetWidth; }; WalkontableViewport.prototype.getColumnHeaderHeight = function () { if (isNaN(this.columnHeaderHeight)) { var cellOffset = this.instance.wtDom.offset(this.instance.wtTable.TBODY) , tableOffset = this.instance.wtTable.tableOffset; this.columnHeaderHeight = cellOffset.top - tableOffset.top; } return this.columnHeaderHeight; }; WalkontableViewport.prototype.getViewportHeight = function (proposedHeight) { var containerHeight = this.getWorkspaceHeight(proposedHeight); if (containerHeight === Infinity) { return containerHeight; } var columnHeaderHeight = this.getColumnHeaderHeight(); if (columnHeaderHeight > 0) { return containerHeight - columnHeaderHeight; } else { 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 += this.instance.wtDom.outerWidth(TH); TH = TH.nextSibling; } else { this.rowHeaderWidth += 50; //yes this is a cheat but it worked like that before, just taking assumption from CSS instead of measuring. TODO: proper fix } } } else { this.rowHeaderWidth = 0; } } return this.rowHeaderWidth; }; WalkontableViewport.prototype.getViewportWidth = function (proposedWidth) { var containerWidth = this.getWorkspaceWidth(proposedWidth); if (containerWidth === Infinity) { return containerWidth; } var rowHeaderWidth = this.getRowHeaderWidth(); if (rowHeaderWidth > 0) { return containerWidth - rowHeaderWidth; } else { return containerWidth; } }; WalkontableViewport.prototype.resetSettings = function () { this.rowHeaderWidth = NaN; this.columnHeaderHeight = NaN; }; function WalkontableWheel(instance) { if (instance.getSetting('nativeScrollbars')) { return; } //spreader === instance.wtTable.TABLE.parentNode $(instance.wtTable.spreader).on('mousewheel', function (event, delta, deltaX, deltaY) { if (!deltaX && !deltaY && delta) { //we are in IE8, see https://github.com/brandonaaron/jquery-mousewheel/issues/53 deltaY = delta; } if (!deltaX && !deltaY) { //this happens in IE8 test case return; } if (deltaY > 0 && instance.getSetting('offsetRow') === 0) { return; //attempt to scroll up when it's already showing first row } else if (deltaY < 0 && instance.wtTable.isLastRowFullyVisible()) { return; //attempt to scroll down when it's already showing last row } else if (deltaX < 0 && instance.getSetting('offsetColumn') === 0) { return; //attempt to scroll left when it's already showing first column } else if (deltaX > 0 && instance.wtTable.isLastColumnFullyVisible()) { return; //attempt to scroll right when it's already showing last column } //now we are sure we really want to scroll clearTimeout(instance.wheelTimeout); instance.wheelTimeout = setTimeout(function () { //timeout is needed because with fast-wheel scrolling mousewheel event comes dozen times per second if (deltaY) { //ceil is needed because jquery-mousewheel reports fractional mousewheel deltas on touchpad scroll //see http://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers if (instance.wtScrollbars.vertical.visible) { // if we see scrollbar instance.scrollVertical(-Math.ceil(deltaY)).draw(); } } else if (deltaX) { if (instance.wtScrollbars.horizontal.visible) { // if we see scrollbar instance.scrollHorizontal(Math.ceil(deltaX)).draw(); } } }, 0); event.preventDefault(); }); } /** * Dragdealer JS v0.9.5 - patched by Walkontable at lines 66, 309-310, 339-340 * http://code.ovidiu.ch/dragdealer-js * * Copyright (c) 2010, Ovidiu Chereches * MIT License * http://legal.ovidiu.ch/licenses/MIT */ /* Cursor */ var Cursor = { x: 0, y: 0, init: function() { this.setEvent('mouse'); this.setEvent('touch'); }, setEvent: function(type) { var moveHandler = document['on' + type + 'move'] || function(){}; document['on' + type + 'move'] = function(e) { moveHandler(e); Cursor.refresh(e); } }, refresh: function(e) { if(!e) { e = window.event; } if(e.type == 'mousemove') { this.set(e); } else if(e.touches) { this.set(e.touches[0]); } }, set: function(e) { if(e.pageX || e.pageY) { this.x = e.pageX; this.y = e.pageY; } else if(document.body && (e.clientX || e.clientY)) //need to check whether body exists, because of IE8 issue (#1084) { this.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; this.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } } }; Cursor.init(); /* Position */ var Position = { get: function(obj) { var curtop = 0, curleft = 0; //Walkontable patch. Original (var curleft = curtop = 0;) created curtop in global scope if(obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while((obj = obj.offsetParent)); } return [curleft, curtop]; } }; /* Dragdealer */ var Dragdealer = function(wrapper, options) { if(typeof(wrapper) == 'string') { wrapper = document.getElementById(wrapper); } if(!wrapper) { return; } var handle = wrapper.getElementsByTagName('div')[0]; if(!handle || handle.className.search(/(^|\s)handle(\s|$)/) == -1) { return; } this.init(wrapper, handle, options || {}); this.setup(); }; Dragdealer.prototype = { init: function(wrapper, handle, options) { this.wrapper = wrapper; this.handle = handle; this.options = options; this.disabled = this.getOption('disabled', false); this.horizontal = this.getOption('horizontal', true); this.vertical = this.getOption('vertical', false); this.slide = this.getOption('slide', true); this.steps = this.getOption('steps', 0); this.snap = this.getOption('snap', false); this.loose = this.getOption('loose', false); this.speed = this.getOption('speed', 10) / 100; this.xPrecision = this.getOption('xPrecision', 0); this.yPrecision = this.getOption('yPrecision', 0); this.callback = options.callback || null; this.animationCallback = options.animationCallback || null; this.bounds = { left: options.left || 0, right: -(options.right || 0), top: options.top || 0, bottom: -(options.bottom || 0), x0: 0, x1: 0, xRange: 0, y0: 0, y1: 0, yRange: 0 }; this.value = { prev: [-1, -1], current: [options.x || 0, options.y || 0], target: [options.x || 0, options.y || 0] }; this.offset = { wrapper: [0, 0], mouse: [0, 0], prev: [-999999, -999999], current: [0, 0], target: [0, 0] }; this.change = [0, 0]; this.activity = false; this.dragging = false; this.tapping = false; }, getOption: function(name, defaultValue) { return this.options[name] !== undefined ? this.options[name] : defaultValue; }, setup: function() { this.setWrapperOffset(); this.setBoundsPadding(); this.setBounds(); this.setSteps(); this.addListeners(); }, setWrapperOffset: function() { this.offset.wrapper = Position.get(this.wrapper); }, setBoundsPadding: function() { if(!this.bounds.left && !this.bounds.right) { this.bounds.left = Position.get(this.handle)[0] - this.offset.wrapper[0]; this.bounds.right = -this.bounds.left; } if(!this.bounds.top && !this.bounds.bottom) { this.bounds.top = Position.get(this.handle)[1] - this.offset.wrapper[1]; this.bounds.bottom = -this.bounds.top; } }, setBounds: function() { this.bounds.x0 = this.bounds.left; this.bounds.x1 = this.wrapper.offsetWidth + this.bounds.right; this.bounds.xRange = (this.bounds.x1 - this.bounds.x0) - this.handle.offsetWidth; this.bounds.y0 = this.bounds.top; this.bounds.y1 = this.wrapper.offsetHeight + this.bounds.bottom; this.bounds.yRange = (this.bounds.y1 - this.bounds.y0) - this.handle.offsetHeight; this.bounds.xStep = 1 / (this.xPrecision || Math.max(this.wrapper.offsetWidth, this.handle.offsetWidth)); this.bounds.yStep = 1 / (this.yPrecision || Math.max(this.wrapper.offsetHeight, this.handle.offsetHeight)); }, setSteps: function() { if(this.steps > 1) { this.stepRatios = []; for(var i = 0; i <= this.steps - 1; i++) { this.stepRatios[i] = i / (this.steps - 1); } } }, addListeners: function() { var self = this; this.wrapper.onselectstart = function() { return false; } this.handle.onmousedown = this.handle.ontouchstart = function(e) { self.handleDownHandler(e); }; this.wrapper.onmousedown = this.wrapper.ontouchstart = function(e) { self.wrapperDownHandler(e); }; var mouseUpHandler = document.onmouseup || function(){}; document.onmouseup = function(e) { mouseUpHandler(e); self.documentUpHandler(e); }; var touchEndHandler = document.ontouchend || function(){}; document.ontouchend = function(e) { touchEndHandler(e); self.documentUpHandler(e); }; var resizeHandler = window.onresize || function(){}; window.onresize = function(e) { resizeHandler(e); self.documentResizeHandler(e); }; this.wrapper.onmousemove = function(e) { self.activity = true; } this.wrapper.onclick = function(e) { return !self.activity; } this.interval = setInterval(function(){ self.animate() }, 25); self.animate(false, true); }, handleDownHandler: function(e) { this.activity = false; Cursor.refresh(e); this.preventDefaults(e, true); this.startDrag(); }, wrapperDownHandler: function(e) { Cursor.refresh(e); this.preventDefaults(e, true); this.startTap(); }, documentUpHandler: function(e) { this.stopDrag(); this.stopTap(); }, documentResizeHandler: function(e) { this.setWrapperOffset(); this.setBounds(); this.update(); }, enable: function() { this.disabled = false; this.handle.className = this.handle.className.replace(/\s?disabled/g, ''); }, disable: function() { this.disabled = true; this.handle.className += ' disabled'; }, setStep: function(x, y, snap) { this.setValue( this.steps && x > 1 ? (x - 1) / (this.steps - 1) : 0, this.steps && y > 1 ? (y - 1) / (this.steps - 1) : 0, snap ); }, setValue: function(x, y, snap) { this.setTargetValue([x, y || 0]); if(snap) { this.groupCopy(this.value.current, this.value.target); } }, startTap: function(target) { if(this.disabled) { return; } this.tapping = true; this.setWrapperOffset(); this.setBounds(); if(target === undefined) { target = [ Cursor.x - this.offset.wrapper[0] - (this.handle.offsetWidth / 2), Cursor.y - this.offset.wrapper[1] - (this.handle.offsetHeight / 2) ]; } this.setTargetOffset(target); }, stopTap: function() { if(this.disabled || !this.tapping) { return; } this.tapping = false; this.setTargetValue(this.value.current); this.result(); }, startDrag: function() { if(this.disabled) { return; } this.setWrapperOffset(); this.setBounds(); this.offset.mouse = [ Cursor.x - Position.get(this.handle)[0], Cursor.y - Position.get(this.handle)[1] ]; this.dragging = true; }, stopDrag: function() { if(this.disabled || !this.dragging) { return; } this.dragging = false; var target = this.groupClone(this.value.current); if(this.slide) { var ratioChange = this.change; target[0] += ratioChange[0] * 4; target[1] += ratioChange[1] * 4; } this.setTargetValue(target); this.result(); }, feedback: function() { var value = this.value.current; if(this.snap && this.steps > 1) { value = this.getClosestSteps(value); } if(!this.groupCompare(value, this.value.prev)) { if(typeof(this.animationCallback) == 'function') { this.animationCallback(value[0], value[1]); } this.groupCopy(this.value.prev, value); } }, result: function() { if(typeof(this.callback) == 'function') { this.callback(this.value.target[0], this.value.target[1]); } }, animate: function(direct, first) { if(direct && !this.dragging) { return; } if(this.dragging) { var prevTarget = this.groupClone(this.value.target); var offset = [ Cursor.x - this.offset.wrapper[0] - this.offset.mouse[0], Cursor.y - this.offset.wrapper[1] - this.offset.mouse[1] ]; this.setTargetOffset(offset, this.loose); this.change = [ this.value.target[0] - prevTarget[0], this.value.target[1] - prevTarget[1] ]; } if(this.dragging || first) { this.groupCopy(this.value.current, this.value.target); } if(this.dragging || this.glide() || first) { this.update(); this.feedback(); } }, glide: function() { var diff = [ this.value.target[0] - this.value.current[0], this.value.target[1] - this.value.current[1] ]; if(!diff[0] && !diff[1]) { return false; } if(Math.abs(diff[0]) > this.bounds.xStep || Math.abs(diff[1]) > this.bounds.yStep) { this.value.current[0] += diff[0] * this.speed; this.value.current[1] += diff[1] * this.speed; } else { this.groupCopy(this.value.current, this.value.target); } return true; }, update: function() { if(!this.snap) { this.offset.current = this.getOffsetsByRatios(this.value.current); } else { this.offset.current = this.getOffsetsByRatios( this.getClosestSteps(this.value.current) ); } this.show(); }, show: function() { if(!this.groupCompare(this.offset.current, this.offset.prev)) { if(this.horizontal) { this.handle.style.left = String(this.offset.current[0]) + 'px'; } if(this.vertical) { this.handle.style.top = String(this.offset.current[1]) + 'px'; } this.groupCopy(this.offset.prev, this.offset.current); } }, setTargetValue: function(value, loose) { var target = loose ? this.getLooseValue(value) : this.getProperValue(value); this.groupCopy(this.value.target, target); this.offset.target = this.getOffsetsByRatios(target); }, setTargetOffset: function(offset, loose) { var value = this.getRatiosByOffsets(offset); var target = loose ? this.getLooseValue(value) : this.getProperValue(value); this.groupCopy(this.value.target, target); this.offset.target = this.getOffsetsByRatios(target); }, getLooseValue: function(value) { var proper = this.getProperValue(value); return [ proper[0] + ((value[0] - proper[0]) / 4), proper[1] + ((value[1] - proper[1]) / 4) ]; }, getProperValue: function(value) { var proper = this.groupClone(value); proper[0] = Math.max(proper[0], 0); proper[1] = Math.max(proper[1], 0); proper[0] = Math.min(proper[0], 1); proper[1] = Math.min(proper[1], 1); if((!this.dragging && !this.tapping) || this.snap) { if(this.steps > 1) { proper = this.getClosestSteps(proper); } } return proper; }, getRatiosByOffsets: function(group) { return [ this.getRatioByOffset(group[0], this.bounds.xRange, this.bounds.x0), this.getRatioByOffset(group[1], this.bounds.yRange, this.bounds.y0) ]; }, getRatioByOffset: function(offset, range, padding) { return range ? (offset - padding) / range : 0; }, getOffsetsByRatios: function(group) { return [ this.getOffsetByRatio(group[0], this.bounds.xRange, this.bounds.x0), this.getOffsetByRatio(group[1], this.bounds.yRange, this.bounds.y0) ]; }, getOffsetByRatio: function(ratio, range, padding) { return Math.round(ratio * range) + padding; }, getClosestSteps: function(group) { return [ this.getClosestStep(group[0]), this.getClosestStep(group[1]) ]; }, getClosestStep: function(value) { var k = 0; var min = 1; for(var i = 0; i <= this.steps - 1; i++) { if(Math.abs(this.stepRatios[i] - value) < min) { min = Math.abs(this.stepRatios[i] - value); k = i; } } return this.stepRatios[k]; }, groupCompare: function(a, b) { return a[0] == b[0] && a[1] == b[1]; }, groupCopy: function(a, b) { a[0] = b[0]; a[1] = b[1]; }, groupClone: function(a) { return [a[0], a[1]]; }, preventDefaults: function(e, selection) { if(!e) { e = window.event; } if(e.preventDefault) { e.preventDefault(); } e.returnValue = false; if(selection && document.selection) { document.selection.empty(); } }, cancelEvent: function(e) { if(!e) { e = window.event; } if(e.stopPropagation) { e.stopPropagation(); } e.cancelBubble = true; } }; /*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.1.3 * * Requires: 1.2.2+ */ (function (factory) { if ( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS style for Browserify module.exports = factory; } else { // Browser globals factory(jQuery); } }(function ($) { var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll']; var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll']; var lowestDelta, lowestDeltaXY; if ( $.event.fixHooks ) { for ( var i = toFix.length; i; ) { $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, absDeltaXY = 0, fn; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; } if ( orgEvent.detail ) { delta = orgEvent.detail * -1; } // New school wheel delta (wheel event) if ( orgEvent.deltaY ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( orgEvent.deltaX ) { deltaX = orgEvent.deltaX; delta = deltaX * -1; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; } // Look for lowest delta to normalize the delta values absDelta = Math.abs(delta); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; } absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX)); if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; } // Get a whole value for the deltas fn = delta > 0 ? 'floor' : 'ceil'; delta = Math[fn](delta / lowestDelta); deltaX = Math[fn](deltaX / lowestDeltaXY); deltaY = Math[fn](deltaY / lowestDeltaXY); // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return ($.event.dispatch || $.event.handle).apply(this, args); } })); })(jQuery, window, Handsontable); // numeral.js // version : 1.4.7 // author : Adam Draper // license : MIT // http://adamwdraper.github.com/Numeral-js/ (function () { /************************************ Constants ************************************/ var numeral, VERSION = '1.4.7', // internal storage for language config files languages = {}, currentLanguage = 'en', zeroFormat = null, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports); /************************************ Constructors ************************************/ // Numeral prototype object function Numeral (number) { this._n = number; } /** * Implementation of toFixed() that treats floats more like decimals * * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present * problems for accounting- and finance-related software. */ function toFixed (value, precision, optionals) { var power = Math.pow(10, precision), output; // Multiply up by precision, round accurately, then divide and use native toFixed(): output = (Math.round(value * power) / power).toFixed(precision); if (optionals) { var optionalsRegExp = new RegExp('0{1,' + optionals + '}$'); output = output.replace(optionalsRegExp, ''); } return output; } /************************************ Formatting ************************************/ // determine what type of formatting we need to do function formatNumeral (n, format) { var output; // figure out what kind of format we are dealing with if (format.indexOf('$') > -1) { // currency!!!!! output = formatCurrency(n, format); } else if (format.indexOf('%') > -1) { // percentage output = formatPercentage(n, format); } else if (format.indexOf(':') > -1) { // time output = formatTime(n, format); } else { // plain ol' numbers or bytes output = formatNumber(n, format); } // return string return output; } // revert to number function unformatNumeral (n, string) { if (string.indexOf(':') > -1) { n._n = unformatTime(string); } else { if (string === zeroFormat) { n._n = 0; } else { var stringOriginal = string; if (languages[currentLanguage].delimiters.decimal !== '.') { string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.'); } // see if abbreviations are there so that we can multiply to the correct number var thousandRegExp = new RegExp(languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), millionRegExp = new RegExp(languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), billionRegExp = new RegExp(languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), trillionRegExp = new RegExp(languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); // see if bytes are there so that we can multiply to the correct number var prefixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], bytesMultiplier = false; for (var power = 0; power <= prefixes.length; power++) { bytesMultiplier = (string.indexOf(prefixes[power]) > -1) ? Math.pow(1024, power + 1) : false; if (bytesMultiplier) { break; } } // do some math to create our number n._n = ((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) * Number(((string.indexOf('(') > -1) ? '-' : '') + string.replace(/[^0-9\.-]+/g, '')); // round if we are talking about bytes n._n = (bytesMultiplier) ? Math.ceil(n._n) : n._n; } } return n._n; } function formatCurrency (n, format) { var prependSymbol = (format.indexOf('$') <= 1) ? true : false; // remove $ for the moment var space = ''; // check for space before or after currency if (format.indexOf(' $') > -1) { space = ' '; format = format.replace(' $', ''); } else if (format.indexOf('$ ') > -1) { space = ' '; format = format.replace('$ ', ''); } else { format = format.replace('$', ''); } // format the number var output = formatNumeral(n, format); // position the symbol if (prependSymbol) { if (output.indexOf('(') > -1 || output.indexOf('-') > -1) { output = output.split(''); output.splice(1, 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) { var space = ''; // check for space before % if (format.indexOf(' %') > -1) { space = ' '; format = format.replace(' %', ''); } else { format = format.replace('%', ''); } n._n = n._n * 100; var output = formatNumeral(n, format); if (output.indexOf(')') > -1 ) { output = output.split(''); output.splice(-1, 0, space + '%'); output = output.join(''); } else { output = output + space + '%'; } return output; } function formatTime (n, format) { var hours = Math.floor(n._n/60/60), minutes = Math.floor((n._n - (hours * 60 * 60))/60), seconds = Math.round(n._n - (hours * 60 * 60) - (minutes * 60)); return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds); } function unformatTime (string) { var timeArray = string.split(':'), seconds = 0; // turn hours and minutes into seconds and add them all up if (timeArray.length === 3) { // hours seconds = seconds + (Number(timeArray[0]) * 60 * 60); // minutes seconds = seconds + (Number(timeArray[1]) * 60); // seconds seconds = seconds + Number(timeArray[2]); } else if (timeArray.lenght === 2) { // minutes seconds = seconds + (Number(timeArray[0]) * 60); // seconds seconds = seconds + Number(timeArray[1]); } return Number(seconds); } function formatNumber (n, format) { var negP = false, optDec = false, abbr = '', bytes = '', ord = '', abs = Math.abs(n._n); // check if number is zero and a custom zero format has been set if (n._n === 0 && zeroFormat !== null) { return zeroFormat; } else { // see if we should use parentheses for negative number if (format.indexOf('(') > -1) { negP = true; format = format.slice(1, -1); } // see if abbreviation is wanted if (format.indexOf('a') > -1) { // check for space before abbreviation if (format.indexOf(' a') > -1) { abbr = ' '; format = format.replace(' a', ''); } else { format = format.replace('a', ''); } if (abs >= Math.pow(10, 12)) { // trillion abbr = abbr + languages[currentLanguage].abbreviations.trillion; n._n = n._n / Math.pow(10, 12); } else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9)) { // billion abbr = abbr + languages[currentLanguage].abbreviations.billion; n._n = n._n / Math.pow(10, 9); } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6)) { // million abbr = abbr + languages[currentLanguage].abbreviations.million; n._n = n._n / Math.pow(10, 6); } else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3)) { // thousand abbr = abbr + languages[currentLanguage].abbreviations.thousand; n._n = n._n / Math.pow(10, 3); } } // see if we are formatting bytes if (format.indexOf('b') > -1) { // check for space before if (format.indexOf(' b') > -1) { bytes = ' '; format = format.replace(' b', ''); } else { format = format.replace('b', ''); } var prefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max; for (var power = 0; power <= prefixes.length; power++) { min = Math.pow(1024, power); max = Math.pow(1024, power+1); if (n._n >= min && n._n < max) { bytes = bytes + prefixes[power]; if (min > 0) { n._n = n._n / min; } break; } } } // see if ordinal is wanted if (format.indexOf('o') > -1) { // check for space before if (format.indexOf(' o') > -1) { ord = ' '; format = format.replace(' o', ''); } else { format = format.replace('o', ''); } ord = ord + languages[currentLanguage].ordinal(n._n); } if (format.indexOf('[.]') > -1) { optDec = true; format = format.replace('[.]', '.'); } var w = n._n.toString().split('.')[0], precision = format.split('.')[1], thousands = format.indexOf(','), d = '', neg = false; if (precision) { if (precision.indexOf('[') > -1) { precision = precision.replace(']', ''); precision = precision.split('['); d = toFixed(n._n, (precision[0].length + precision[1].length), precision[1].length); } else { d = toFixed(n._n, precision.length); } w = d.split('.')[0]; if (d.split('.')[1].length) { d = languages[currentLanguage].delimiters.decimal + d.split('.')[1]; } else { d = ''; } if (optDec && Number(d) === 0) { d = ''; } } else { w = toFixed(n._n, null); } // format number if (w.indexOf('-') > -1) { w = w.slice(1); neg = true; } if (thousands > -1) { w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands); } if (format.indexOf('.') === 0) { w = ''; } return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : ''); } } /************************************ Top Level Functions ************************************/ numeral = function (input) { if (numeral.isNumeral(input)) { input = input.value(); } else if (!Number(input)) { input = 0; } return new Numeral(Number(input)); }; // version number numeral.version = VERSION; // compare numeral object numeral.isNumeral = function (obj) { return obj instanceof Numeral; }; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. numeral.language = function (key, values) { if (!key) { return currentLanguage; } if (key && !values) { currentLanguage = key; } if (values || !languages[key]) { loadLanguage(key, values); } return numeral; }; 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) { if (typeof(format) === 'string') { zeroFormat = format; } else { zeroFormat = null; } }; /************************************ Helpers ************************************/ function loadLanguage(key, values) { languages[key] = values; } /************************************ Numeral Prototype ************************************/ numeral.fn = Numeral.prototype = { clone : function () { return numeral(this); }, format : function (inputString) { return formatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, unformat : function (inputString) { return unformatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, value : function () { return this._n; }, valueOf : function () { return this._n; }, set : function (value) { this._n = Number(value); return this; }, add : function (value) { this._n = this._n + Number(value); return this; }, subtract : function (value) { this._n = this._n - Number(value); return this; }, multiply : function (value) { this._n = this._n * Number(value); return this; }, divide : function (value) { this._n = this._n / Number(value); return this; }, difference : function (value) { var difference = this._n - Number(value); if (difference < 0) { difference = -difference; } return difference; } }; /************************************ Exposing Numeral ************************************/ // CommonJS module is defined if (hasModule) { module.exports = numeral; } /*global ender:false */ if (typeof ender === 'undefined') { // here, `this` means `window` in the browser, or `global` on the server // add `numeral` as a global object via a string identifier, // for Closure Compiler 'advanced' mode this['numeral'] = numeral; } /*global define:false */ if (typeof define === 'function' && define.amd) { define([], function () { return numeral; }); } }).call(this);
ajax/libs/js-data/1.5.11/js-data-debug.js
nolsherry/cdnjs
/*! * js-data * @version 1.5.11 - Homepage <http://www.js-data.io/> * @author Jason Dobry <[email protected]> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("bluebird"), (function webpackLoadOptionalExternalModule() { try { return require("js-data-schema"); } catch(e) {} }())); else if(typeof define === 'function' && define.amd) define(["bluebird", "js-data-schema"], factory); else if(typeof exports === 'object') exports["JSData"] = factory(require("bluebird"), (function webpackLoadOptionalExternalModule() { try { return require("js-data-schema"); } catch(e) {} }())); else root["JSData"] = factory(root["bluebird"], root["Schemator"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_5__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var DS = _interopRequire(__webpack_require__(3)); module.exports = { DS: DS, createStore: function createStore(options) { return new DS(options); }, DSUtils: DSUtils, DSErrors: DSErrors, version: { full: "1.5.11", major: parseInt("1", 10), minor: parseInt("5", 10), patch: parseInt("11", 10), alpha: true ? "false" : false, beta: true ? "false" : false } }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; /* jshint eqeqeq:false */ var DSErrors = _interopRequire(__webpack_require__(2)); var forEach = _interopRequire(__webpack_require__(9)); var slice = _interopRequire(__webpack_require__(10)); var forOwn = _interopRequire(__webpack_require__(14)); var contains = _interopRequire(__webpack_require__(11)); var deepMixIn = _interopRequire(__webpack_require__(15)); var pascalCase = _interopRequire(__webpack_require__(19)); var remove = _interopRequire(__webpack_require__(12)); var pick = _interopRequire(__webpack_require__(16)); var sort = _interopRequire(__webpack_require__(13)); var upperCase = _interopRequire(__webpack_require__(20)); var observe = _interopRequire(__webpack_require__(8)); var es6Promise = _interopRequire(__webpack_require__(21)); var BinaryHeap = _interopRequire(__webpack_require__(22)); var w = undefined, _Promise = undefined; var DSUtils = undefined; var objectProto = Object.prototype; var toString = objectProto.toString; es6Promise.polyfill(); var isArray = Array.isArray || function isArray(value) { return toString.call(value) == "[object Array]" || false; }; var isRegExp = function (value) { return toString.call(value) == "[object RegExp]" || false; }; // adapted from lodash.isBoolean var isBoolean = function (value) { return value === true || value === false || value && typeof value == "object" && toString.call(value) == "[object Boolean]" || false; }; // adapted from lodash.isString var isString = function (value) { return typeof value == "string" || value && typeof value == "object" && toString.call(value) == "[object String]" || false; }; var isObject = function (value) { return toString.call(value) == "[object Object]" || false; }; // adapted from lodash.isDate var isDate = function (value) { return value && typeof value == "object" && toString.call(value) == "[object Date]" || false; }; // adapted from lodash.isNumber var isNumber = function (value) { var type = typeof value; return type == "number" || value && type == "object" && toString.call(value) == "[object Number]" || false; }; // adapted from lodash.isFunction var isFunction = function (value) { return typeof value == "function" || value && toString.call(value) === "[object Function]" || false; }; // shorthand argument checking functions, using these shaves 1.18 kb off of the minified build var isStringOrNumber = function (value) { return isString(value) || isNumber(value); }; var isStringOrNumberErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be a string or a number!"); }; var isObjectErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be an object!"); }; var isArrayErr = function (field) { return new DSErrors.IA("\"" + field + "\" must be an array!"); }; // adapted from mout.isEmpty var isEmpty = function (val) { if (val == null) { // jshint ignore:line // typeof null == 'object' so we check it first return true; } else if (typeof val === "string" || isArray(val)) { return !val.length; } else if (typeof val === "object") { var _ret = (function () { var result = true; forOwn(val, function () { result = false; return false; // break loop }); return { v: result }; })(); if (typeof _ret === "object") return _ret.v; } else { return true; } }; var intersection = function (array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item = undefined; for (var i = 0, _length = array1.length; i < _length; i++) { item = array1[i]; if (DSUtils.contains(result, item)) { continue; } if (DSUtils.contains(array2, item)) { result.push(item); } } return result; }; var filter = function (array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; }; function finallyPolyfill(cb) { var constructor = this.constructor; return this.then(function (value) { return constructor.resolve(cb()).then(function () { return value; }); }, function (reason) { return constructor.resolve(cb()).then(function () { throw reason; }); }); } try { w = window; if (!w.Promise.prototype["finally"]) { w.Promise.prototype["finally"] = finallyPolyfill; } _Promise = w.Promise; w = {}; } catch (e) { w = null; _Promise = __webpack_require__(4); } function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } var toPromisify = ["beforeValidate", "validate", "afterValidate", "beforeCreate", "afterCreate", "beforeUpdate", "afterUpdate", "beforeDestroy", "afterDestroy"]; // adapted from angular.copy var copy = function (source, destination, stackSource, stackDest) { if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { destination = copy(source, Object.create(Object.getPrototypeOf(source)), stackSource, stackDest); } } } else { if (source === destination) { throw new Error("Cannot copy! Source and destination are identical."); } stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) { return stackDest[index]; } stackSource.push(source); stackDest.push(destination); } var result = undefined; if (isArray(source)) { destination.length = 0; for (var i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function (value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { result = copy(source[key], null, stackSource, stackDest); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } } } return destination; }; // adapted from angular.equals var equals = function (o1, o2) { if (o1 === o2) { return true; } if (o1 === null || o2 === null) { return false; } if (o1 !== o1 && o2 !== o2) { return true; } // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == "object") { if (isArray(o1)) { if (!isArray(o2)) { return false; } if ((length = o1.length) == o2.length) { // jshint ignore:line for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) { return false; } } return true; } } else if (isDate(o1)) { if (!isDate(o2)) { return false; } return equals(o1.getTime(), o2.getTime()); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isArray(o2)) { return false; } keySet = {}; for (key in o1) { if (key.charAt(0) === "$" || isFunction(o1[key])) { continue; } if (!equals(o1[key], o2[key])) { return false; } keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== "$" && o2[key] !== undefined && !isFunction(o2[key])) { return false; } } return true; } } } return false; }; var resolveId = function (definition, idOrInstance) { if (isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } }; var resolveItem = function (resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } }; var isValidString = function (val) { return val != null && val !== ""; // jshint ignore:line }; var join = function (items, separator) { separator = separator || ""; return filter(items, isValidString).join(separator); }; var makePath = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var result = join(args, "/"); return result.replace(/([^:\/]|^)\/{2,}/g, "$1/"); }; DSUtils = { // Options that inherit from defaults _: function _(parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new DSErrors.IA("\"options\" must be an object!"); } forEach(toPromisify, function (name) { if (typeof options[name] === "function" && options[name].toString().indexOf("for (var _len = arg") === -1) { options[name] = _this.promisify(options[name]); } }); var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; O.prototype = parent; O.prototype.orig = function () { var orig = {}; forOwn(this, function (value, key) { orig[key] = value; }); return orig; }; return new O(options); }, _n: isNumber, _s: isString, _sn: isStringOrNumber, _snErr: isStringOrNumberErr, _o: isObject, _oErr: isObjectErr, _a: isArray, _aErr: isArrayErr, compute: function compute(fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property _this[field] = fn[fn.length - 1].apply(_this, args); }, contains: contains, copy: copy, deepMixIn: deepMixIn, diffObjectFromOldObject: observe.diffObjectFromOldObject, BinaryHeap: BinaryHeap, equals: equals, Events: Events, filter: filter, forEach: forEach, forOwn: forOwn, fromJson: function fromJson(json) { return isString(json) ? JSON.parse(json) : json; }, get: __webpack_require__(17), intersection: intersection, isArray: isArray, isBoolean: isBoolean, isDate: isDate, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isRegExp: isRegExp, isString: isString, makePath: makePath, observe: observe, pascalCase: pascalCase, pick: pick, Promise: _Promise, promisify: function promisify(fn, target) { var _this = this; if (!fn) { return; } else if (typeof fn !== "function") { throw new Error("Can only promisify functions!"); } return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new _this.Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, remove: remove, set: __webpack_require__(18), slice: slice, sort: sort, toJson: JSON.stringify, updateTimestamp: function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === "function" ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } }, upperCase: upperCase, removeCircular: function removeCircular(object) { var objects = []; return (function rmCirc(value) { var i = undefined; var nu = undefined; if (typeof value === "object" && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return undefined; } } objects.push(value); if (DSUtils.isArray(value)) { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = rmCirc(value[i]); } } else { nu = {}; forOwn(value, function (v, k) { nu[k] = rmCirc(value[k]); }); } return nu; } return value; })(object); }, resolveItem: resolveItem, resolveId: resolveId, w: w }; module.exports = DSUtils; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var IllegalArgumentError = (function (_Error) { function IllegalArgumentError(message) { _classCallCheck(this, IllegalArgumentError); _get(Object.getPrototypeOf(IllegalArgumentError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || "Illegal Argument!"; } _inherits(IllegalArgumentError, _Error); return IllegalArgumentError; })(Error); var RuntimeError = (function (_Error2) { function RuntimeError(message) { _classCallCheck(this, RuntimeError); _get(Object.getPrototypeOf(RuntimeError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || "RuntimeError Error!"; } _inherits(RuntimeError, _Error2); return RuntimeError; })(Error); var NonexistentResourceError = (function (_Error3) { function NonexistentResourceError(resourceName) { _classCallCheck(this, NonexistentResourceError); _get(Object.getPrototypeOf(NonexistentResourceError.prototype), "constructor", this).call(this, this); if (typeof Error.captureStackTrace === "function") { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = "" + resourceName + " is not a registered resource!"; } _inherits(NonexistentResourceError, _Error3); return NonexistentResourceError; })(Error); module.exports = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /* jshint eqeqeq:false */ var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var syncMethods = _interopRequire(__webpack_require__(6)); var asyncMethods = _interopRequire(__webpack_require__(7)); var Schemator = undefined; function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(_x, _x2, _x3, _x4) { var _again = true; _function: while (_again) { _again = false; var orderBy = _x, index = _x2, a = _x3, b = _x4; def = cA = cB = undefined; var def = orderBy[index]; var cA = DSUtils.get(a, def[0]), cB = DSUtils.get(b, def[0]); if (DSUtils._s(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils._s(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === "DESC") { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { _x = orderBy; _x2 = index + 1; _x3 = a; _x4 = b; _again = true; continue _function; } else { return 0; } } } } } var Defaults = (function () { function Defaults() { _classCallCheck(this, Defaults); } _createClass(Defaults, { errorFn: { value: function errorFn(a, b) { if (this.error && typeof this.error === "function") { try { if (typeof a === "string") { throw new Error(a); } else { throw a; } } catch (err) { a = err; } this.error(this.name || null, a || null, b || null); } } } }); return Defaults; })(); var defaultsPrototype = Defaults.prototype; defaultsPrototype.actions = {}; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.afterReap = lifecycleNoop; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.basePath = ""; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.beforeReap = lifecycleNoop; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.bypassCache = false; defaultsPrototype.cacheResponse = !!DSUtils.w; defaultsPrototype.defaultAdapter = "http"; defaultsPrototype.debug = true; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.endpoint = ""; defaultsPrototype.error = console ? function (a, b, c) { return console[typeof console.error === "function" ? "error" : "log"](a, b, c); } : false; defaultsPrototype.fallbackAdapters = ["http"]; defaultsPrototype.findBelongsTo = true; defaultsPrototype.findHasOne = true; defaultsPrototype.findHasMany = true; defaultsPrototype.findInverseLinks = true; defaultsPrototype.idAttribute = "id"; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.ignoreMissing = false; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.loadFromServer = false; defaultsPrototype.log = console ? function (a, b, c, d, e) { return console[typeof console.info === "function" ? "info" : "log"](a, b, c, d, e); } : false; defaultsPrototype.logFn = function (a, b, c, d) { var _this = this; if (_this.debug && _this.log && typeof _this.log === "function") { _this.log(_this.name || null, a || null, b || null, c || null, d || null); } }; defaultsPrototype.maxAge = false; defaultsPrototype.notify = !!DSUtils.w; defaultsPrototype.reapAction = !!DSUtils.w ? "inject" : "none"; defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.strategy = "single"; defaultsPrototype.upsert = !!DSUtils.w; defaultsPrototype.useClass = true; defaultsPrototype.useFilter = false; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var filtered = collection; var where = null; var reserved = { skip: "", offset: "", where: "", limit: "", orderBy: "", sort: "" }; params = params || {}; options = options || {}; if (DSUtils._o(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { "==": value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forOwn(where, function (clause, field) { if (DSUtils._s(clause)) { clause = { "===": clause }; } else if (DSUtils._n(clause) || DSUtils.isBoolean(clause)) { clause = { "==": clause }; } if (DSUtils._o(clause)) { DSUtils.forOwn(clause, function (term, op) { var expr = undefined; var isOr = op[0] === "|"; var val = attrs[field]; op = isOr ? op.substr(1) : op; if (op === "==") { expr = val == term; } else if (op === "===") { expr = val === term; } else if (op === "!=") { expr = val != term; } else if (op === "!==") { expr = val !== term; } else if (op === ">") { expr = val > term; } else if (op === ">=") { expr = val >= term; } else if (op === "<") { expr = val < term; } else if (op === "<=") { expr = val <= term; } else if (op === "isectEmpty") { expr = !DSUtils.intersection(val || [], term || []).length; } else if (op === "isectNotEmpty") { expr = DSUtils.intersection(val || [], term || []).length; } else if (op === "in") { if (DSUtils._s(term)) { expr = term.indexOf(val) !== -1; } else { expr = DSUtils.contains(term, val); } } else if (op === "notIn") { if (DSUtils._s(term)) { expr = term.indexOf(val) === -1; } else { expr = !DSUtils.contains(term, val); } } else if (op === "contains") { if (DSUtils._s(val)) { expr = val.indexOf(term) !== -1; } else { expr = DSUtils.contains(val, term); } } else if (op === "notContains") { if (DSUtils._s(val)) { expr = val.indexOf(term) === -1; } else { expr = !DSUtils.contains(val, term); } } if (expr !== undefined) { keep = first ? expr : isOr ? keep || expr : keep && expr; } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils._s(params.orderBy)) { orderBy = [[params.orderBy, "ASC"]]; } else if (DSUtils._a(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils._s(params.sort)) { orderBy = [[params.sort, "ASC"]]; } else if (!orderBy && DSUtils._a(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { (function () { var index = 0; DSUtils.forEach(orderBy, function (def, i) { if (DSUtils._s(def)) { orderBy[i] = [def, "ASC"]; } else if (!DSUtils._a(def)) { throw new DSErrors.IA("DS.filter(\"" + resourceName + "\"[, params][, options]): " + DSUtils.toJson(def) + ": Must be a string or an array!", { params: { "orderBy[i]": { actual: typeof def, expected: "string|array" } } }); } }); filtered = DSUtils.sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); })(); } var limit = DSUtils._n(params.limit) ? params.limit : null; var skip = null; if (DSUtils._n(params.skip)) { skip = params.skip; } else if (DSUtils._n(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (DSUtils._n(limit)) { filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (DSUtils._n(skip)) { if (skip < filtered.length) { filtered = DSUtils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; var DS = (function () { function DS(options) { _classCallCheck(this, DS); var _this = this; options = options || {}; try { Schemator = __webpack_require__(5); } catch (e) {} if (!Schemator || DSUtils.isEmpty(Schemator)) { try { Schemator = window.Schemator; } catch (e) {} } Schemator = Schemator || options.schemator; if (typeof Schemator === "function") { _this.schemator = new Schemator(); } _this.store = {}; // alias store, shaves 0.1 kb off the minified build _this.s = _this.store; _this.definitions = {}; // alias definitions, shaves 0.3 kb off the minified build _this.defs = _this.definitions; _this.adapters = {}; _this.defaults = new Defaults(); _this.observe = DSUtils.observe; DSUtils.forOwn(options, function (v, k) { _this.defaults[k] = v; }); _this.defaults.logFn("new data store created", _this.defaults); } _createClass(DS, { getAdapter: { value: function getAdapter(options) { var errorIfNotExist = false; options = options || {}; this.defaults.logFn("getAdapter", options); if (DSUtils._s(options)) { errorIfNotExist = true; options = { adapter: options }; } var adapter = this.adapters[options.adapter]; if (adapter) { return adapter; } else if (errorIfNotExist) { throw new Error("" + options.adapter + " is not a registered adapter!"); } else { return this.adapters[options.defaultAdapter]; } } }, registerAdapter: { value: function registerAdapter(name, Adapter, options) { var _this = this; options = options || {}; _this.defaults.logFn("registerAdapter", name, Adapter, options); if (DSUtils.isFunction(Adapter)) { _this.adapters[name] = new Adapter(options); } else { _this.adapters[name] = Adapter; } if (options["default"]) { _this.defaults.defaultAdapter = name; } _this.defaults.logFn("default adapter is " + _this.defaults.defaultAdapter); } }, is: { value: function is(resourceName, instance) { var definition = this.defs[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } return instance instanceof definition[definition["class"]]; } } }); return DS; })(); var dsPrototype = DS.prototype; dsPrototype.getAdapter.shorthand = false; dsPrototype.registerAdapter.shorthand = false; dsPrototype.errors = DSErrors; dsPrototype.utils = DSUtils; DSUtils.deepMixIn(dsPrototype, syncMethods); DSUtils.deepMixIn(dsPrototype, asyncMethods); module.exports = DS; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { if(typeof __WEBPACK_EXTERNAL_MODULE_5__ === 'undefined') {var e = new Error("Cannot find module \"undefined\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var defineResource = _interopRequire(__webpack_require__(23)); var eject = _interopRequire(__webpack_require__(24)); var ejectAll = _interopRequire(__webpack_require__(25)); var filter = _interopRequire(__webpack_require__(26)); var inject = _interopRequire(__webpack_require__(27)); var link = _interopRequire(__webpack_require__(28)); var linkAll = _interopRequire(__webpack_require__(29)); var linkInverse = _interopRequire(__webpack_require__(30)); var unlinkInverse = _interopRequire(__webpack_require__(31)); var NER = DSErrors.NER; var IA = DSErrors.IA; var R = DSErrors.R; function diffIsEmpty(diff) { return !(DSUtils.isEmpty(diff.added) && DSUtils.isEmpty(diff.removed) && DSUtils.isEmpty(diff.changed)); } module.exports = { changes: function changes(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("changes", id, options); var item = _this.get(resourceName, id); if (item) { var _ret = (function () { if (DSUtils.w) { _this.s[resourceName].observers[id].deliver(); } var ignoredChanges = options.ignoredChanges || []; DSUtils.forEach(definition.relationFields, function (field) { return ignoredChanges.push(field); }); var diff = DSUtils.diffObjectFromOldObject(item, _this.s[resourceName].previousAttributes[id], DSUtils.equals, ignoredChanges); DSUtils.forOwn(diff, function (changeset, name) { var toKeep = []; DSUtils.forOwn(changeset, function (value, field) { if (!DSUtils.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return { v: diff }; })(); if (typeof _ret === "object") { return _ret.v; } } }, changeHistory: function changeHistory(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (resourceName && !_this.defs[resourceName]) { throw new NER(resourceName); } else if (id && !DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("changeHistory", id); if (!definition.keepChangeHistory) { definition.errorFn("changeHistory is disabled for this resource!"); } else { if (resourceName) { var item = _this.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } }, compute: function compute(resourceName, instance) { var _this = this; var definition = _this.defs[resourceName]; instance = DSUtils.resolveItem(_this.s[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!instance) { throw new R("Item not in the store!"); } else if (!DSUtils._o(instance) && !DSUtils._sn(instance)) { throw new IA("\"instance\" must be an object, string or number!"); } definition.logFn("compute", instance); DSUtils.forOwn(definition.computed, function (fn, field) { DSUtils.compute.call(instance, fn, field); }); return instance; }, createInstance: function createInstance(resourceName, attrs, options) { var definition = this.defs[resourceName]; var item = undefined; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !DSUtils.isObject(attrs)) { throw new IA("\"attrs\" must be an object!"); } options = DSUtils._(definition, options); options.logFn("createInstance", attrs, options); if (options.notify) { options.beforeCreateInstance(options, attrs); } if (options.useClass) { var Constructor = definition[definition["class"]]; item = new Constructor(); } else { item = {}; } DSUtils.deepMixIn(item, attrs); if (options.notify) { options.afterCreateInstance(options, attrs); } return item; }, defineResource: defineResource, digest: function digest() { this.observe.Platform.performMicrotaskCheckpoint(); }, eject: eject, ejectAll: ejectAll, filter: filter, get: function get(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("get", id, options); // cache miss, request resource from server var item = _this.s[resourceName].index[id]; if (!item && options.loadFromServer) { _this.find(resourceName, id, options); } // return resource from cache return item; }, getAll: function getAll(resourceName, ids) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var collection = []; if (!definition) { throw new NER(resourceName); } else if (ids && !DSUtils._a(ids)) { throw DSUtils._aErr("ids"); } definition.logFn("getAll", ids); if (DSUtils._a(ids)) { var _length = ids.length; for (var i = 0; i < _length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { collection = resource.collection.slice(); } return collection; }, hasChanges: function hasChanges(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("hasChanges", id); // return resource from cache if (_this.get(resourceName, id)) { return diffIsEmpty(_this.changes(resourceName, id)); } else { return false; } }, inject: inject, lastModified: function lastModified(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } definition.logFn("lastModified", id); if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; }, lastSaved: function lastSaved(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } definition.logFn("lastSaved", id); if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; }, link: link, linkAll: linkAll, linkInverse: linkInverse, previous: function previous(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } definition.logFn("previous", id); // return resource from cache return resource.previousAttributes[id] ? DSUtils.copy(resource.previousAttributes[id]) : undefined; }, unlinkInverse: unlinkInverse }; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var create = _interopRequire(__webpack_require__(40)); var destroy = _interopRequire(__webpack_require__(41)); var destroyAll = _interopRequire(__webpack_require__(42)); var find = _interopRequire(__webpack_require__(43)); var findAll = _interopRequire(__webpack_require__(44)); var loadRelations = _interopRequire(__webpack_require__(45)); var reap = _interopRequire(__webpack_require__(46)); var save = _interopRequire(__webpack_require__(47)); var update = _interopRequire(__webpack_require__(48)); var updateAll = _interopRequire(__webpack_require__(49)); module.exports = { create: create, destroy: destroy, destroyAll: destroyAll, find: find, findAll: findAll, loadRelations: loadRelations, reap: reap, refresh: function refresh(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.defs[resourceName]; id = DSUtils.resolveId(_this.defs[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.bypassCache = true; options.logFn("refresh", id, options); resolve(_this.get(resourceName, id)); } }).then(function (item) { return item ? _this.find(resourceName, id, options) : item; }); }, save: save, update: update, updateAll: updateAll }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // Modifications // Copyright 2014-2015 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Exposed diffObjectFromOldObject on the exported object // Added the "equals" argument to diffObjectFromOldObject to be used to check equality // Added a way in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; var testingExposeCycleCount = global.testingExposeCycleCount; var equalityFn = function (a, b) { return a === b; }; var blacklist = []; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function isBlacklisted(prop, bl) { if (!bl || !bl.length) { return false; } var matches; for (var i = 0; i < bl.length; i++) { if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) { return matches = prop; } } return !!matches; } function diffObjectFromOldObject(object, oldObject, equals, bl) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, bl)) continue; if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop])) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; if (isBlacklisted(prop, bl)) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ return function(fn) { return Promise.resolve().then(fn); } })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, 'delete': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } // Export the observe-js object for **Node.js**, with backwards-compatibility // for the old `require()` API. Also ensure `exports` is not a DOM Element. // If we're in the browser, export as a global object. global.Observer = Observer; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.diffObjectFromOldObject = diffObjectFromOldObject; global.ObjectObserver = ObjectObserver; })(exports); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(32); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var indexOf = __webpack_require__(32); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(33); var forIn = __webpack_require__(34); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var forOwn = __webpack_require__(14); var isPlainObject = __webpack_require__(36); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var slice = __webpack_require__(10); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var isPrimitive = __webpack_require__(35); /** * get "nested" object property */ function get(obj, prop){ var parts = prop.split('.'), last = parts.pop(); while (prop = parts.shift()) { obj = obj[prop]; if (obj == null) return; } return obj[last]; } module.exports = get; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var namespace = __webpack_require__(37); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(38); var camelCase = __webpack_require__(39); var upperCase = __webpack_require__(20); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(38); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(process, global, module) {/*! * @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/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, 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. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** 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 var 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){ var 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 $$es6$promise$promise$$Promise(resolver) { this._id = $$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** 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 var 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 var 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: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor($$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `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(onRejection) { return this.then(null, onRejection); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { 'Promise': $$es6$promise$promise$$default, 'polyfill': $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if ("function" === 'function' && __webpack_require__(51)['amd']) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return es6$promise$umd$$ES6Promise; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(50), (function() { return this; }()), __webpack_require__(52)(module))) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /*! * yabh * @version 1.0.0 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <[email protected]> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else if(typeof define === 'function' && define.amd) define(factory); else if(typeof exports === 'object') exports["BinaryHeap"] = factory(); else root["BinaryHeap"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var _parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(_parent)) { break; } else { heap[parentN] = element; heap[n] = _parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ var bubbleDown = function (heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } }; var BinaryHeap = (function () { function BinaryHeap(weightFunc, compareFunc) { _classCallCheck(this, BinaryHeap); if (!weightFunc) { weightFunc = function (x) { return x; }; } if (!compareFunc) { compareFunc = function (x, y) { return x === y; }; } if (typeof weightFunc !== "function") { throw new Error("BinaryHeap([weightFunc][, compareFunc]): \"weightFunc\" must be a function!"); } if (typeof compareFunc !== "function") { throw new Error("BinaryHeap([weightFunc][, compareFunc]): \"compareFunc\" must be a function!"); } this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } _createClass(BinaryHeap, { push: { value: function push(node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); } }, peek: { value: function peek() { return this.heap[0]; } }, pop: { value: function pop() { var front = this.heap[0]; var end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; } }, remove: { value: function remove(node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; } }, removeAll: { value: function removeAll() { this.heap = []; } }, size: { value: function size() { return this.heap.length; } } }); return BinaryHeap; })(); module.exports = BinaryHeap; /***/ } /******/ ]) }); ; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; module.exports = defineResource; /*jshint evil:true, loopfunc:true*/ var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); var Resource = function Resource(options) { _classCallCheck(this, Resource); DSUtils.deepMixIn(this, options); if ("endpoint" in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } }; var instanceMethods = ["compute", "refresh", "save", "update", "destroy", "loadRelations", "changeHistory", "changes", "hasChanges", "lastModified", "lastSaved", "link", "linkInverse", "previous", "unlinkInverse"]; function defineResource(definition) { var _this = this; var definitions = _this.defs; if (DSUtils._s(definition)) { definition = { name: definition.replace(/\s/gi, "") }; } if (!DSUtils._o(definition)) { throw DSUtils._oErr("definition"); } else if (!DSUtils._s(definition.name)) { throw new DSErrors.IA("\"name\" must be a string!"); } else if (_this.s[definition.name]) { throw new DSErrors.R("" + definition.name + " is already registered!"); } try { // Inherit from global defaults Resource.prototype = _this.defaults; definitions[definition.name] = new Resource(definition); var def = definitions[definition.name]; // alias name, shaves 0.08 kb off the minified build def.n = def.name; def.logFn("Preparing resource."); if (!DSUtils._s(def.idAttribute)) { throw new DSErrors.IA("\"idAttribute\" must be a string!"); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forOwn(def.relations, function (relatedModels, type) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (!DSUtils._a(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.n; def.relationList.push(d); def.relationFields.push(d.localField); }); }); }); if (def.relations.belongsTo) { DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; def.parentField = relation.localField; } }); }); } if (typeof Object.freeze === "function") { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getResource = function (resourceName) { return _this.defs[resourceName]; }; def.getEndpoint = function (id, options) { options.params = options.params || {}; var item = undefined; var parentKey = def.parentKey; var endpoint = options.hasOwnProperty("endpoint") ? options.endpoint : def.endpoint; var parentField = def.parentField; var parentDef = definitions[def.parent]; var parentId = options.params[parentKey]; if (parentId === false || !parentKey || !parentDef) { if (parentId === false) { delete options.params[parentKey]; } return endpoint; } else { delete options.params[parentKey]; if (DSUtils._sn(id)) { item = def.get(id); } else if (DSUtils._o(id)) { item = id; } if (item) { parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null); } if (parentId) { var _ret = (function () { delete options.endpoint; var _options = {}; DSUtils.forOwn(options, function (value, key) { _options[key] = value; }); return { v: DSUtils.makePath(parentDef.getEndpoint(parentId, DSUtils._(parentDef, _options)), parentId, endpoint) }; })(); if (typeof _ret === "object") return _ret.v; } else { return endpoint; } } }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Create the wrapper class for the new resource var _class = def["class"] = DSUtils.pascalCase(def.name); try { if (typeof def.useClass === "function") { eval("function " + _class + "() { def.useClass.call(this); }"); def[_class] = eval(_class); def[_class].prototype = (function (proto) { function Ctor() {} Ctor.prototype = proto; return new Ctor(); })(def.useClass.prototype); } else { eval("function " + _class + "() {}"); def[_class] = eval(_class); } } catch (e) { def[_class] = function () {}; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[_class].prototype, def.methods); } def[_class].prototype.set = function (key, value) { DSUtils.set(this, key, value); var observer = _this.s[def.n].observers[this[def.idAttribute]]; if (observer && !DSUtils.observe.hasObjectObserve) { observer.deliver(); } else { _this.compute(def.n, this); } return this; }; def[_class].prototype.get = function (key) { return DSUtils.get(this, key); }; // Prepare for computed properties if (def.computed) { DSUtils.forOwn(def.computed, function (fn, field) { if (DSUtils.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { def.errorFn("Computed property \"" + field + "\" conflicts with previously defined prototype method!"); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(","); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { def.errorFn("Use the computed property array syntax for compatibility with minified code!"); } } deps = fn.slice(0, fn.length - 1); DSUtils.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); } if (definition.schema && _this.schemator) { def.schema = _this.schemator.defineSchema(def.n, definition.schema); if (!definition.hasOwnProperty("validate")) { def.validate = function (resourceName, attrs, cb) { def.schema.validate(attrs, { ignoreMissing: def.ignoreMissing }, function (err) { if (err) { return cb(err); } else { return cb(null, attrs); } }); }; } } DSUtils.forEach(instanceMethods, function (name) { def[_class].prototype["DS" + DSUtils.pascalCase(name)] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this[def.idAttribute] || this); args.unshift(def.n); return _this[name].apply(_this, args); }; }); def[_class].prototype.DSCreate = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(this); args.unshift(def.n); return _this.create.apply(_this, args); }; // Initialize store data for the new resource _this.s[def.n] = { collection: [], expiresHeap: new DSUtils.BinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, queryData: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; if (def.reapInterval) { setInterval(function () { return _this.reap(def.n, { isInterval: true }); }, def.reapInterval); } // Proxy DS methods with shorthand ones var fns = ["registerAdapter", "getAdapter", "is"]; for (var key in _this) { if (typeof _this[key] === "function") { fns.push(key); } } DSUtils.forEach(fns, function (key) { var k = key; if (_this[k].shorthand !== false) { def[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args.unshift(def.n); return _this[k].apply(_this, args); }; } else { def[k] = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _this[k].apply(_this, args); }; } }); def.beforeValidate = DSUtils.promisify(def.beforeValidate); def.validate = DSUtils.promisify(def.validate); def.afterValidate = DSUtils.promisify(def.afterValidate); def.beforeCreate = DSUtils.promisify(def.beforeCreate); def.afterCreate = DSUtils.promisify(def.afterCreate); def.beforeUpdate = DSUtils.promisify(def.beforeUpdate); def.afterUpdate = DSUtils.promisify(def.afterUpdate); def.beforeDestroy = DSUtils.promisify(def.beforeDestroy); def.afterDestroy = DSUtils.promisify(def.afterDestroy); DSUtils.forOwn(def.actions, function (action, name) { if (def[name] && !def.actions[name]) { throw new Error("Cannot override existing method \"" + name + "\"!"); } def[name] = function (options) { options = options || {}; var adapter = _this.getAdapter(action.adapter || "http"); var config = DSUtils.deepMixIn({}, action); if (!options.hasOwnProperty("endpoint") && config.endpoint) { options.endpoint = config.endpoint; } if (typeof options.getEndpoint === "function") { config.url = options.getEndpoint(def, options); } else { config.url = DSUtils.makePath(options.basePath || adapter.defaults.basePath || def.basePath, def.getEndpoint(null, options), name); } config.method = config.method || "GET"; DSUtils.deepMixIn(config, options); return adapter.HTTP(config); }; }); // Mix-in events DSUtils.Events(def); def.logFn("Done preparing resource."); return def; } catch (err) { delete definitions[definition.name]; delete _this.s[definition.name]; throw err; } } /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { module.exports = eject; function eject(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item = undefined; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } options = DSUtils._(definition, options); options.logFn("eject", id, options); for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { // jshint ignore:line item = resource.collection[i]; resource.expiresHeap.remove(item); found = true; break; } } if (found) { var _ret = (function () { if (options.notify) { definition.beforeEject(options, item); definition.emit("DS.beforeEject", definition, item); } _this.unlinkInverse(definition.n, id); resource.collection.splice(i, 1); if (DSUtils.w) { resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); var toRemove = []; DSUtils.forOwn(resource.queryData, function (items, queryHash) { if (items.$$injected) { DSUtils.remove(items, item); } if (!items.length) { toRemove.push(queryHash); } }); DSUtils.forEach(toRemove, function (queryHash) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.notify) { definition.afterEject(options, item); definition.emit("DS.afterEject", definition, item); } return { v: item }; })(); if (typeof _ret === "object") { return _ret.v; } } } /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { module.exports = ejectAll; function ejectAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; params = params || {}; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._o(params)) { throw DSUtils._oErr("params"); } definition.logFn("ejectAll", params, options); var resource = _this.s[resourceName]; var queryHash = DSUtils.toJson(params); var items = _this.filter(definition.n, params); var ids = []; if (DSUtils.isEmpty(params)) { resource.completedQueries = {}; } else { delete resource.completedQueries[queryHash]; } DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); DSUtils.forEach(ids, function (id) { _this.eject(definition.n, id, options); }); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); return items; } /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { module.exports = filter; function filter(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; if (!definition) { throw new _this.errors.NER(resourceName); } else if (params && !DSUtils._o(params)) { throw DSUtils._oErr("params"); } // Protect against null params = params || {}; options = DSUtils._(definition, options); options.logFn("filter", params, options); var queryHash = DSUtils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started _this.findAll(resourceName, params, options); } } return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options); } /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; module.exports = inject; var DSUtils = _interopRequire(__webpack_require__(1)); var DSErrors = _interopRequire(__webpack_require__(2)); function _getReactFunction(DS, definition, resource) { var name = definition.n; return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item = undefined; var innerId = oldValueFn && oldValueFn(definition.idAttribute) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(name, innerId); DSUtils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed DSUtils.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { DSUtils.compute.call(item, fn, field); } }); } if (definition.relations) { item = item || DS.get(name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { definition.errorFn("Doh! You just changed the primary key of an object! Your data for the \"" + name + "\" resource is now in an undefined (probably broken) state."); } }; } function _inject(definition, resource, attrs, options) { var _this = this; var _react = _getReactFunction(_this, definition, resource, attrs, options); var injected = undefined; if (DSUtils._a(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { (function () { var args = []; DSUtils.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); })(); } if (!(idA in attrs)) { var error = new DSErrors.R("" + definition.n + ".inject: \"attrs\" must contain the property specified by \"idAttribute\"!"); options.errorFn(error); throw error; } else { try { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.defs[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new DSErrors.R("" + definition.n + " relation is defined but the resource is not!"); } if (DSUtils._a(toInject)) { (function () { var items = []; DSUtils.forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.s[relationName].index[toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = _this.inject(relationName, toInjectItem, options.orig()); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { options.errorFn(err, "Failed to inject " + def.type + " relation: \"" + relationName + "\"!"); } } }); attrs[def.localField] = items; })(); } else { if (toInject !== _this.s[relationName].index[toInject[relationDef.idAttribute]]) { try { attrs[def.localField] = _this.inject(relationName, attrs[def.localField], options.orig()); if (def.foreignKey) { attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { options.errorFn(err, "Failed to inject " + def.type + " relation: \"" + relationName + "\"!"); } } } } }); var id = attrs[idA]; var item = _this.get(definition.n, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition["class"]]) { item = attrs; } else { item = new definition[definition["class"]](); } } else { item = {}; } DSUtils.deepMixIn(item, attrs); resource.collection.push(item); resource.changeHistories[id] = []; if (DSUtils.w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } resource.index[id] = item; _react.call(item, {}, {}, {}, null, true); resource.previousAttributes[id] = DSUtils.copy(item); } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(item); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (DSUtils.w) { resource.observers[id].deliver(); } } resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; resource.expiresHeap.remove(item); var timestamp = new Date().getTime(); resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); injected = item; } catch (err) { options.errorFn(err, attrs); } } } return injected; } function _link(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === "belongsTo" && injected[definition.idAttribute]) { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } else if (options.findHasMany && def.type === "hasMany" || options.findHasOne && def.type === "hasOne") { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } }); } function inject(resourceName, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var injected = undefined; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._o(attrs) && !DSUtils._a(attrs)) { throw new DSErrors.IA("" + resourceName + ".inject: \"attrs\" must be an object or an array!"); } var name = definition.n; options = DSUtils._(definition, options); options.logFn("inject", attrs, options); if (options.notify) { options.beforeInject(options, attrs); definition.emit("DS.beforeInject", definition, attrs); } injected = _inject.call(_this, definition, resource, attrs, options); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.findInverseLinks) { if (DSUtils._a(injected)) { if (injected.length) { _this.linkInverse(name, injected[0][definition.idAttribute]); } } else { _this.linkInverse(name, injected[definition.idAttribute]); } } if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (injectedI) { _link.call(_this, definition, injectedI, options); }); } else { _link.call(_this, definition, injected, options); } if (options.notify) { options.afterInject(options, injected); definition.emit("DS.afterInject", definition, injected); } return injected; } /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { module.exports = link; function link(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("link", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } var params = {}; if (def.type === "belongsTo") { var _parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null; if (_parent) { linked[def.localField] = _parent; } } else if (def.type === "hasMany") { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === "hasOne") { params[def.foreignKey] = linked[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } return linked; } /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { module.exports = linkAll; function linkAll(resourceName, params, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("linkAll", params, relations); var linked = _this.filter(resourceName, params); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } if (def.type === "belongsTo") { DSUtils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === "hasMany") { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === "hasOne") { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } return linked; } /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { module.exports = linkInverse; function linkInverse(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("linkInverse", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (relations.length && !DSUtils.contains(relations, d.n)) { return; } if (definition.n === relationName) { _this.linkAll(d.n, {}, [definition.n]); } }); }); }); } return linked; } /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { module.exports = unlinkInverse; function unlinkInverse(resourceName, id, relations) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new _this.errors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr("id"); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr("relations"); } definition.logFn("unlinkInverse", id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (definition.n === relationName) { DSUtils.forEach(defs, function (def) { DSUtils.forEach(_this.s[def.name].collection, function (item) { if (def.type === "hasMany" && item[def.localField]) { (function () { var index = undefined; DSUtils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); if (index !== undefined) { item[def.localField].splice(index, 1); } })(); } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } return linked; } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var hasOwn = __webpack_require__(33); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the object is a primitive */ function isPrimitive(value) { // Using switch fallthrough because it's simple to read and is // generally fast: http://jsperf.com/testing-value-is-primitive/5 switch (typeof value) { case "string": case "number": case "boolean": return true; } return value == null; } module.exports = isPrimitive; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var forEach = __webpack_require__(9); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(38); var replaceAccents = __webpack_require__(53); var removeNonWord = __webpack_require__(54); var upperCase = __webpack_require__(20); var lowerCase = __webpack_require__(55); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { module.exports = create; function create(resourceName, attrs, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; options = options || {}; attrs = attrs || {}; var rejectionError = undefined; if (!definition) { rejectionError = new _this.errors.NER(resourceName); } else if (!DSUtils._o(attrs)) { rejectionError = DSUtils._oErr("attrs"); } else { options = DSUtils._(definition, options); if (options.upsert && DSUtils._sn(attrs[definition.idAttribute])) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } options.logFn("create", attrs, options); } return new DSUtils.Promise(function (resolve, reject) { if (rejectionError) { reject(rejectionError); } else { resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeCreate", definition, attrs); } return _this.getAdapter(options).create(definition, attrs, options); }).then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterCreate", definition, attrs); } if (options.cacheResponse) { var created = _this.inject(definition.n, attrs, options.orig()); var id = created[definition.idAttribute]; var resource = _this.s[resourceName]; resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return created; } else { return _this.createInstance(resourceName, attrs, options); } }); } /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { module.exports = destroy; function destroy(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var item = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { item = _this.get(resourceName, id) || { id: id }; options = DSUtils._(definition, options); options.logFn("destroy", id, options); resolve(item); } }).then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeDestroy", definition, attrs); } if (options.eagerEject) { _this.eject(resourceName, id); } return _this.getAdapter(options).destroy(definition, id, options); }).then(function () { return options.afterDestroy.call(item, options, item); }).then(function (item) { if (options.notify) { definition.emit("DS.afterDestroy", definition, item); } _this.eject(resourceName, id); return id; })["catch"](function (err) { if (options && options.eagerEject && item) { _this.inject(resourceName, item, { notify: false }); } throw err; }); } /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { module.exports = destroyAll; function destroyAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var ejected = undefined, toEject = undefined; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr("attrs")); } else { options = DSUtils._(definition, options); options.logFn("destroyAll", params, options); resolve(); } }).then(function () { toEject = _this.defaults.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit("DS.beforeDestroy", definition, toEject); } if (options.eagerEject) { ejected = _this.ejectAll(resourceName, params); } return _this.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit("DS.afterDestroy", definition, toEject); } return ejected || _this.ejectAll(resourceName, params); })["catch"](function (err) { if (options && options.eagerEject && ejected) { _this.inject(resourceName, ejected, { notify: false }); } throw err; }); } /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /* jshint -W082 */ module.exports = find; function find(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.logFn("find", id, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (id in resource.completedQueries && _this.get(resourceName, id)) { resolve(_this.get(resourceName, id)); } else { delete resource.completedQueries[id]; resolve(); } } }).then(function (item) { if (!item) { if (!(id in resource.pendingQueries)) { var promise = undefined; var strategy = options.findStrategy || options.strategy; if (strategy === "fallback") { (function () { var makeFallbackCall = function (index) { return _this.getAdapter((options.findFallbackAdapters || options.fallbackAdapters)[index]).find(definition, id, options)["catch"](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return DSUtils.Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { promise = _this.getAdapter(options).find(definition, id, options); } resource.pendingQueries[id] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { var injected = _this.inject(resourceName, data, options.orig()); resource.completedQueries[id] = new Date().getTime(); resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); return injected; } else { return _this.createInstance(resourceName, data, options.orig()); } }); } return resource.pendingQueries[id]; } else { return item; } })["catch"](function (err) { if (resource) { delete resource.pendingQueries[id]; } throw err; }); } /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { module.exports = findAll; /* jshint -W082 */ function processResults(data, resourceName, queryHash, options) { var _this = this; var DSUtils = _this.utils; var resource = _this.s[resourceName]; var idAttribute = _this.defs[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = _this.inject(resourceName, data, options.orig()); // Make sure each object is added to completedQueries if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (item) { if (item) { var id = item[idAttribute]; if (id) { resource.completedQueries[id] = date; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); } } }); } else { options.errorFn("response is expected to be an array!"); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function findAll(resourceName, params, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var queryHash = undefined; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.defs[resourceName]) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr("params")); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); options.logFn("findAll", params, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; } if (queryHash in resource.completedQueries) { if (options.useFilter) { resolve(_this.filter(resourceName, params, options.orig())); } else { resolve(resource.queryData[queryHash]); } } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { var promise = undefined; var strategy = options.findAllStrategy || options.strategy; if (strategy === "fallback") { (function () { var makeFallbackCall = function (index) { return _this.getAdapter((options.findAllFallbackAdapters || options.fallbackAdapters)[index]).findAll(definition, params, options)["catch"](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return Promise.reject(err); } }); }; promise = makeFallbackCall(0); })(); } else { promise = _this.getAdapter(options).findAll(definition, params, options); } resource.pendingQueries[queryHash] = promise.then(function (data) { delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options); resource.queryData[queryHash].$$injected = true; return resource.queryData[queryHash]; } else { DSUtils.forEach(data, function (item, i) { data[i] = _this.createInstance(resourceName, item, options.orig()); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { return items; } })["catch"](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } throw err; }); } /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { module.exports = loadRelations; function loadRelations(resourceName, instance, relations, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var fields = []; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils._sn(instance)) { instance = _this.get(resourceName, instance); } if (DSUtils._s(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._o(instance)) { reject(new DSErrors.IA("\"instance(id)\" must be a string, number or object!")); } else if (!DSUtils._a(relations)) { reject(new DSErrors.IA("\"relations\" must be a string or an array!")); } else { (function () { var _options = DSUtils._(definition, options); if (!_options.hasOwnProperty("findBelongsTo")) { _options.findBelongsTo = true; } if (!_options.hasOwnProperty("findHasMany")) { _options.findHasMany = true; } _options.logFn("loadRelations", instance, relations, _options); var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = definition.getResource(relationName); var __options = DSUtils._(relationDef, options); if (DSUtils.contains(relations, relationName) || DSUtils.contains(relations, def.localField)) { var task = undefined; var params = {}; if (__options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { "==": instance[definition.idAttribute] }; } if (def.type === "hasMany" && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options.orig()); } else if (def.type === "hasOne") { if (def.localKey && instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], __options.orig()); } else if (def.foreignKey && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options.orig()).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); resolve(tasks); })(); } }).then(function (tasks) { return DSUtils.Promise.all(tasks); }).then(function (loadedRelations) { DSUtils.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); } /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { module.exports = reap; function reap(resourceName, options) { var _this = this; var DSUtils = _this.utils; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty("notify")) { options.notify = false; } options.logFn("reap", options); var items = []; var now = new Date().getTime(); var expiredItem = undefined; while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { if (options.isInterval || options.notify) { definition.beforeReap(options, items); definition.emit("DS.beforeReap", definition, items); } if (options.reapAction === "inject") { (function () { var timestamp = new Date().getTime(); DSUtils.forEach(items, function (item) { resource.expiresHeap.push({ item: item, timestamp: timestamp, expires: definition.maxAge ? timestamp + definition.maxAge : Number.MAX_VALUE }); }); })(); } else if (options.reapAction === "eject") { DSUtils.forEach(items, function (item) { _this.eject(resourceName, item[definition.idAttribute]); }); } else if (options.reapAction === "refresh") { var _ret2 = (function () { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.refresh(resourceName, item[definition.idAttribute])); }); return { v: DSUtils.Promise.all(tasks) }; })(); if (typeof _ret2 === "object") return _ret2.v; } return items; }).then(function (items) { if (options.isInterval || options.notify) { definition.afterReap(options, items); definition.emit("DS.afterReap", definition, items); } return items; }); } /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { module.exports = save; function save(resourceName, id, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; var item = undefined; var noChanges = undefined; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R("id \"" + id + "\" not found in cache!")); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); options.logFn("save", id, options); resolve(item); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } if (options.changesOnly) { var resource = _this.s[resourceName]; if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = _this.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return options.logFn("save - no changes", id, options); noChanges = true; return attrs; } else { attrs = changes; } } return _this.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } if (noChanges) { return attrs; } else if (options.cacheResponse) { var injected = _this.inject(definition.n, attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected); } return injected; } else { return _this.createInstance(resourceName, attrs, options.orig()); } }); } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { module.exports = update; function update(resourceName, id, attrs, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr("id")); } else { options = DSUtils._(definition, options); options.logFn("update", id, attrs, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } return _this.getAdapter(options).update(definition, id, attrs, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (attrs) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } if (options.cacheResponse) { var injected = _this.inject(definition.n, attrs, options.orig()); var resource = _this.s[resourceName]; var _id = injected[definition.idAttribute]; resource.saved[_id] = DSUtils.updateTimestamp(resource.saved[_id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[_id] = DSUtils.copy(injected); } return injected; } else { return _this.createInstance(resourceName, attrs, options.orig()); } }); } /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { module.exports = updateAll; function updateAll(resourceName, attrs, params, options) { var _this = this; var DSUtils = _this.utils; var DSErrors = _this.errors; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); options.logFn("updateAll", attrs, params, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.validate.call(attrs, options, attrs); }).then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }).then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }).then(function (attrs) { if (options.notify) { definition.emit("DS.beforeUpdate", definition, attrs); } return _this.getAdapter(options).updateAll(definition, attrs, params, options); }).then(function (data) { return options.afterUpdate.call(data, options, data); }).then(function (data) { if (options.notify) { definition.emit("DS.afterUpdate", definition, attrs); } var origOptions = options.orig(); if (options.cacheResponse) { var _ret = (function () { var injected = _this.inject(definition.n, data, origOptions); var resource = _this.s[resourceName]; DSUtils.forEach(injected, function (i) { var id = i[definition.idAttribute]; resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); if (!definition.resetHistoryOnInject) { resource.previousAttributes[id] = DSUtils.copy(i); } }); return { v: injected }; })(); if (typeof _ret === "object") return _ret.v; } else { var _ret2 = (function () { var instances = []; DSUtils.forEach(data, function (item) { instances.push(_this.createInstance(resourceName, item, origOptions)); }); return { v: instances }; })(); if (typeof _ret2 === "object") return _ret2.v; } }); } /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { // 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'); }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(38); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(38); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(38); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; /***/ } /******/ ]) });
src/routes/app/routes/tables/routes/static/components/StaticTables.js
ahthamrin/kbri-admin2
import React from 'react'; import QueueAnim from 'rc-queue-anim'; const MaterialTable = () => ( <article className="article"> <h2 className="article-title">Material Table</h2> <div className="box box-default table-box mdl-shadow--2dp"> <table className="mdl-data-table"> <thead> <tr> <th className="mdl-data-table__cell--non-numeric">#</th> <th className="mdl-data-table__cell--non-numeric">Code</th> <th className="mdl-data-table__cell--non-numeric">Material</th> <th>Quantity</th> <th>Unit price</th> </tr> </thead> <tbody> <tr> <td className="mdl-data-table__cell--non-numeric">1</td> <td className="mdl-data-table__cell--non-numeric">AZ90</td> <td className="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td> <td>25</td> <td>$2.90</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">2</td> <td className="mdl-data-table__cell--non-numeric">BC30</td> <td className="mdl-data-table__cell--non-numeric">Plywood (Birch)</td> <td>50</td> <td>$1.25</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">3</td> <td className="mdl-data-table__cell--non-numeric">DL32</td> <td className="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td> <td>10</td> <td>$2.35</td> </tr> </tbody> </table> </div> </article> ); const TableStyle = () => ( <article className="article"> <h2 className="article-title">Table Style</h2> <div className="row"> <div className="col-xl-6"> <div className="box box-transparent"> <div className="box-header no-padding-h">Basic table</div> <div className="box-body no-padding-h"> <div className="box box-default table-box mdl-shadow--2dp"> <table className="mdl-data-table"> <thead> <tr> <th className="mdl-data-table__cell--non-numeric">#</th> <th className="mdl-data-table__cell--non-numeric">Material</th> <th>Quantity</th> <th>Unit price</th> </tr> </thead> <tbody> <tr> <td className="mdl-data-table__cell--non-numeric">1</td> <td className="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td> <td>25</td> <td>$2.90</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">2</td> <td className="mdl-data-table__cell--non-numeric">Plywood (Birch)</td> <td>50</td> <td>$1.25</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">3</td> <td className="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td> <td>10</td> <td>$2.35</td> </tr> </tbody> </table> </div> </div> </div> </div> <div className="col-xl-6"> <div className="box box-transparent"> <div className="box-header no-padding-h">Striped table</div> <div className="box-body no-padding-h"> <div className="box box-default table-box mdl-shadow--2dp"> <table className="mdl-data-table table-striped"> <thead> <tr> <th className="mdl-data-table__cell--non-numeric">#</th> <th className="mdl-data-table__cell--non-numeric">Material</th> <th>Quantity</th> <th>Unit price</th> </tr> </thead> <tbody> <tr> <td className="mdl-data-table__cell--non-numeric">1</td> <td className="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td> <td>25</td> <td>$2.90</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">2</td> <td className="mdl-data-table__cell--non-numeric">Plywood (Birch)</td> <td>50</td> <td>$1.25</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">3</td> <td className="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td> <td>10</td> <td>$2.35</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> <div className="row"> <div className="col-xl-6"> <div className="box box-transparent"> <div className="box-header no-padding-h">Bordered table</div> <div className="box-body no-padding-h"> <div className="box box-default table-box mdl-shadow--2dp"> <table className="mdl-data-table table-bordered"> <thead> <tr> <th className="mdl-data-table__cell--non-numeric">#</th> <th className="mdl-data-table__cell--non-numeric">Material</th> <th>Quantity</th> <th>Unit price</th> </tr> </thead> <tbody> <tr> <td className="mdl-data-table__cell--non-numeric">1</td> <td className="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td> <td>25</td> <td>$2.90</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">2</td> <td className="mdl-data-table__cell--non-numeric">Plywood (Birch)</td> <td>50</td> <td>$1.25</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">3</td> <td className="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td> <td>10</td> <td>$2.35</td> </tr> </tbody> </table> </div> </div> </div> </div> <div className="col-xl-6"> <div className="box box-transparent"> <div className="box-header no-padding-h">Contextual table</div> <div className="box-body no-padding-h"> <div className="box box-default table-box mdl-shadow--2dp"> <table className="mdl-data-table"> <thead> <tr> <th className="mdl-data-table__cell--non-numeric">#</th> <th className="mdl-data-table__cell--non-numeric">Material</th> <th>Quantity</th> <th>Unit price</th> </tr> </thead> <tbody> <tr> <td className="mdl-data-table__cell--non-numeric">1</td> <td className="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td> <td>25</td> <td>$2.90</td> </tr> <tr className="bg-color-info"> <td className="mdl-data-table__cell--non-numeric">2</td> <td className="mdl-data-table__cell--non-numeric">Plywood (Birch)</td> <td>50</td> <td>$1.25</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">3</td> <td className="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td> <td>10</td> <td>$2.35</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </article> ); const Page = () => ( <section className="container-fluid with-maxwidth chapter"> <QueueAnim type="bottom" className="ui-animate"> <div key="1"><MaterialTable /></div> <div key="2"><TableStyle /></div> </QueueAnim> </section> ); module.exports = Page;
src/index.js
rnbez/bluetooth-chrome
import React from 'react' import ReactDOM from 'react-dom' import App from './App' import './index.css' ReactDOM.render(<App />, document.getElementById('root'))
resources/apps/frontend/src/pages/attendance/actions.js
johndavedecano/PHPLaravelGymManagementSystem
import React from 'react'; import {Row, Col} from 'reactstrap'; import get from 'lodash/get'; import {TableFilters} from 'components/Table'; import MemberSelect from 'components/Form/Select/MemberSelect'; import queryFilters from 'utils/query-filters'; import Search from 'components/Form/Input/Search'; import withFilters from 'enhancers/withFilters'; class Component extends React.Component { static defaultProps = { isLoading: false, }; state = queryFilters(); onChangeStatus = option => { this.props.onChangeFilter('status', option.value); this.setState({status: option.value}); }; onSearch = keyword => { this.setState({q: keyword}); this.props.onChangeFilter('q', keyword); }; onChangeFilter = (key, valueKey = 'value') => option => { this.props.onChangeFilter(key, option[valueKey]); this.setState({[key]: option[valueKey]}); }; render() { return ( <TableFilters> <Row> <Col md={2}> <MemberSelect placeholder="Select User" disabled={this.props.isLoading} defaultValue={get(this.state, 'entity_id')} onChange={this.onChangeFilter('entity_id', 'id')} plainLabel /> </Col> <Col md={2}> <Search disabled={this.props.isLoading} name="search" defaultValue={get(this.state, 'q')} onSubmit={this.onSearch} /> </Col> <Col md={6} /> <Col md={2} /> </Row> </TableFilters> ); } } export default withFilters(Component);
ajax/libs/yasr/2.0.2/yasr.bundled.min.js
chrisdavies/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASR=e()}}(function(){var e;return function t(e,n,r){function i(a,s){if(!n[a]){if(!e[a]){var l="function"==typeof require&&require;if(!s&&l)return l(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[a]={exports:{}};e[a][0].call(c.exports,function(t){var n=e[a][1][t];return i(n?n:t)},c,c.exports,t,e,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a<r.length;a++)i(r[a]);return i}({1:[function(e,t){"use strict";var n=e("jquery"),r=e("yasgui-utils");console=console||{log:function(){}};var i=t.exports=function(t,s,l){var u={};u.options=n.extend(!0,{},i.defaults,s),u.container=n("<div class='yasr'></div>").appendTo(t),u.header=n("<div class='yasr_header'></div>").appendTo(u.container),u.resultsContainer=n("<div class='yasr_results'></div>").appendTo(u.container),u.plugins={};for(var c in i.plugins)u.plugins[c]=new i.plugins[c](u);if(u.draw=function(e){if(!u.results)return!1;if(e||(e=u.options.output),e in u.plugins&&u.plugins[e].canHandleResults(u))return n(u.resultsContainer).empty(),u.plugins[e].draw(),!0;var t=null,r=-1;for(var i in u.plugins)if(u.plugins[i].canHandleResults(u)){var o=u.plugins[i].getPriority;"function"==typeof o&&(o=o(u)),null!=o&&void 0!=o&&o>r&&(r=o,t=i)}return t?(n(u.resultsContainer).empty(),u.plugins[t].draw(),!0):!1},u.somethingDrawn=function(){return!u.resultsContainer.is(":empty")},u.setResponse=function(t){try{u.results=e("./parsers/wrapper.js")(t)}catch(n){u.results=n}if(u.draw(),u.options.persistency&&u.options.persistency.results&&u.results.getOriginalResponseAsString&&u.results.getOriginalResponseAsString().length<u.options.persistency.results.maxSize){var i="string"==typeof u.options.persistency.results.id?u.options.persistency.results.id:u.options.persistency.results.id(u);r.storage.set(i,u.results.getOriginalResponse(),"month")}},u.options.persistency&&u.options.persistency.outputSelector){var f="string"==typeof u.options.persistency.outputSelector?u.options.persistency.outputSelector:u.options.persistency.outputSelector(u);if(f){var d=r.storage.get(f);d&&(u.options.output=d)}}if(!l&&u.options.persistency&&u.options.persistency.results){var f="string"==typeof u.options.persistency.results.id?u.options.persistency.results.id:u.options.persistency.results.id(u);l=r.storage.get(f)}return a(u),l&&u.setResponse(l),o(u),u},o=function(e){var t=e.header.find(".yasr_downloadIcon");t.removeAttr("title");var n=e.plugins[e.options.output];if(n){var r=n.getDownloadInfo?n.getDownloadInfo():null;r?(r.buttonTitle&&t.attr(r.buttonTitle),t.prop("disabled",!1),t.find("path").each(function(){this.style.fill="black"})):(t.prop("disabled",!0).prop("title","Download not supported for this result representation"),t.find("path").each(function(){this.style.fill="gray"}))}},a=function(t){var i=function(){var e=n('<div class="yasr_btnGroup"></div>');n.each(t.plugins,function(i,a){if(!a.hideFromSelection){var s=a.name||i,l=n("<button class='yasr_btn'></button>").text(s).addClass("select_"+i).click(function(){if(e.find("button.selected").removeClass("selected"),n(this).addClass("selected"),t.options.output=i,t.options.persistency&&t.options.persistency.outputSelector){var a="string"==typeof t.options.persistency.outputSelector?t.options.persistency.outputSelector:t.options.persistency.outputSelector(t);r.storage.set(a,t.options.output,"month")}t.draw(),o(t)}).appendTo(e);t.options.output==i&&l.addClass("selected")}}),e.children().length>1&&t.header.append(e)},a=function(){var r=function(e,t){var n=null,r=window.URL||window.webkitURL||window.mozURL||window.msURL;if(r&&Blob){var i=new Blob([e],{type:t});n=r.createObjectURL(i)}return n},i=n("<button class='yasr_btn yasr_downloadIcon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").download,{width:"15px",height:"15px"})).click(function(){var e=t.plugins[t.options.output];if(e&&e.getDownloadInfo){var i=e.getDownloadInfo(),o=r(i.getContent(),i.contentType?i.contentType:"text/plain"),a=n("<a></a>");a.attr("href",o),a.attr("download",i.filename),a.get(0).click()}});t.header.append(i)};t.options.drawOutputSelector&&i(),t.options.drawDownloadIcon&&a()};i.plugins={},i.registerOutput=function(e,t){i.plugins[e]=t},i.registerOutput("boolean",e("./boolean.js")),i.registerOutput("table",e("./table.js")),i.registerOutput("rawResponse",e("./rawResponse.js")),i.registerOutput("error",e("./error.js")),i.defaults=e("./defaults.js"),i.version={YASR:e("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":e("yasgui-utils").version}},{"../package.json":14,"./boolean.js":16,"./defaults.js":17,"./error.js":18,"./imgs.js":19,"./parsers/wrapper.js":24,"./rawResponse.js":26,"./table.js":27,jquery:8,"yasgui-utils":11}],2:[function(t,n,r){!function(n,i,o){!function(n){"use strict";"function"==typeof e&&e.amd?e("datatables",["jquery"],n):"object"==typeof r?n(t("jquery")):jQuery&&!jQuery.fn.dataTable&&n(jQuery)}(function(e){"use strict";function t(n){var r,i,o="a aa ai ao as b fn i m o s ",a={};e.each(n,function(e){r=e.match(/^([^A-Z]+?)([A-Z])/),r&&-1!==o.indexOf(r[1]+" ")&&(i=e.replace(r[0],r[2].toLowerCase()),a[i]=e,"o"===r[1]&&t(n[e]))}),n._hungarianMap=a}function r(n,i,a){n._hungarianMap||t(n);var s;e.each(i,function(t){s=n._hungarianMap[t],s===o||!a&&i[s]!==o||("o"===s.charAt(0)?(i[s]||(i[s]={}),e.extend(!0,i[s],i[t]),r(n[s],i[s],a)):i[s]=i[t])})}function a(e){var t=$t.defaults.oLanguage,n=e.sZeroRecords;!e.sEmptyTable&&n&&"No data available in table"===t.sEmptyTable&&Rt(e,e,"sZeroRecords","sEmptyTable"),!e.sLoadingRecords&&n&&"Loading..."===t.sLoadingRecords&&Rt(e,e,"sZeroRecords","sLoadingRecords"),e.sInfoThousands&&(e.sThousands=e.sInfoThousands);var r=e.sDecimal;r&&Xt(r)}function s(e){yn(e,"ordering","bSort"),yn(e,"orderMulti","bSortMulti"),yn(e,"orderClasses","bSortClasses"),yn(e,"orderCellsTop","bSortCellsTop"),yn(e,"order","aaSorting"),yn(e,"orderFixed","aaSortingFixed"),yn(e,"paging","bPaginate"),yn(e,"pagingType","sPaginationType"),yn(e,"pageLength","iDisplayLength"),yn(e,"searching","bFilter");var t=e.aoSearchCols;if(t)for(var n=0,i=t.length;i>n;n++)t[n]&&r($t.models.oSearch,t[n])}function l(e){yn(e,"orderable","bSortable"),yn(e,"orderData","aDataSort"),yn(e,"orderSequence","asSorting"),yn(e,"orderDataType","sortDataType")}function u(t){var n=t.oBrowser,r=e("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(e("<div/>").css({position:"absolute",top:1,left:1,width:100,overflow:"scroll"}).append(e('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),i=r.find(".test");n.bScrollOversize=100===i[0].offsetWidth,n.bScrollbarLeft=1!==i.offset().left,r.remove()}function c(e,t,n,r,i,a){var s,l=r,u=!1;for(n!==o&&(s=n,u=!0);l!==i;)e.hasOwnProperty(l)&&(s=u?t(s,e[l],l,e):e[l],u=!0,l+=a);return s}function f(t,n){var r=$t.defaults.column,o=t.aoColumns.length,a=e.extend({},$t.models.oColumn,r,{nTh:n?n:i.createElement("th"),sTitle:r.sTitle?r.sTitle:n?n.innerHTML:"",aDataSort:r.aDataSort?r.aDataSort:[o],mData:r.mData?r.mData:o,idx:o});t.aoColumns.push(a);var s=t.aoPreSearchCols;s[o]=e.extend({},$t.models.oSearch,s[o]),d(t,o,null)}function d(t,n,i){var a=t.aoColumns[n],s=t.oClasses,u=e(a.nTh);if(!a.sWidthOrig){a.sWidthOrig=u.attr("width")||null;var c=(u.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);c&&(a.sWidthOrig=c[1])}i!==o&&null!==i&&(l(i),r($t.defaults.column,i),i.mDataProp===o||i.mData||(i.mData=i.mDataProp),i.sType&&(a._sManualType=i.sType),i.className&&!i.sClass&&(i.sClass=i.className),e.extend(a,i),Rt(a,i,"sWidth","sWidthOrig"),"number"==typeof i.iDataSort&&(a.aDataSort=[i.iDataSort]),Rt(a,i,"aDataSort"));var f=a.mData,d=L(f),h=a.mRender?L(a.mRender):null,p=function(e){return"string"==typeof e&&-1!==e.indexOf("@")};a._bAttrSrc=e.isPlainObject(f)&&(p(f.sort)||p(f.type)||p(f.filter)),a.fnGetData=function(e,t,n){var r=d(e,t,o,n);return h&&t?h(r,t,e,n):r},a.fnSetData=function(e,t,n){return A(f)(e,t,n)},t.oFeatures.bSort||(a.bSortable=!1,u.addClass(s.sSortableNone));var g=-1!==e.inArray("asc",a.asSorting),m=-1!==e.inArray("desc",a.asSorting);a.bSortable&&(g||m)?g&&!m?(a.sSortingClass=s.sSortableAsc,a.sSortingClassJUI=s.sSortJUIAscAllowed):!g&&m?(a.sSortingClass=s.sSortableDesc,a.sSortingClassJUI=s.sSortJUIDescAllowed):(a.sSortingClass=s.sSortable,a.sSortingClassJUI=s.sSortJUI):(a.sSortingClass=s.sSortableNone,a.sSortingClassJUI="")}function h(e){if(e.oFeatures.bAutoWidth!==!1){var t=e.aoColumns;yt(e);for(var n=0,r=t.length;r>n;n++)t[n].nTh.style.width=t[n].sWidth}var i=e.oScroll;(""!==i.sY||""!==i.sX)&&mt(e),zt(e,null,"column-sizing",[e])}function p(e,t){var n=v(e,"bVisible");return"number"==typeof n[t]?n[t]:null}function g(t,n){var r=v(t,"bVisible"),i=e.inArray(n,r);return-1!==i?i:null}function m(e){return v(e,"bVisible").length}function v(t,n){var r=[];return e.map(t.aoColumns,function(e,t){e[n]&&r.push(t)}),r}function y(e){var t,n,r,i,a,s,l,u,c,f=e.aoColumns,d=e.aoData,h=$t.ext.type.detect;for(t=0,n=f.length;n>t;t++)if(l=f[t],c=[],!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){for(r=0,i=h.length;i>r;r++){for(a=0,s=d.length;s>a&&(c[a]===o&&(c[a]=T(e,a,t,"type")),u=h[r](c[a],e),u&&"html"!==u);a++);if(u){l.sType=u;break}}l.sType||(l.sType="string")}}function b(t,n,r,i){var a,s,l,u,c,d,h,p=t.aoColumns;if(n)for(a=n.length-1;a>=0;a--){h=n[a];var g=h.targets!==o?h.targets:h.aTargets;for(e.isArray(g)||(g=[g]),l=0,u=g.length;u>l;l++)if("number"==typeof g[l]&&g[l]>=0){for(;p.length<=g[l];)f(t);i(g[l],h)}else if("number"==typeof g[l]&&g[l]<0)i(p.length+g[l],h);else if("string"==typeof g[l])for(c=0,d=p.length;d>c;c++)("_all"==g[l]||e(p[c].nTh).hasClass(g[l]))&&i(c,h)}if(r)for(a=0,s=r.length;s>a;a++)i(a,r[a])}function x(t,n,r,i){var o=t.aoData.length,a=e.extend(!0,{},$t.models.oRow,{src:r?"dom":"data"});a._aData=n,t.aoData.push(a);for(var s=t.aoColumns,l=0,u=s.length;u>l;l++)r&&D(t,o,l,T(t,o,l)),s[l].sType=null;return t.aiDisplayMaster.push(o),(r||!t.oFeatures.bDeferRender)&&I(t,o,r,i),o}function w(t,n){var r;return n instanceof e||(n=e(n)),n.map(function(e,n){return r=j(t,n),x(t,r.data,n,r.cells)})}function S(e,t){return t._DT_RowIndex!==o?t._DT_RowIndex:null}function C(t,n,r){return e.inArray(r,t.aoData[n].anCells)}function T(e,t,n,r){var i=e.iDraw,a=e.aoColumns[n],s=e.aoData[t]._aData,l=a.sDefaultContent,u=a.fnGetData(s,r,{settings:e,row:t,col:n});if(u===o)return e.iDrawError!=i&&null===l&&(Ot(e,0,"Requested unknown parameter "+("function"==typeof a.mData?"{function}":"'"+a.mData+"'")+" for row "+t,4),e.iDrawError=i),l;if(u!==s&&null!==u||null===l){if("function"==typeof u)return u.call(s)}else u=l;return null===u&&"display"==r?"":u}function D(e,t,n,r){var i=e.aoColumns[n],o=e.aoData[t]._aData;i.fnSetData(o,r,{settings:e,row:t,col:n})}function k(t){return e.map(t.match(/(\\.|[^\.])+/g),function(e){return e.replace(/\\./g,".")})}function L(t){if(e.isPlainObject(t)){var n={};return e.each(t,function(e,t){t&&(n[e]=L(t))}),function(e,t,r,i){var a=n[t]||n._;return a!==o?a(e,t,r,i):e}}if(null===t)return function(e){return e};if("function"==typeof t)return function(e,n,r,i){return t(e,n,r,i)};if("string"!=typeof t||-1===t.indexOf(".")&&-1===t.indexOf("[")&&-1===t.indexOf("("))return function(e){return e[t]};var r=function(e,t,n){var i,a,s,l;if(""!==n)for(var u=k(n),c=0,f=u.length;f>c;c++){if(i=u[c].match(bn),a=u[c].match(xn),i){u[c]=u[c].replace(bn,""),""!==u[c]&&(e=e[u[c]]),s=[],u.splice(0,c+1),l=u.join(".");for(var d=0,h=e.length;h>d;d++)s.push(r(e[d],t,l));var p=i[0].substring(1,i[0].length-1);e=""===p?s:s.join(p);break}if(a)u[c]=u[c].replace(xn,""),e=e[u[c]]();else{if(null===e||e[u[c]]===o)return o;e=e[u[c]]}}return e};return function(e,n){return r(e,n,t)}}function A(t){if(e.isPlainObject(t))return A(t._);if(null===t)return function(){};if("function"==typeof t)return function(e,n,r){t(e,"set",n,r)};if("string"!=typeof t||-1===t.indexOf(".")&&-1===t.indexOf("[")&&-1===t.indexOf("("))return function(e,n){e[t]=n};var n=function(e,t,r){for(var i,a,s,l,u,c=k(r),f=c[c.length-1],d=0,h=c.length-1;h>d;d++){if(a=c[d].match(bn),s=c[d].match(xn),a){c[d]=c[d].replace(bn,""),e[c[d]]=[],i=c.slice(),i.splice(0,d+1),u=i.join(".");for(var p=0,g=t.length;g>p;p++)l={},n(l,t[p],u),e[c[d]].push(l);return}s&&(c[d]=c[d].replace(xn,""),e=e[c[d]](t)),(null===e[c[d]]||e[c[d]]===o)&&(e[c[d]]={}),e=e[c[d]]}f.match(xn)?e=e[f.replace(xn,"")](t):e[f.replace(bn,"")]=t};return function(e,r){return n(e,r,t)}}function N(e){return hn(e.aoData,"_aData")}function _(e){e.aoData.length=0,e.aiDisplayMaster.length=0,e.aiDisplay.length=0}function M(e,t,n){for(var r=-1,i=0,a=e.length;a>i;i++)e[i]==t?r=i:e[i]>t&&e[i]--;-1!=r&&n===o&&e.splice(r,1)}function E(e,t,n,r){var i,a,s=e.aoData[t];if("dom"!==n&&(n&&"auto"!==n||"dom"!==s.src)){var l,u=s.anCells;if(u)for(i=0,a=u.length;a>i;i++){for(l=u[i];l.childNodes.length;)l.removeChild(l.firstChild);u[i].innerHTML=T(e,t,i,"display")}}else s._aData=j(e,s).data;s._aSortData=null,s._aFilterData=null;var c=e.aoColumns;if(r!==o)c[r].sType=null;else for(i=0,a=c.length;a>i;i++)c[i].sType=null;H(s)}function j(t,n){var r,i,o,a,s=[],l=[],u=n.firstChild,c=0,f=t.aoColumns,d=function(e,t,n){if("string"==typeof e){var r=e.indexOf("@");if(-1!==r){var i=e.substring(r+1);o["@"+i]=n.getAttribute(i)}}},h=function(t){i=f[c],a=e.trim(t.innerHTML),i&&i._bAttrSrc?(o={display:a},d(i.mData.sort,o,t),d(i.mData.type,o,t),d(i.mData.filter,o,t),s.push(o)):s.push(a),c++};if(u)for(;u;)r=u.nodeName.toUpperCase(),("TD"==r||"TH"==r)&&(h(u),l.push(u)),u=u.nextSibling;else{l=n.anCells;for(var p=0,g=l.length;g>p;p++)h(l[p])}return{data:s,cells:l}}function I(e,t,n,r){var o,a,s,l,u,c=e.aoData[t],f=c._aData,d=[];if(null===c.nTr){for(o=n||i.createElement("tr"),c.nTr=o,c.anCells=d,o._DT_RowIndex=t,H(c),l=0,u=e.aoColumns.length;u>l;l++)s=e.aoColumns[l],a=n?r[l]:i.createElement(s.sCellType),d.push(a),(!n||s.mRender||s.mData!==l)&&(a.innerHTML=T(e,t,l,"display")),s.sClass&&(a.className+=" "+s.sClass),s.bVisible&&!n?o.appendChild(a):!s.bVisible&&n&&a.parentNode.removeChild(a),s.fnCreatedCell&&s.fnCreatedCell.call(e.oInstance,a,T(e,t,l),f,t,l);zt(e,"aoRowCreatedCallback",null,[o,f,t])}c.nTr.setAttribute("role","row")}function H(t){var n=t.nTr,r=t._aData;if(n){if(r.DT_RowId&&(n.id=r.DT_RowId),r.DT_RowClass){var i=r.DT_RowClass.split(" ");t.__rowc=t.__rowc?vn(t.__rowc.concat(i)):i,e(n).removeClass(t.__rowc.join(" ")).addClass(r.DT_RowClass)}r.DT_RowData&&e(n).data(r.DT_RowData)}}function O(t){var n,r,i,o,a,s=t.nTHead,l=t.nTFoot,u=0===e("th, td",s).length,c=t.oClasses,f=t.aoColumns;for(u&&(o=e("<tr/>").appendTo(s)),n=0,r=f.length;r>n;n++)a=f[n],i=e(a.nTh).addClass(a.sClass),u&&i.appendTo(o),t.oFeatures.bSort&&(i.addClass(a.sSortingClass),a.bSortable!==!1&&(i.attr("tabindex",t.iTabIndex).attr("aria-controls",t.sTableId),_t(t,a.nTh,n))),a.sTitle!=i.html()&&i.html(a.sTitle),qt(t,"header")(t,i,a,c);if(u&&z(t.aoHeader,s),e(s).find(">tr").attr("role","row"),e(s).find(">tr>th, >tr>td").addClass(c.sHeaderTH),e(l).find(">tr>th, >tr>td").addClass(c.sFooterTH),null!==l){var d=t.aoFooter[0];for(n=0,r=d.length;r>n;n++)a=f[n],a.nTf=d[n].cell,a.sClass&&e(a.nTf).addClass(a.sClass)}}function R(t,n,r){var i,a,s,l,u,c,f,d,h,p=[],g=[],m=t.aoColumns.length;if(n){for(r===o&&(r=!1),i=0,a=n.length;a>i;i++){for(p[i]=n[i].slice(),p[i].nTr=n[i].nTr,s=m-1;s>=0;s--)t.aoColumns[s].bVisible||r||p[i].splice(s,1);g.push([])}for(i=0,a=p.length;a>i;i++){if(f=p[i].nTr)for(;c=f.firstChild;)f.removeChild(c);for(s=0,l=p[i].length;l>s;s++)if(d=1,h=1,g[i][s]===o){for(f.appendChild(p[i][s].cell),g[i][s]=1;p[i+d]!==o&&p[i][s].cell==p[i+d][s].cell;)g[i+d][s]=1,d++;for(;p[i][s+h]!==o&&p[i][s].cell==p[i][s+h].cell;){for(u=0;d>u;u++)g[i+u][s+h]=1;h++}e(p[i][s].cell).attr("rowspan",d).attr("colspan",h)}}}}function P(t){var n=zt(t,"aoPreDrawCallback","preDraw",[t]);if(-1!==e.inArray(!1,n))return void pt(t,!1);var r=[],i=0,a=t.asStripeClasses,s=a.length,l=(t.aoOpenRows.length,t.oLanguage),u=t.iInitDisplayStart,c="ssp"==Ut(t),f=t.aiDisplay;t.bDrawing=!0,u!==o&&-1!==u&&(t._iDisplayStart=c?u:u>=t.fnRecordsDisplay()?0:u,t.iInitDisplayStart=-1);var d=t._iDisplayStart,h=t.fnDisplayEnd();if(t.bDeferLoading)t.bDeferLoading=!1,t.iDraw++,pt(t,!1);else if(c){if(!t.bDestroying&&!U(t))return}else t.iDraw++;if(0!==f.length)for(var p=c?0:d,g=c?t.aoData.length:h,v=p;g>v;v++){var y=f[v],b=t.aoData[y];null===b.nTr&&I(t,y);var x=b.nTr;if(0!==s){var w=a[i%s];b._sRowStripe!=w&&(e(x).removeClass(b._sRowStripe).addClass(w),b._sRowStripe=w)}zt(t,"aoRowCallback",null,[x,b._aData,i,v]),r.push(x),i++}else{var S=l.sZeroRecords;1==t.iDraw&&"ajax"==Ut(t)?S=l.sLoadingRecords:l.sEmptyTable&&0===t.fnRecordsTotal()&&(S=l.sEmptyTable),r[0]=e("<tr/>",{"class":s?a[0]:""}).append(e("<td />",{valign:"top",colSpan:m(t),"class":t.oClasses.sRowEmpty}).html(S))[0]}zt(t,"aoHeaderCallback","header",[e(t.nTHead).children("tr")[0],N(t),d,h,f]),zt(t,"aoFooterCallback","footer",[e(t.nTFoot).children("tr")[0],N(t),d,h,f]);var C=e(t.nTBody);C.children().detach(),C.append(e(r)),zt(t,"aoDrawCallback","draw",[t]),t.bSorted=!1,t.bFiltered=!1,t.bDrawing=!1}function F(e,t){var n=e.oFeatures,r=n.bSort,i=n.bFilter;r&&Lt(e),i?J(e,e.oPreviousSearch):e.aiDisplay=e.aiDisplayMaster.slice(),t!==!0&&(e._iDisplayStart=0),e._drawHold=t,P(e),e._drawHold=!1}function W(t){var n=t.oClasses,r=e(t.nTable),i=e("<div/>").insertBefore(r),o=t.oFeatures,a=e("<div/>",{id:t.sTableId+"_wrapper","class":n.sWrapper+(t.nTFoot?"":" "+n.sNoFooter)});t.nHolding=i[0],t.nTableWrapper=a[0],t.nTableReinsertBefore=t.nTable.nextSibling;for(var s,l,u,c,f,d,h=t.sDom.split(""),p=0;p<h.length;p++){if(s=null,l=h[p],"<"==l){if(u=e("<div/>")[0],c=h[p+1],"'"==c||'"'==c){for(f="",d=2;h[p+d]!=c;)f+=h[p+d],d++;if("H"==f?f=n.sJUIHeader:"F"==f&&(f=n.sJUIFooter),-1!=f.indexOf(".")){var g=f.split(".");u.id=g[0].substr(1,g[0].length-1),u.className=g[1]}else"#"==f.charAt(0)?u.id=f.substr(1,f.length-1):u.className=f;p+=d}a.append(u),a=e(u)}else if(">"==l)a=a.parent();else if("l"==l&&o.bPaginate&&o.bLengthChange)s=ct(t);else if("f"==l&&o.bFilter)s=$(t);else if("r"==l&&o.bProcessing)s=ht(t);else if("t"==l)s=gt(t);else if("i"==l&&o.bInfo)s=it(t);else if("p"==l&&o.bPaginate)s=ft(t);else if(0!==$t.ext.feature.length)for(var m=$t.ext.feature,v=0,y=m.length;y>v;v++)if(l==m[v].cFeature){s=m[v].fnInit(t);break}if(s){var b=t.aanFeatures;b[l]||(b[l]=[]),b[l].push(s),a.append(s)}}i.replaceWith(a)}function z(t,n){var r,i,o,a,s,l,u,c,f,d,h,p=e(n).children("tr"),g=function(e,t,n){for(var r=e[t];r[n];)n++;return n};for(t.splice(0,t.length),o=0,l=p.length;l>o;o++)t.push([]);for(o=0,l=p.length;l>o;o++)for(r=p[o],c=0,i=r.firstChild;i;){if("TD"==i.nodeName.toUpperCase()||"TH"==i.nodeName.toUpperCase())for(f=1*i.getAttribute("colspan"),d=1*i.getAttribute("rowspan"),f=f&&0!==f&&1!==f?f:1,d=d&&0!==d&&1!==d?d:1,u=g(t,o,c),h=1===f?!0:!1,s=0;f>s;s++)for(a=0;d>a;a++)t[o+a][u+s]={cell:i,unique:h},t[o+a].nTr=r;i=i.nextSibling}}function B(e,t,n){var r=[];n||(n=e.aoHeader,t&&(n=[],z(n,t)));for(var i=0,o=n.length;o>i;i++)for(var a=0,s=n[i].length;s>a;a++)!n[i][a].unique||r[a]&&e.bSortCellsTop||(r[a]=n[i][a].cell);return r}function q(t,n,r){if(zt(t,"aoServerParams","serverParams",[n]),n&&e.isArray(n)){var i={},o=/(.*?)\[\]$/;e.each(n,function(e,t){var n=t.name.match(o);if(n){var r=n[0];i[r]||(i[r]=[]),i[r].push(t.value)}else i[t.name]=t.value}),n=i}var a,s=t.ajax,l=t.oInstance;if(e.isPlainObject(s)&&s.data){a=s.data;var u=e.isFunction(a)?a(n):a;n=e.isFunction(a)&&u?u:e.extend(!0,n,u),delete s.data}var c={data:n,success:function(e){var n=e.error||e.sError;n&&t.oApi._fnLog(t,0,n),t.json=e,zt(t,null,"xhr",[t,e]),r(e)},dataType:"json",cache:!1,type:t.sServerMethod,error:function(e,n){var r=t.oApi._fnLog;"parsererror"==n?r(t,0,"Invalid JSON response",1):4===e.readyState&&r(t,0,"Ajax error",7),pt(t,!1)}};t.oAjaxData=n,zt(t,null,"preXhr",[t,n]),t.fnServerData?t.fnServerData.call(l,t.sAjaxSource,e.map(n,function(e,t){return{name:t,value:e}}),r,t):t.sAjaxSource||"string"==typeof s?t.jqXHR=e.ajax(e.extend(c,{url:s||t.sAjaxSource})):e.isFunction(s)?t.jqXHR=s.call(l,n,r,t):(t.jqXHR=e.ajax(e.extend(c,s)),s.data=a)}function U(e){return e.bAjaxDataGet?(e.iDraw++,pt(e,!0),q(e,V(e),function(t){X(e,t)}),!1):!0}function V(t){var n,r,i,o,a=t.aoColumns,s=a.length,l=t.oFeatures,u=t.oPreviousSearch,c=t.aoPreSearchCols,f=[],d=kt(t),h=t._iDisplayStart,p=l.bPaginate!==!1?t._iDisplayLength:-1,g=function(e,t){f.push({name:e,value:t})};g("sEcho",t.iDraw),g("iColumns",s),g("sColumns",hn(a,"sName").join(",")),g("iDisplayStart",h),g("iDisplayLength",p);var m={draw:t.iDraw,columns:[],order:[],start:h,length:p,search:{value:u.sSearch,regex:u.bRegex}};for(n=0;s>n;n++)i=a[n],o=c[n],r="function"==typeof i.mData?"function":i.mData,m.columns.push({data:r,name:i.sName,searchable:i.bSearchable,orderable:i.bSortable,search:{value:o.sSearch,regex:o.bRegex}}),g("mDataProp_"+n,r),l.bFilter&&(g("sSearch_"+n,o.sSearch),g("bRegex_"+n,o.bRegex),g("bSearchable_"+n,i.bSearchable)),l.bSort&&g("bSortable_"+n,i.bSortable);l.bFilter&&(g("sSearch",u.sSearch),g("bRegex",u.bRegex)),l.bSort&&(e.each(d,function(e,t){m.order.push({column:t.col,dir:t.dir}),g("iSortCol_"+e,t.col),g("sSortDir_"+e,t.dir)}),g("iSortingCols",d.length));var v=$t.ext.legacy.ajax;return null===v?t.sAjaxSource?f:m:v?f:m}function X(e,t){var n=function(e,n){return t[e]!==o?t[e]:t[n]},r=n("sEcho","draw"),i=n("iTotalRecords","recordsTotal"),a=n("iTotalDisplayRecords","recordsFiltered");if(r){if(1*r<e.iDraw)return;e.iDraw=1*r}_(e),e._iRecordsTotal=parseInt(i,10),e._iRecordsDisplay=parseInt(a,10);for(var s=G(e,t),l=0,u=s.length;u>l;l++)x(e,s[l]);e.aiDisplay=e.aiDisplayMaster.slice(),e.bAjaxDataGet=!1,P(e),e._bInitComplete||lt(e,t),e.bAjaxDataGet=!0,pt(e,!1)}function G(t,n){var r=e.isPlainObject(t.ajax)&&t.ajax.dataSrc!==o?t.ajax.dataSrc:t.sAjaxDataProp;return"data"===r?n.aaData||n[r]:""!==r?L(r)(n):n}function $(t){var n=t.oClasses,r=t.sTableId,o=t.oLanguage,a=t.oPreviousSearch,s=t.aanFeatures,l='<input type="search" class="'+n.sFilterInput+'"/>',u=o.sSearch;u=u.match(/_INPUT_/)?u.replace("_INPUT_",l):u+l;var c=e("<div/>",{id:s.f?null:r+"_filter","class":n.sFilter}).append(e("<label/>").append(u)),f=function(){var e=(s.f,this.value?this.value:"");e!=a.sSearch&&(J(t,{sSearch:e,bRegex:a.bRegex,bSmart:a.bSmart,bCaseInsensitive:a.bCaseInsensitive}),t._iDisplayStart=0,P(t))},d=e("input",c).val(a.sSearch).attr("placeholder",o.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT","ssp"===Ut(t)?bt(f,400):f).bind("keypress.DT",function(e){return 13==e.keyCode?!1:void 0}).attr("aria-controls",r);return e(t.nTable).on("search.dt.DT",function(e,n){if(t===n)try{d[0]!==i.activeElement&&d.val(a.sSearch)}catch(r){}}),c[0]}function J(e,t,n){var r=e.oPreviousSearch,i=e.aoPreSearchCols,a=function(e){r.sSearch=e.sSearch,r.bRegex=e.bRegex,r.bSmart=e.bSmart,r.bCaseInsensitive=e.bCaseInsensitive},s=function(e){return e.bEscapeRegex!==o?!e.bEscapeRegex:e.bRegex};if(y(e),"ssp"!=Ut(e)){Q(e,t.sSearch,n,s(t),t.bSmart,t.bCaseInsensitive),a(t);for(var l=0;l<i.length;l++)K(e,i[l].sSearch,l,s(i[l]),i[l].bSmart,i[l].bCaseInsensitive);Y(e)}else a(t);e.bFiltered=!0,zt(e,null,"search",[e])}function Y(e){for(var t,n,r=$t.ext.search,i=e.aiDisplay,o=0,a=r.length;a>o;o++){for(var s=[],l=0,u=i.length;u>l;l++)n=i[l],t=e.aoData[n],r[o](e,t._aFilterData,n,t._aData,l)&&s.push(n);i.length=0,i.push.apply(i,s)}}function K(e,t,n,r,i,o){if(""!==t)for(var a,s=e.aiDisplay,l=Z(t,r,i,o),u=s.length-1;u>=0;u--)a=e.aoData[s[u]]._aFilterData[n],l.test(a)||s.splice(u,1)}function Q(e,t,n,r,i,o){var a,s,l,u=Z(t,r,i,o),c=e.oPreviousSearch.sSearch,f=e.aiDisplayMaster;if(0!==$t.ext.search.length&&(n=!0),s=tt(e),t.length<=0)e.aiDisplay=f.slice();else for((s||n||c.length>t.length||0!==t.indexOf(c)||e.bSorted)&&(e.aiDisplay=f.slice()),a=e.aiDisplay,l=a.length-1;l>=0;l--)u.test(e.aoData[a[l]]._sFilterRow)||a.splice(l,1)}function Z(t,n,r,i){if(t=n?t:et(t),r){var o=e.map(t.match(/"[^"]+"|[^ ]+/g)||"",function(e){return'"'===e.charAt(0)?e.match(/^"(.*)"$/)[1]:e});t="^(?=.*?"+o.join(")(?=.*?")+").*$"}return new RegExp(t,i?"i":"")}function et(e){return e.replace(on,"\\$1")}function tt(e){var t,n,r,i,o,a,s,l,u=e.aoColumns,c=$t.ext.type.search,f=!1;for(n=0,i=e.aoData.length;i>n;n++)if(l=e.aoData[n],!l._aFilterData){for(a=[],r=0,o=u.length;o>r;r++)t=u[r],t.bSearchable?(s=T(e,n,r,"filter"),c[t.sType]&&(s=c[t.sType](s)),null===s&&(s=""),"string"!=typeof s&&s.toString&&(s=s.toString())):s="",s.indexOf&&-1!==s.indexOf("&")&&(wn.innerHTML=s,s=Sn?wn.textContent:wn.innerText),s.replace&&(s=s.replace(/[\r\n]/g,"")),a.push(s);l._aFilterData=a,l._sFilterRow=a.join(" "),f=!0}return f}function nt(e){return{search:e.sSearch,smart:e.bSmart,regex:e.bRegex,caseInsensitive:e.bCaseInsensitive}}function rt(e){return{sSearch:e.search,bSmart:e.smart,bRegex:e.regex,bCaseInsensitive:e.caseInsensitive}}function it(t){var n=t.sTableId,r=t.aanFeatures.i,i=e("<div/>",{"class":t.oClasses.sInfo,id:r?null:n+"_info"});return r||(t.aoDrawCallback.push({fn:ot,sName:"information"}),i.attr("role","status").attr("aria-live","polite"),e(t.nTable).attr("aria-describedby",n+"_info")),i[0]}function ot(t){var n=t.aanFeatures.i;if(0!==n.length){var r=t.oLanguage,i=t._iDisplayStart+1,o=t.fnDisplayEnd(),a=t.fnRecordsTotal(),s=t.fnRecordsDisplay(),l=s?r.sInfo:r.sInfoEmpty;s!==a&&(l+=" "+r.sInfoFiltered),l+=r.sInfoPostFix,l=at(t,l);var u=r.fnInfoCallback;null!==u&&(l=u.call(t.oInstance,t,i,o,a,s,l)),e(n).html(l)}}function at(e,t){var n=e.fnFormatNumber,r=e._iDisplayStart+1,i=e._iDisplayLength,o=e.fnRecordsDisplay(),a=-1===i;return t.replace(/_START_/g,n.call(e,r)).replace(/_END_/g,n.call(e,e.fnDisplayEnd())).replace(/_MAX_/g,n.call(e,e.fnRecordsTotal())).replace(/_TOTAL_/g,n.call(e,o)).replace(/_PAGE_/g,n.call(e,a?1:Math.ceil(r/i))).replace(/_PAGES_/g,n.call(e,a?1:Math.ceil(o/i)))}function st(e){var t,n,r,i=e.iInitDisplayStart,o=e.aoColumns,a=e.oFeatures;if(!e.bInitialised)return void setTimeout(function(){st(e)},200);for(W(e),O(e),R(e,e.aoHeader),R(e,e.aoFooter),pt(e,!0),a.bAutoWidth&&yt(e),t=0,n=o.length;n>t;t++)r=o[t],r.sWidth&&(r.nTh.style.width=Tt(r.sWidth));F(e);var s=Ut(e);"ssp"!=s&&("ajax"==s?q(e,[],function(n){var r=G(e,n);for(t=0;t<r.length;t++)x(e,r[t]);e.iInitDisplayStart=i,F(e),pt(e,!1),lt(e,n)},e):(pt(e,!1),lt(e)))}function lt(e,t){e._bInitComplete=!0,t&&h(e),zt(e,"aoInitComplete","init",[e,t])}function ut(e,t){var n=parseInt(t,10);e._iDisplayLength=n,Bt(e),zt(e,null,"length",[e,n])}function ct(t){for(var n=t.oClasses,r=t.sTableId,i=t.aLengthMenu,o=e.isArray(i[0]),a=o?i[0]:i,s=o?i[1]:i,l=e("<select/>",{name:r+"_length","aria-controls":r,"class":n.sLengthSelect}),u=0,c=a.length;c>u;u++)l[0][u]=new Option(s[u],a[u]);var f=e("<div><label/></div>").addClass(n.sLength);return t.aanFeatures.l||(f[0].id=r+"_length"),f.children().append(t.oLanguage.sLengthMenu.replace("_MENU_",l[0].outerHTML)),e("select",f).val(t._iDisplayLength).bind("change.DT",function(){ut(t,e(this).val()),P(t)}),e(t.nTable).bind("length.dt.DT",function(n,r,i){t===r&&e("select",f).val(i)}),f[0]}function ft(t){var n=t.sPaginationType,r=$t.ext.pager[n],i="function"==typeof r,o=function(e){P(e)},a=e("<div/>").addClass(t.oClasses.sPaging+n)[0],s=t.aanFeatures;return i||r.fnInit(t,a,o),s.p||(a.id=t.sTableId+"_paginate",t.aoDrawCallback.push({fn:function(e){if(i){var t,n,a=e._iDisplayStart,l=e._iDisplayLength,u=e.fnRecordsDisplay(),c=-1===l,f=c?0:Math.ceil(a/l),d=c?1:Math.ceil(u/l),h=r(f,d);for(t=0,n=s.p.length;n>t;t++)qt(e,"pageButton")(e,s.p[t],t,h,f,d)}else r.fnUpdate(e,o)},sName:"pagination"})),a}function dt(e,t,n){var r=e._iDisplayStart,i=e._iDisplayLength,o=e.fnRecordsDisplay();0===o||-1===i?r=0:"number"==typeof t?(r=t*i,r>o&&(r=0)):"first"==t?r=0:"previous"==t?(r=i>=0?r-i:0,0>r&&(r=0)):"next"==t?o>r+i&&(r+=i):"last"==t?r=Math.floor((o-1)/i)*i:Ot(e,0,"Unknown paging action: "+t,5);var a=e._iDisplayStart!==r;return e._iDisplayStart=r,a&&(zt(e,null,"page",[e]),n&&P(e)),a}function ht(t){return e("<div/>",{id:t.aanFeatures.r?null:t.sTableId+"_processing","class":t.oClasses.sProcessing}).html(t.oLanguage.sProcessing).insertBefore(t.nTable)[0]}function pt(t,n){t.oFeatures.bProcessing&&e(t.aanFeatures.r).css("display",n?"block":"none"),zt(t,null,"processing",[t,n])}function gt(t){var n=e(t.nTable);n.attr("role","grid");var r=t.oScroll;if(""===r.sX&&""===r.sY)return t.nTable;var i=r.sX,o=r.sY,a=t.oClasses,s=n.children("caption"),l=s.length?s[0]._captionSide:null,u=e(n[0].cloneNode(!1)),c=e(n[0].cloneNode(!1)),f=n.children("tfoot"),d="<div/>",h=function(e){return e?Tt(e):null};r.sX&&"100%"===n.attr("width")&&n.removeAttr("width"),f.length||(f=null);var p=e(d,{"class":a.sScrollWrapper}).append(e(d,{"class":a.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:i?h(i):"100%"}).append(e(d,{"class":a.sScrollHeadInner}).css({"box-sizing":"content-box",width:r.sXInner||"100%"}).append(u.removeAttr("id").css("margin-left",0).append(n.children("thead")))).append("top"===l?s:null)).append(e(d,{"class":a.sScrollBody}).css({overflow:"auto",height:h(o),width:h(i)}).append(n));f&&p.append(e(d,{"class":a.sScrollFoot}).css({overflow:"hidden",border:0,width:i?h(i):"100%"}).append(e(d,{"class":a.sScrollFootInner}).append(c.removeAttr("id").css("margin-left",0).append(n.children("tfoot")))).append("bottom"===l?s:null));var g=p.children(),m=g[0],v=g[1],y=f?g[2]:null;return i&&e(v).scroll(function(){var e=this.scrollLeft;m.scrollLeft=e,f&&(y.scrollLeft=e)}),t.nScrollHead=m,t.nScrollBody=v,t.nScrollFoot=y,t.aoDrawCallback.push({fn:mt,sName:"scrolling"}),p[0]}function mt(t){var n,r,i,o,a,s,l,u,c,f=t.oScroll,d=f.sX,h=f.sXInner,g=f.sY,m=f.iBarWidth,v=e(t.nScrollHead),y=v[0].style,b=v.children("div"),x=b[0].style,w=b.children("table"),S=t.nScrollBody,C=e(S),T=S.style,D=e(t.nScrollFoot),k=D.children("div"),L=k.children("table"),A=e(t.nTHead),N=e(t.nTable),_=N[0],M=_.style,E=t.nTFoot?e(t.nTFoot):null,j=t.oBrowser,I=j.bScrollOversize,H=[],O=[],R=[],P=function(e){var t=e.style;t.paddingTop="0",t.paddingBottom="0",t.borderTopWidth="0",t.borderBottomWidth="0",t.height=0};if(N.children("thead, tfoot").remove(),a=A.clone().prependTo(N),n=A.find("tr"),i=a.find("tr"),a.find("th, td").removeAttr("tabindex"),E&&(s=E.clone().prependTo(N),r=E.find("tr"),o=s.find("tr")),d||(T.width="100%",v[0].style.width="100%"),e.each(B(t,a),function(e,n){l=p(t,e),n.style.width=t.aoColumns[l].sWidth}),E&&vt(function(e){e.style.width=""},o),f.bCollapse&&""!==g&&(T.height=C[0].offsetHeight+A[0].offsetHeight+"px"),c=N.outerWidth(),""===d?(M.width="100%",I&&(N.find("tbody").height()>S.offsetHeight||"scroll"==C.css("overflow-y"))&&(M.width=Tt(N.outerWidth()-m))):""!==h?M.width=Tt(h):c==C.width()&&C.height()<N.height()?(M.width=Tt(c-m),N.outerWidth()>c-m&&(M.width=Tt(c))):M.width=Tt(c),c=N.outerWidth(),vt(P,i),vt(function(t){R.push(t.innerHTML),H.push(Tt(e(t).css("width")))},i),vt(function(e,t){e.style.width=H[t]},n),e(i).height(0),E&&(vt(P,o),vt(function(t){O.push(Tt(e(t).css("width")))},o),vt(function(e,t){e.style.width=O[t]},r),e(o).height(0)),vt(function(e,t){e.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+R[t]+"</div>",e.style.width=H[t]},i),E&&vt(function(e,t){e.innerHTML="",e.style.width=O[t]},o),N.outerWidth()<c?(u=S.scrollHeight>S.offsetHeight||"scroll"==C.css("overflow-y")?c+m:c,I&&(S.scrollHeight>S.offsetHeight||"scroll"==C.css("overflow-y"))&&(M.width=Tt(u-m)),(""===d||""!==h)&&Ot(t,1,"Possible column misalignment",6)):u="100%",T.width=Tt(u),y.width=Tt(u),E&&(t.nScrollFoot.style.width=Tt(u)),g||I&&(T.height=Tt(_.offsetHeight+m)),g&&f.bCollapse){T.height=Tt(g);var F=d&&_.offsetWidth>S.offsetWidth?m:0;_.offsetHeight<S.offsetHeight&&(T.height=Tt(_.offsetHeight+F))}var W=N.outerWidth();w[0].style.width=Tt(W),x.width=Tt(W);var z=N.height()>S.clientHeight||"scroll"==C.css("overflow-y"),q="padding"+(j.bScrollbarLeft?"Left":"Right"); x[q]=z?m+"px":"0px",E&&(L[0].style.width=Tt(W),k[0].style.width=Tt(W),k[0].style[q]=z?m+"px":"0px"),C.scroll(),!t.bSorted&&!t.bFiltered||t._drawHold||(S.scrollTop=0)}function vt(e,t,n){for(var r,i,o=0,a=0,s=t.length;s>a;){for(r=t[a].firstChild,i=n?n[a].firstChild:null;r;)1===r.nodeType&&(n?e(r,i,o):e(r,o),o++),r=r.nextSibling,i=n?i.nextSibling:null;a++}}function yt(t){var r,i,o,a,s,l=t.nTable,u=t.aoColumns,c=t.oScroll,f=c.sY,d=c.sX,p=c.sXInner,g=u.length,y=v(t,"bVisible"),b=e("th",t.nTHead),x=l.getAttribute("width"),w=l.parentNode,S=!1;for(r=0;r<y.length;r++)i=u[y[r]],null!==i.sWidth&&(i.sWidth=xt(i.sWidthOrig,w),S=!0);if(S||d||f||g!=m(t)||g!=b.length){var C=e(l).clone().empty().css("visibility","hidden").removeAttr("id").append(e(t.nTHead).clone(!1)).append(e(t.nTFoot).clone(!1)).append(e("<tbody><tr/></tbody>"));C.find("tfoot th, tfoot td").css("width","");var T=C.find("tbody tr");for(b=B(t,C.find("thead")[0]),r=0;r<y.length;r++)i=u[y[r]],b[r].style.width=null!==i.sWidthOrig&&""!==i.sWidthOrig?Tt(i.sWidthOrig):"";if(t.aoData.length)for(r=0;r<y.length;r++)o=y[r],i=u[o],e(St(t,o)).clone(!1).append(i.sContentPadding).appendTo(T);if(C.appendTo(w),d&&p?C.width(p):d?(C.css("width","auto"),C.width()<w.offsetWidth&&C.width(w.offsetWidth)):f?C.width(w.offsetWidth):x&&C.width(x),wt(t,C[0]),d){var D=0;for(r=0;r<y.length;r++)i=u[y[r]],s=e(b[r]).outerWidth(),D+=null===i.sWidthOrig?s:parseInt(i.sWidth,10)+s-e(b[r]).width();C.width(Tt(D)),l.style.width=Tt(D)}for(r=0;r<y.length;r++)i=u[y[r]],a=e(b[r]).width(),a&&(i.sWidth=Tt(a));l.style.width=Tt(C.css("width")),C.remove()}else for(r=0;g>r;r++)u[r].sWidth=Tt(b.eq(r).width());x&&(l.style.width=Tt(x)),!x&&!d||t._reszEvt||(e(n).bind("resize.DT-"+t.sInstance,bt(function(){h(t)})),t._reszEvt=!0)}function bt(e,t){var n,r,i=t||200;return function(){var t=this,a=+new Date,s=arguments;n&&n+i>a?(clearTimeout(r),r=setTimeout(function(){n=o,e.apply(t,s)},i)):n?(n=a,e.apply(t,s)):n=a}}function xt(t,n){if(!t)return 0;var r=e("<div/>").css("width",Tt(t)).appendTo(n||i.body),o=r[0].offsetWidth;return r.remove(),o}function wt(t,n){var r=t.oScroll;if(r.sX||r.sY){var i=r.sX?0:r.iBarWidth;n.style.width=Tt(e(n).outerWidth()-i)}}function St(t,n){var r=Ct(t,n);if(0>r)return null;var i=t.aoData[r];return i.nTr?i.anCells[n]:e("<td/>").html(T(t,r,n,"display"))[0]}function Ct(e,t){for(var n,r=-1,i=-1,o=0,a=e.aoData.length;a>o;o++)n=T(e,o,t,"display")+"",n=n.replace(Cn,""),n.length>r&&(r=n.length,i=o);return i}function Tt(e){return null===e?"0px":"number"==typeof e?0>e?"0px":e+"px":e.match(/\d$/)?e+"px":e}function Dt(){if(!$t.__scrollbarWidth){var t=e("<p/>").css({width:"100%",height:200,padding:0})[0],n=e("<div/>").css({position:"absolute",top:0,left:0,width:200,height:150,padding:0,overflow:"hidden",visibility:"hidden"}).append(t).appendTo("body"),r=t.offsetWidth;n.css("overflow","scroll");var i=t.offsetWidth;r===i&&(i=n[0].clientWidth),n.remove(),$t.__scrollbarWidth=r-i}return $t.__scrollbarWidth}function kt(t){var n,r,i,o,a,s,l,u=[],c=t.aoColumns,f=t.aaSortingFixed,d=e.isPlainObject(f),h=[],p=function(t){t.length&&!e.isArray(t[0])?h.push(t):h.push.apply(h,t)};for(e.isArray(f)&&p(f),d&&f.pre&&p(f.pre),p(t.aaSorting),d&&f.post&&p(f.post),n=0;n<h.length;n++)for(l=h[n][0],o=c[l].aDataSort,r=0,i=o.length;i>r;r++)a=o[r],s=c[a].sType||"string",u.push({src:l,col:a,dir:h[n][1],index:h[n][2],type:s,formatter:$t.ext.type.order[s+"-pre"]});return u}function Lt(e){var t,n,r,i,o,a=[],s=$t.ext.type.order,l=e.aoData,u=(e.aoColumns,0),c=e.aiDisplayMaster;for(y(e),o=kt(e),t=0,n=o.length;n>t;t++)i=o[t],i.formatter&&u++,Et(e,i.col);if("ssp"!=Ut(e)&&0!==o.length){for(t=0,r=c.length;r>t;t++)a[c[t]]=t;c.sort(u===o.length?function(e,t){var n,r,i,s,u,c=o.length,f=l[e]._aSortData,d=l[t]._aSortData;for(i=0;c>i;i++)if(u=o[i],n=f[u.col],r=d[u.col],s=r>n?-1:n>r?1:0,0!==s)return"asc"===u.dir?s:-s;return n=a[e],r=a[t],r>n?-1:n>r?1:0}:function(e,t){var n,r,i,u,c,f,d=o.length,h=l[e]._aSortData,p=l[t]._aSortData;for(i=0;d>i;i++)if(c=o[i],n=h[c.col],r=p[c.col],f=s[c.type+"-"+c.dir]||s["string-"+c.dir],u=f(n,r),0!==u)return u;return n=a[e],r=a[t],r>n?-1:n>r?1:0})}e.bSorted=!0}function At(e){for(var t,n,r=e.aoColumns,i=kt(e),o=e.oLanguage.oAria,a=0,s=r.length;s>a;a++){var l=r[a],u=l.asSorting,c=l.sTitle.replace(/<.*?>/g,""),f=l.nTh;f.removeAttribute("aria-sort"),l.bSortable?(i.length>0&&i[0].col==a?(f.setAttribute("aria-sort","asc"==i[0].dir?"ascending":"descending"),n=u[i[0].index+1]||u[0]):n=u[0],t=c+("asc"===n?o.sSortAscending:o.sSortDescending)):t=c,f.setAttribute("aria-label",t)}}function Nt(t,n,r,i){var a,s=t.aoColumns[n],l=t.aaSorting,u=s.asSorting,c=function(t){var n=t._idx;return n===o&&(n=e.inArray(t[1],u)),n+1>=u.length?0:n+1};if("number"==typeof l[0]&&(l=t.aaSorting=[l]),r&&t.oFeatures.bSortMulti){var f=e.inArray(n,hn(l,"0"));-1!==f?(a=c(l[f]),l[f][1]=u[a],l[f]._idx=a):(l.push([n,u[0],0]),l[l.length-1]._idx=0)}else l.length&&l[0][0]==n?(a=c(l[0]),l.length=1,l[0][1]=u[a],l[0]._idx=a):(l.length=0,l.push([n,u[0]]),l[0]._idx=0);F(t),"function"==typeof i&&i(t)}function _t(e,t,n,r){var i=e.aoColumns[n];Ft(t,{},function(t){i.bSortable!==!1&&(e.oFeatures.bProcessing?(pt(e,!0),setTimeout(function(){Nt(e,n,t.shiftKey,r),"ssp"!==Ut(e)&&pt(e,!1)},0)):Nt(e,n,t.shiftKey,r))})}function Mt(t){var n,r,i,o=t.aLastSort,a=t.oClasses.sSortColumn,s=kt(t),l=t.oFeatures;if(l.bSort&&l.bSortClasses){for(n=0,r=o.length;r>n;n++)i=o[n].src,e(hn(t.aoData,"anCells",i)).removeClass(a+(2>n?n+1:3));for(n=0,r=s.length;r>n;n++)i=s[n].src,e(hn(t.aoData,"anCells",i)).addClass(a+(2>n?n+1:3))}t.aLastSort=s}function Et(e,t){var n,r=e.aoColumns[t],i=$t.ext.order[r.sSortDataType];i&&(n=i.call(e.oInstance,e,t,g(e,t)));for(var o,a,s=$t.ext.type.order[r.sType+"-pre"],l=0,u=e.aoData.length;u>l;l++)o=e.aoData[l],o._aSortData||(o._aSortData=[]),(!o._aSortData[t]||i)&&(a=i?n[l]:T(e,l,t,"sort"),o._aSortData[t]=s?s(a):a)}function jt(t){if(t.oFeatures.bStateSave&&!t.bDestroying){var n={time:+new Date,start:t._iDisplayStart,length:t._iDisplayLength,order:e.extend(!0,[],t.aaSorting),search:nt(t.oPreviousSearch),columns:e.map(t.aoColumns,function(e,n){return{visible:e.bVisible,search:nt(t.aoPreSearchCols[n])}})};zt(t,"aoStateSaveParams","stateSaveParams",[t,n]),t.oSavedState=n,t.fnStateSaveCallback.call(t.oInstance,t,n)}}function It(t){var n,r,i=t.aoColumns;if(t.oFeatures.bStateSave){var o=t.fnStateLoadCallback.call(t.oInstance,t);if(o&&o.time){var a=zt(t,"aoStateLoadParams","stateLoadParams",[t,o]);if(-1===e.inArray(!1,a)){var s=t.iStateDuration;if(!(s>0&&o.time<+new Date-1e3*s)&&i.length===o.columns.length){for(t.oLoadedState=e.extend(!0,{},o),t._iDisplayStart=o.start,t.iInitDisplayStart=o.start,t._iDisplayLength=o.length,t.aaSorting=[],e.each(o.order,function(e,n){t.aaSorting.push(n[0]>=i.length?[0,n[1]]:n)}),e.extend(t.oPreviousSearch,rt(o.search)),n=0,r=o.columns.length;r>n;n++){var l=o.columns[n];i[n].bVisible=l.visible,e.extend(t.aoPreSearchCols[n],rt(l.search))}zt(t,"aoStateLoaded","stateLoaded",[t,o])}}}}}function Ht(t){var n=$t.settings,r=e.inArray(t,hn(n,"nTable"));return-1!==r?n[r]:null}function Ot(e,t,r,i){if(r="DataTables warning: "+(null!==e?"table id="+e.sTableId+" - ":"")+r,i&&(r+=". For more information about this error, please see http://datatables.net/tn/"+i),t)n.console&&console.log&&console.log(r);else{var o=$t.ext,a=o.sErrMode||o.errMode;if("alert"!=a)throw new Error(r);alert(r)}}function Rt(t,n,r,i){return e.isArray(r)?void e.each(r,function(r,i){e.isArray(i)?Rt(t,n,i[0],i[1]):Rt(t,n,i)}):(i===o&&(i=r),void(n[r]!==o&&(t[i]=n[r])))}function Pt(t,n,r){var i;for(var o in n)n.hasOwnProperty(o)&&(i=n[o],e.isPlainObject(i)?(e.isPlainObject(t[o])||(t[o]={}),e.extend(!0,t[o],i)):t[o]=r&&"data"!==o&&"aaData"!==o&&e.isArray(i)?i.slice():i);return t}function Ft(t,n,r){e(t).bind("click.DT",n,function(e){t.blur(),r(e)}).bind("keypress.DT",n,function(e){13===e.which&&(e.preventDefault(),r(e))}).bind("selectstart.DT",function(){return!1})}function Wt(e,t,n,r){n&&e[t].push({fn:n,sName:r})}function zt(t,n,r,i){var o=[];return n&&(o=e.map(t[n].slice().reverse(),function(e){return e.fn.apply(t.oInstance,i)})),null!==r&&e(t.nTable).trigger(r+".dt",i),o}function Bt(e){var t=e._iDisplayStart,n=e.fnDisplayEnd(),r=e._iDisplayLength;n===e.fnRecordsDisplay()&&(t=n-r),(-1===r||0>t)&&(t=0),e._iDisplayStart=t}function qt(t,n){var r=t.renderer,i=$t.ext.renderer[n];return e.isPlainObject(r)&&r[n]?i[r[n]]||i._:"string"==typeof r?i[r]||i._:i._}function Ut(e){return e.oFeatures.bServerSide?"ssp":e.ajax||e.sAjaxSource?"ajax":"dom"}function Vt(e,t){var n=[],r=Vn.numbers_length,i=Math.floor(r/2);return r>=t?n=gn(0,t):i>=e?(n=gn(0,r-2),n.push("ellipsis"),n.push(t-1)):e>=t-1-i?(n=gn(t-(r-2),t),n.splice(0,0,"ellipsis"),n.splice(0,0,0)):(n=gn(e-1,e+2),n.push("ellipsis"),n.push(t-1),n.splice(0,0,"ellipsis"),n.splice(0,0,0)),n.DT_el="span",n}function Xt(t){e.each({num:function(e){return Xn(e,t)},"num-fmt":function(e){return Xn(e,t,an)},"html-num":function(e){return Xn(e,t,tn)},"html-num-fmt":function(e){return Xn(e,t,tn,an)}},function(e,n){Jt.type.order[e+t+"-pre"]=n})}function Gt(e){return function(){var t=[Ht(this[$t.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return $t.ext.internal[e].apply(this,t)}}var $t,Jt,Yt,Kt,Qt,Zt={},en=/[\r\n]/g,tn=/<.*?>/g,nn=/^[\w\+\-]/,rn=/[\w\+\-]$/,on=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^","-"].join("|\\")+")","g"),an=/[',$£€¥%\u2009\u202F]/g,sn=function(e){return e&&e!==!0&&"-"!==e?!1:!0},ln=function(e){var t=parseInt(e,10);return!isNaN(t)&&isFinite(e)?t:null},un=function(e,t){return Zt[t]||(Zt[t]=new RegExp(et(t),"g")),"string"==typeof e?e.replace(/\./g,"").replace(Zt[t],"."):e},cn=function(e,t,n){var r="string"==typeof e;return t&&r&&(e=un(e,t)),n&&r&&(e=e.replace(an,"")),sn(e)||!isNaN(parseFloat(e))&&isFinite(e)},fn=function(e){return sn(e)||"string"==typeof e},dn=function(e,t,n){if(sn(e))return!0;var r=fn(e);return r&&cn(mn(e),t,n)?!0:null},hn=function(e,t,n){var r=[],i=0,a=e.length;if(n!==o)for(;a>i;i++)e[i]&&e[i][t]&&r.push(e[i][t][n]);else for(;a>i;i++)e[i]&&r.push(e[i][t]);return r},pn=function(e,t,n,r){var i=[],a=0,s=t.length;if(r!==o)for(;s>a;a++)i.push(e[t[a]][n][r]);else for(;s>a;a++)i.push(e[t[a]][n]);return i},gn=function(e,t){var n,r=[];t===o?(t=0,n=e):(n=t,t=e);for(var i=t;n>i;i++)r.push(i);return r},mn=function(e){return e.replace(tn,"")},vn=function(e){var t,n,r,i=[],o=e.length,a=0;e:for(n=0;o>n;n++){for(t=e[n],r=0;a>r;r++)if(i[r]===t)continue e;i.push(t),a++}return i},yn=function(e,t,n){e[t]!==o&&(e[n]=e[t])},bn=/\[.*?\]$/,xn=/\(\)$/,wn=e("<div>")[0],Sn=wn.textContent!==o,Cn=/<.*?>/g;$t=function(t){this.$=function(e,t){return this.api(!0).$(e,t)},this._=function(e,t){return this.api(!0).rows(e,t).data()},this.api=function(e){return new Yt(e?Ht(this[Jt.iApiIndex]):this)},this.fnAddData=function(t,n){var r=this.api(!0),i=e.isArray(t)&&(e.isArray(t[0])||e.isPlainObject(t[0]))?r.rows.add(t):r.row.add(t);return(n===o||n)&&r.draw(),i.flatten().toArray()},this.fnAdjustColumnSizing=function(e){var t=this.api(!0).columns.adjust(),n=t.settings()[0],r=n.oScroll;e===o||e?t.draw(!1):(""!==r.sX||""!==r.sY)&&mt(n)},this.fnClearTable=function(e){var t=this.api(!0).clear();(e===o||e)&&t.draw()},this.fnClose=function(e){this.api(!0).row(e).child.hide()},this.fnDeleteRow=function(e,t,n){var r=this.api(!0),i=r.rows(e),a=i.settings()[0],s=a.aoData[i[0][0]];return i.remove(),t&&t.call(this,a,s),(n===o||n)&&r.draw(),s},this.fnDestroy=function(e){this.api(!0).destroy(e)},this.fnDraw=function(e){this.api(!0).draw(!e)},this.fnFilter=function(e,t,n,r,i,a){var s=this.api(!0);null===t||t===o?s.search(e,n,r,a):s.column(t).search(e,n,r,a),s.draw()},this.fnGetData=function(e,t){var n=this.api(!0);if(e!==o){var r=e.nodeName?e.nodeName.toLowerCase():"";return t!==o||"td"==r||"th"==r?n.cell(e,t).data():n.row(e).data()||null}return n.data().toArray()},this.fnGetNodes=function(e){var t=this.api(!0);return e!==o?t.row(e).node():t.rows().nodes().flatten().toArray()},this.fnGetPosition=function(e){var t=this.api(!0),n=e.nodeName.toUpperCase();if("TR"==n)return t.row(e).index();if("TD"==n||"TH"==n){var r=t.cell(e).index();return[r.row,r.columnVisible,r.column]}return null},this.fnIsOpen=function(e){return this.api(!0).row(e).child.isShown()},this.fnOpen=function(e,t,n){return this.api(!0).row(e).child(t,n).show().child()[0]},this.fnPageChange=function(e,t){var n=this.api(!0).page(e);(t===o||t)&&n.draw(!1)},this.fnSetColumnVis=function(e,t,n){var r=this.api(!0).column(e).visible(t);(n===o||n)&&r.columns.adjust().draw()},this.fnSettings=function(){return Ht(this[Jt.iApiIndex])},this.fnSort=function(e){this.api(!0).order(e).draw()},this.fnSortListener=function(e,t,n){this.api(!0).order.listener(e,t,n)},this.fnUpdate=function(e,t,n,r,i){var a=this.api(!0);return n===o||null===n?a.row(t).data(e):a.cell(t,n).data(e),(i===o||i)&&a.columns.adjust(),(r===o||r)&&a.draw(),0},this.fnVersionCheck=Jt.fnVersionCheck;var n=this,i=t===o,c=this.length;i&&(t={}),this.oApi=this.internal=Jt.internal;for(var h in $t.ext.internal)h&&(this[h]=Gt(h));return this.each(function(){var h,p={},g=c>1?Pt(p,t,!0):t,m=0,v=this.getAttribute("id"),y=!1,S=$t.defaults;if("table"!=this.nodeName.toLowerCase())return void Ot(null,0,"Non-table node initialisation ("+this.nodeName+")",2);s(S),l(S.column),r(S,S,!0),r(S.column,S.column,!0),r(S,g);var C=$t.settings;for(m=0,h=C.length;h>m;m++){if(C[m].nTable==this){var T=g.bRetrieve!==o?g.bRetrieve:S.bRetrieve,D=g.bDestroy!==o?g.bDestroy:S.bDestroy;if(i||T)return C[m].oInstance;if(D){C[m].oInstance.fnDestroy();break}return void Ot(C[m],0,"Cannot reinitialise DataTable",3)}if(C[m].sTableId==this.id){C.splice(m,1);break}}(null===v||""===v)&&(v="DataTables_Table_"+$t.ext._unique++,this.id=v);var k=e.extend(!0,{},$t.models.oSettings,{nTable:this,oApi:n.internal,oInit:g,sDestroyWidth:e(this)[0].style.width,sInstance:v,sTableId:v});C.push(k),k.oInstance=1===n.length?n:e(this).dataTable(),s(g),g.oLanguage&&a(g.oLanguage),g.aLengthMenu&&!g.iDisplayLength&&(g.iDisplayLength=e.isArray(g.aLengthMenu[0])?g.aLengthMenu[0][0]:g.aLengthMenu[0]),g=Pt(e.extend(!0,{},S),g),Rt(k.oFeatures,g,["bPaginate","bLengthChange","bFilter","bSort","bSortMulti","bInfo","bProcessing","bAutoWidth","bSortClasses","bServerSide","bDeferRender"]),Rt(k,g,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback","renderer",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]),Rt(k.oScroll,g,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]),Rt(k.oLanguage,g,"fnInfoCallback"),Wt(k,"aoDrawCallback",g.fnDrawCallback,"user"),Wt(k,"aoServerParams",g.fnServerParams,"user"),Wt(k,"aoStateSaveParams",g.fnStateSaveParams,"user"),Wt(k,"aoStateLoadParams",g.fnStateLoadParams,"user"),Wt(k,"aoStateLoaded",g.fnStateLoaded,"user"),Wt(k,"aoRowCallback",g.fnRowCallback,"user"),Wt(k,"aoRowCreatedCallback",g.fnCreatedRow,"user"),Wt(k,"aoHeaderCallback",g.fnHeaderCallback,"user"),Wt(k,"aoFooterCallback",g.fnFooterCallback,"user"),Wt(k,"aoInitComplete",g.fnInitComplete,"user"),Wt(k,"aoPreDrawCallback",g.fnPreDrawCallback,"user");var L=k.oClasses;if(g.bJQueryUI?(e.extend(L,$t.ext.oJUIClasses,g.oClasses),g.sDom===S.sDom&&"lfrtip"===S.sDom&&(k.sDom='<"H"lfr>t<"F"ip>'),k.renderer?e.isPlainObject(k.renderer)&&!k.renderer.header&&(k.renderer.header="jqueryui"):k.renderer="jqueryui"):e.extend(L,$t.ext.classes,g.oClasses),e(this).addClass(L.sTable),(""!==k.oScroll.sX||""!==k.oScroll.sY)&&(k.oScroll.iBarWidth=Dt()),k.oScroll.sX===!0&&(k.oScroll.sX="100%"),k.iInitDisplayStart===o&&(k.iInitDisplayStart=g.iDisplayStart,k._iDisplayStart=g.iDisplayStart),null!==g.iDeferLoading){k.bDeferLoading=!0;var A=e.isArray(g.iDeferLoading);k._iRecordsDisplay=A?g.iDeferLoading[0]:g.iDeferLoading,k._iRecordsTotal=A?g.iDeferLoading[1]:g.iDeferLoading}""!==g.oLanguage.sUrl?(k.oLanguage.sUrl=g.oLanguage.sUrl,e.getJSON(k.oLanguage.sUrl,null,function(t){a(t),r(S.oLanguage,t),e.extend(!0,k.oLanguage,g.oLanguage,t),st(k)}),y=!0):e.extend(!0,k.oLanguage,g.oLanguage),null===g.asStripeClasses&&(k.asStripeClasses=[L.sStripeOdd,L.sStripeEven]);var N=k.asStripeClasses,_=e("tbody tr:eq(0)",this);-1!==e.inArray(!0,e.map(N,function(e){return _.hasClass(e)}))&&(e("tbody tr",this).removeClass(N.join(" ")),k.asDestroyStripes=N.slice());var M,E=[],I=this.getElementsByTagName("thead");if(0!==I.length&&(z(k.aoHeader,I[0]),E=B(k)),null===g.aoColumns)for(M=[],m=0,h=E.length;h>m;m++)M.push(null);else M=g.aoColumns;for(m=0,h=M.length;h>m;m++)f(k,E?E[m]:null);if(b(k,g.aoColumnDefs,M,function(e,t){d(k,e,t)}),_.length){var H=function(e,t){return e.getAttribute("data-"+t)?t:null};e.each(j(k,_[0]).cells,function(e,t){var n=k.aoColumns[e];if(n.mData===e){var r=H(t,"sort")||H(t,"order"),i=H(t,"filter")||H(t,"search");(null!==r||null!==i)&&(n.mData={_:e+".display",sort:null!==r?e+".@data-"+r:o,type:null!==r?e+".@data-"+r:o,filter:null!==i?e+".@data-"+i:o},d(k,e))}})}var O=k.oFeatures;if(g.bStateSave&&(O.bStateSave=!0,It(k,g),Wt(k,"aoDrawCallback",jt,"state_save")),g.aaSorting===o){var R=k.aaSorting;for(m=0,h=R.length;h>m;m++)R[m][1]=k.aoColumns[m].asSorting[0]}Mt(k),O.bSort&&Wt(k,"aoDrawCallback",function(){if(k.bSorted){var t=kt(k),n={};e.each(t,function(e,t){n[t.src]=t.dir}),zt(k,null,"order",[k,t,n]),At(k)}}),Wt(k,"aoDrawCallback",function(){(k.bSorted||"ssp"===Ut(k)||O.bDeferRender)&&Mt(k)},"sc"),u(k);var P=e(this).children("caption").each(function(){this._captionSide=e(this).css("caption-side")}),F=e(this).children("thead");0===F.length&&(F=e("<thead/>").appendTo(this)),k.nTHead=F[0];var W=e(this).children("tbody");0===W.length&&(W=e("<tbody/>").appendTo(this)),k.nTBody=W[0];var q=e(this).children("tfoot");if(0===q.length&&P.length>0&&(""!==k.oScroll.sX||""!==k.oScroll.sY)&&(q=e("<tfoot/>").appendTo(this)),0===q.length||0===q.children().length?e(this).addClass(L.sNoFooter):q.length>0&&(k.nTFoot=q[0],z(k.aoFooter,k.nTFoot)),g.aaData)for(m=0;m<g.aaData.length;m++)x(k,g.aaData[m]);else(k.bDeferLoading||"dom"==Ut(k))&&w(k,e(k.nTBody).children("tr"));k.aiDisplay=k.aiDisplayMaster.slice(),k.bInitialised=!0,y===!1&&st(k)}),n=null,this};var Tn=[],Dn=Array.prototype,kn=function(t){var n,r,i=$t.settings,o=e.map(i,function(e){return e.nTable});return t?t.nTable&&t.oApi?[t]:t.nodeName&&"table"===t.nodeName.toLowerCase()?(n=e.inArray(t,o),-1!==n?[i[n]]:null):t&&"function"==typeof t.settings?t.settings().toArray():("string"==typeof t?r=e(t):t instanceof e&&(r=t),r?r.map(function(){return n=e.inArray(this,o),-1!==n?i[n]:null}).toArray():void 0):[]};Yt=function(t,n){if(!this instanceof Yt)throw"DT API must be constructed as a new object";var r=[],i=function(e){var t=kn(e);t&&r.push.apply(r,t)};if(e.isArray(t))for(var o=0,a=t.length;a>o;o++)i(t[o]);else i(t);this.context=vn(r),n&&this.push.apply(this,n.toArray?n.toArray():n),this.selector={rows:null,cols:null,opts:null},Yt.extend(this,this,Tn)},$t.Api=Yt,Yt.prototype={concat:Dn.concat,context:[],each:function(e){for(var t=0,n=this.length;n>t;t++)e.call(this,this[t],t,this);return this},eq:function(e){var t=this.context;return t.length>e?new Yt(t[e],this[e]):null},filter:function(e){var t=[];if(Dn.filter)t=Dn.filter.call(this,e,this);else for(var n=0,r=this.length;r>n;n++)e.call(this,this[n],n,this)&&t.push(this[n]);return new Yt(this.context,t)},flatten:function(){var e=[];return new Yt(this.context,e.concat.apply(e,this.toArray()))},join:Dn.join,indexOf:Dn.indexOf||function(e,t){for(var n=t||0,r=this.length;r>n;n++)if(this[n]===e)return n;return-1},iterator:function(e,t,n){var r,i,a,s,l,u,c,f,d=[],h=this.context,p=this.selector;for("string"==typeof e&&(n=t,t=e,e=!1),i=0,a=h.length;a>i;i++)if("table"===t)r=n(h[i],i),r!==o&&d.push(r);else if("columns"===t||"rows"===t)r=n(h[i],this[i],i),r!==o&&d.push(r);else if("column"===t||"column-rows"===t||"row"===t||"cell"===t)for(c=this[i],"column-rows"===t&&(u=En(h[i],p.opts)),s=0,l=c.length;l>s;s++)f=c[s],r="cell"===t?n(h[i],f.row,f.column,i,s):n(h[i],f,i,s,u),r!==o&&d.push(r);if(d.length){var g=new Yt(h,e?d.concat.apply([],d):d),m=g.selector;return m.rows=p.rows,m.cols=p.cols,m.opts=p.opts,g}return this},lastIndexOf:Dn.lastIndexOf||function(){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(e){var t=[];if(Dn.map)t=Dn.map.call(this,e,this);else for(var n=0,r=this.length;r>n;n++)t.push(e.call(this,this[n],n));return new Yt(this.context,t)},pluck:function(e){return this.map(function(t){return t[e]})},pop:Dn.pop,push:Dn.push,reduce:Dn.reduce||function(e,t){return c(this,e,t,0,this.length,1)},reduceRight:Dn.reduceRight||function(e,t){return c(this,e,t,this.length-1,-1,-1)},reverse:Dn.reverse,selector:null,shift:Dn.shift,sort:Dn.sort,splice:Dn.splice,toArray:function(){return Dn.slice.call(this)},to$:function(){return e(this)},toJQuery:function(){return e(this)},unique:function(){return new Yt(this.context,vn(this))},unshift:Dn.unshift},Yt.extend=function(t,n,r){if(n&&(n instanceof Yt||n.__dt_wrapper)){var i,o,a,s=function(e,t,n){return function(){var r=t.apply(e,arguments);return Yt.extend(r,r,n.methodExt),r}};for(i=0,o=r.length;o>i;i++)a=r[i],n[a.name]="function"==typeof a.val?s(t,a.val,a):e.isPlainObject(a.val)?{}:a.val,n[a.name].__dt_wrapper=!0,Yt.extend(t,n[a.name],a.propExt)}},Yt.register=Kt=function(t,n){if(e.isArray(t))for(var r=0,i=t.length;i>r;r++)Yt.register(t[r],n);else{var o,a,s,l,u=t.split("."),c=Tn,f=function(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n].name===t)return e[n];return null};for(o=0,a=u.length;a>o;o++){l=-1!==u[o].indexOf("()"),s=l?u[o].replace("()",""):u[o];var d=f(c,s);d||(d={name:s,val:{},methodExt:[],propExt:[]},c.push(d)),o===a-1?d.val=n:c=l?d.methodExt:d.propExt}}},Yt.registerPlural=Qt=function(t,n,r){Yt.register(t,r),Yt.register(n,function(){var t=r.apply(this,arguments);return t===this?this:t instanceof Yt?t.length?e.isArray(t[0])?new Yt(t.context,t[0]):t[0]:o:t})};var Ln=function(t,n){if("number"==typeof t)return[n[t]];var r=e.map(n,function(e){return e.nTable});return e(r).filter(t).map(function(){var t=e.inArray(this,r);return n[t]}).toArray()};Kt("tables()",function(e){return e?new Yt(Ln(e,this.context)):this}),Kt("table()",function(e){var t=this.tables(e),n=t.context;return n.length?new Yt(n[0]):t}),Qt("tables().nodes()","table().node()",function(){return this.iterator("table",function(e){return e.nTable})}),Qt("tables().body()","table().body()",function(){return this.iterator("table",function(e){return e.nTBody})}),Qt("tables().header()","table().header()",function(){return this.iterator("table",function(e){return e.nTHead})}),Qt("tables().footer()","table().footer()",function(){return this.iterator("table",function(e){return e.nTFoot})}),Qt("tables().containers()","table().container()",function(){return this.iterator("table",function(e){return e.nTableWrapper})}),Kt("draw()",function(e){return this.iterator("table",function(t){F(t,e===!1)})}),Kt("page()",function(e){return e===o?this.page.info().page:this.iterator("table",function(t){dt(t,e)})}),Kt("page.info()",function(){if(0===this.context.length)return o;var e=this.context[0],t=e._iDisplayStart,n=e._iDisplayLength,r=e.fnRecordsDisplay(),i=-1===n;return{page:i?0:Math.floor(t/n),pages:i?1:Math.ceil(r/n),start:t,end:e.fnDisplayEnd(),length:n,recordsTotal:e.fnRecordsTotal(),recordsDisplay:r}}),Kt("page.len()",function(e){return e===o?0!==this.context.length?this.context[0]._iDisplayLength:o:this.iterator("table",function(t){ut(t,e)})});var An=function(e,t,n){if("ssp"==Ut(e)?F(e,t):(pt(e,!0),q(e,[],function(n){_(e);for(var r=G(e,n),i=0,o=r.length;o>i;i++)x(e,r[i]);F(e,t),pt(e,!1)})),n){var r=new Yt(e);r.one("draw",function(){n(r.ajax.json())})}};Kt("ajax.json()",function(){var e=this.context;return e.length>0?e[0].json:void 0}),Kt("ajax.params()",function(){var e=this.context;return e.length>0?e[0].oAjaxData:void 0}),Kt("ajax.reload()",function(e,t){return this.iterator("table",function(n){An(n,t===!1,e)})}),Kt("ajax.url()",function(t){var n=this.context;return t===o?0===n.length?o:(n=n[0],n.ajax?e.isPlainObject(n.ajax)?n.ajax.url:n.ajax:n.sAjaxSource):this.iterator("table",function(n){e.isPlainObject(n.ajax)?n.ajax.url=t:n.ajax=t})}),Kt("ajax.url().load()",function(e,t){return this.iterator("table",function(n){An(n,t===!1,e)})});var Nn=function(t,n){var r,i,a,s,l,u,c=[];for(t&&"string"!=typeof t&&t.length!==o||(t=[t]),a=0,s=t.length;s>a;a++)for(i=t[a]&&t[a].split?t[a].split(","):[t[a]],l=0,u=i.length;u>l;l++)r=n("string"==typeof i[l]?e.trim(i[l]):i[l]),r&&r.length&&c.push.apply(c,r);return c},_n=function(e){return e||(e={}),e.filter&&!e.search&&(e.search=e.filter),{search:e.search||"none",order:e.order||"current",page:e.page||"all"}},Mn=function(e){for(var t=0,n=e.length;n>t;t++)if(e[t].length>0)return e[0]=e[t],e.length=1,e.context=[e.context[t]],e;return e.length=0,e},En=function(t,n){var r,i,o,a=[],s=t.aiDisplay,l=t.aiDisplayMaster,u=n.search,c=n.order,f=n.page;if("ssp"==Ut(t))return"removed"===u?[]:gn(0,l.length);if("current"==f)for(r=t._iDisplayStart,i=t.fnDisplayEnd();i>r;r++)a.push(s[r]);else if("current"==c||"applied"==c)a="none"==u?l.slice():"applied"==u?s.slice():e.map(l,function(t){return-1===e.inArray(t,s)?t:null});else if("index"==c||"original"==c)for(r=0,i=t.aoData.length;i>r;r++)"none"==u?a.push(r):(o=e.inArray(r,s),(-1===o&&"removed"==u||o>=0&&"applied"==u)&&a.push(r));return a},jn=function(t,n,r){return Nn(n,function(n){var i=ln(n);if(null!==i&&!r)return[i];var o=En(t,r);if(null!==i&&-1!==e.inArray(i,o))return[i];if(!n)return o;for(var a=[],s=0,l=o.length;l>s;s++)a.push(t.aoData[o[s]].nTr);return n.nodeName&&-1!==e.inArray(n,a)?[n._DT_RowIndex]:e(a).filter(n).map(function(){return this._DT_RowIndex}).toArray()})};Kt("rows()",function(t,n){t===o?t="":e.isPlainObject(t)&&(n=t,t=""),n=_n(n);var r=this.iterator("table",function(e){return jn(e,t,n)});return r.selector.rows=t,r.selector.opts=n,r}),Kt("rows().nodes()",function(){return this.iterator("row",function(e,t){return e.aoData[t].nTr||o})}),Kt("rows().data()",function(){return this.iterator(!0,"rows",function(e,t){return pn(e.aoData,t,"_aData")})}),Qt("rows().cache()","row().cache()",function(e){return this.iterator("row",function(t,n){var r=t.aoData[n];return"search"===e?r._aFilterData:r._aSortData})}),Qt("rows().invalidate()","row().invalidate()",function(e){return this.iterator("row",function(t,n){E(t,n,e)})}),Qt("rows().indexes()","row().index()",function(){return this.iterator("row",function(e,t){return t})}),Qt("rows().remove()","row().remove()",function(){var t=this;return this.iterator("row",function(n,r,i){var o=n.aoData;o.splice(r,1);for(var a=0,s=o.length;s>a;a++)null!==o[a].nTr&&(o[a].nTr._DT_RowIndex=a);e.inArray(r,n.aiDisplay);M(n.aiDisplayMaster,r),M(n.aiDisplay,r),M(t[i],r,!1),Bt(n)})}),Kt("rows.add()",function(e){var t=this.iterator("table",function(t){var n,r,i,o=[];for(r=0,i=e.length;i>r;r++)n=e[r],o.push(n.nodeName&&"TR"===n.nodeName.toUpperCase()?w(t,n)[0]:x(t,n));return o}),n=this.rows(-1);return n.pop(),n.push.apply(n,t.toArray()),n}),Kt("row()",function(e,t){return Mn(this.rows(e,t))}),Kt("row().data()",function(e){var t=this.context;return e===o?t.length&&this.length?t[0].aoData[this[0]]._aData:o:(t[0].aoData[this[0]]._aData=e,E(t[0],this[0],"data"),this)}),Kt("row().node()",function(){var e=this.context;return e.length&&this.length?e[0].aoData[this[0]].nTr||null:null}),Kt("row.add()",function(t){t instanceof e&&t.length&&(t=t[0]);var n=this.iterator("table",function(e){return t.nodeName&&"TR"===t.nodeName.toUpperCase()?w(e,t)[0]:x(e,t)});return this.row(n[0])});var In=function(t,n,r,i){var o=[],a=function(n,r){if(n.nodeName&&"tr"===n.nodeName.toLowerCase())o.push(n);else{var i=e("<tr><td/></tr>").addClass(r);e("td",i).addClass(r).html(n)[0].colSpan=m(t),o.push(i[0])}};if(e.isArray(r)||r instanceof e)for(var s=0,l=r.length;l>s;s++)a(r[s],i);else a(r,i);n._details&&n._details.remove(),n._details=e(o),n._detailsShow&&n._details.insertAfter(n.nTr)},Hn=function(e){var t=e.context;if(t.length&&e.length){var n=t[0].aoData[e[0]];n._details&&(n._details.remove(),n._detailsShow=o,n._details=o)}},On=function(e,t){var n=e.context;if(n.length&&e.length){var r=n[0].aoData[e[0]];r._details&&(r._detailsShow=t,t?r._details.insertAfter(r.nTr):r._details.detach(),Rn(n[0]))}},Rn=function(e){var t=new Yt(e),n=".dt.DT_details",r="draw"+n,i="column-visibility"+n,o="destroy"+n,a=e.aoData;t.off(r+" "+i+" "+o),hn(a,"_details").length>0&&(t.on(r,function(n,r){e===r&&t.rows({page:"current"}).eq(0).each(function(e){var t=a[e];t._detailsShow&&t._details.insertAfter(t.nTr)})}),t.on(i,function(t,n){if(e===n)for(var r,i=m(n),o=0,s=a.length;s>o;o++)r=a[o],r._details&&r._details.children("td[colspan]").attr("colspan",i)}),t.on(o,function(t,n){if(e===n)for(var r=0,i=a.length;i>r;r++)a[r]._details&&Hn(a[r])}))},Pn="",Fn=Pn+"row().child",Wn=Fn+"()";Kt(Wn,function(e,t){var n=this.context;return e===o?n.length&&this.length?n[0].aoData[this[0]]._details:o:(e===!0?this.child.show():e===!1?Hn(this):n.length&&this.length&&In(n[0],n[0].aoData[this[0]],e,t),this)}),Kt([Fn+".show()",Wn+".show()"],function(){return On(this,!0),this}),Kt([Fn+".hide()",Wn+".hide()"],function(){return On(this,!1),this}),Kt([Fn+".remove()",Wn+".remove()"],function(){return Hn(this),this}),Kt(Fn+".isShown()",function(){var e=this.context;return e.length&&this.length?e[0].aoData[this[0]]._detailsShow||!1:!1});var zn=/^(.+):(name|visIdx|visible)$/,Bn=function(t,n){var r=t.aoColumns,i=hn(r,"sName"),o=hn(r,"nTh");return Nn(n,function(n){var a=ln(n);if(""===n)return gn(r.length);if(null!==a)return[a>=0?a:r.length+a];var s="string"==typeof n?n.match(zn):"";if(!s)return e(o).filter(n).map(function(){return e.inArray(this,o)}).toArray();switch(s[2]){case"visIdx":case"visible":var l=parseInt(s[1],10);if(0>l){var u=e.map(r,function(e,t){return e.bVisible?t:null});return[u[u.length+l]]}return[p(t,l)];case"name":return e.map(i,function(e,t){return e===s[1]?t:null})}})},qn=function(t,n,r,i){var a,s,l,u,c=t.aoColumns,f=c[n],d=t.aoData;if(r===o)return f.bVisible;if(f.bVisible!==r){if(r){var p=e.inArray(!0,hn(c,"bVisible"),n+1);for(s=0,l=d.length;l>s;s++)u=d[s].nTr,a=d[s].anCells,u&&u.insertBefore(a[n],a[p]||null)}else e(hn(t.aoData,"anCells",n)).detach();f.bVisible=r,R(t,t.aoHeader),R(t,t.aoFooter),(i===o||i)&&(h(t),(t.oScroll.sX||t.oScroll.sY)&&mt(t)),zt(t,null,"column-visibility",[t,n,r]),jt(t)}};Kt("columns()",function(t,n){t===o?t="":e.isPlainObject(t)&&(n=t,t=""),n=_n(n);var r=this.iterator("table",function(e){return Bn(e,t,n)});return r.selector.cols=t,r.selector.opts=n,r}),Qt("columns().header()","column().header()",function(){return this.iterator("column",function(e,t){return e.aoColumns[t].nTh})}),Qt("columns().footer()","column().footer()",function(){return this.iterator("column",function(e,t){return e.aoColumns[t].nTf})}),Qt("columns().data()","column().data()",function(){return this.iterator("column-rows",function(e,t,n,r,i){for(var o=[],a=0,s=i.length;s>a;a++)o.push(T(e,i[a],t,""));return o})}),Qt("columns().cache()","column().cache()",function(e){return this.iterator("column-rows",function(t,n,r,i,o){return pn(t.aoData,o,"search"===e?"_aFilterData":"_aSortData",n)})}),Qt("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(e,t,n,r,i){return pn(e.aoData,i,"anCells",t)})}),Qt("columns().visible()","column().visible()",function(e,t){return this.iterator("column",function(n,r){return e===o?n.aoColumns[r].bVisible:qn(n,r,e,t)})}),Qt("columns().indexes()","column().index()",function(e){return this.iterator("column",function(t,n){return"visible"===e?g(t,n):n})}),Kt("columns.adjust()",function(){return this.iterator("table",function(e){h(e)})}),Kt("column.index()",function(e,t){if(0!==this.context.length){var n=this.context[0]; if("fromVisible"===e||"toData"===e)return p(n,t);if("fromData"===e||"toVisible"===e)return g(n,t)}}),Kt("column()",function(e,t){return Mn(this.columns(e,t))});var Un=function(t,n,r){var i,a,s,l,u,c=t.aoData,f=En(t,r),d=pn(c,f,"anCells"),h=e([].concat.apply([],d)),p=t.aoColumns.length;return Nn(n,function(t){if(null===t||t===o){for(a=[],s=0,l=f.length;l>s;s++)for(i=f[s],u=0;p>u;u++)a.push({row:i,column:u});return a}return e.isPlainObject(t)?[t]:h.filter(t).map(function(t,n){return i=n.parentNode._DT_RowIndex,{row:i,column:e.inArray(n,c[i].anCells)}}).toArray()})};Kt("cells()",function(t,n,r){if(e.isPlainObject(t)&&(typeof t.row!==o?(r=n,n=null):(r=t,t=null)),e.isPlainObject(n)&&(r=n,n=null),null===n||n===o)return this.iterator("table",function(e){return Un(e,t,_n(r))});var i,a,s,l,u,c=this.columns(n,r),f=this.rows(t,r),d=this.iterator("table",function(e,t){for(i=[],a=0,s=f[t].length;s>a;a++)for(l=0,u=c[t].length;u>l;l++)i.push({row:f[t][a],column:c[t][l]});return i});return e.extend(d.selector,{cols:n,rows:t,opts:r}),d}),Qt("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(e,t,n){return e.aoData[t].anCells[n]})}),Kt("cells().data()",function(){return this.iterator("cell",function(e,t,n){return T(e,t,n)})}),Qt("cells().cache()","cell().cache()",function(e){return e="search"===e?"_aFilterData":"_aSortData",this.iterator("cell",function(t,n,r){return t.aoData[n][e][r]})}),Qt("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(e,t,n){return{row:t,column:n,columnVisible:g(e,n)}})}),Kt(["cells().invalidate()","cell().invalidate()"],function(e){var t=this.selector;return this.rows(t.rows,t.opts).invalidate(e),this}),Kt("cell()",function(e,t,n){return Mn(this.cells(e,t,n))}),Kt("cell().data()",function(e){var t=this.context,n=this[0];return e===o?t.length&&n.length?T(t[0],n[0].row,n[0].column):o:(D(t[0],n[0].row,n[0].column,e),E(t[0],n[0].row,"data",n[0].column),this)}),Kt("order()",function(t,n){var r=this.context;return t===o?0!==r.length?r[0].aaSorting:o:("number"==typeof t?t=[[t,n]]:e.isArray(t[0])||(t=Array.prototype.slice.call(arguments)),this.iterator("table",function(e){e.aaSorting=t.slice()}))}),Kt("order.listener()",function(e,t,n){return this.iterator("table",function(r){_t(r,e,t,n)})}),Kt(["columns().order()","column().order()"],function(t){var n=this;return this.iterator("table",function(r,i){var o=[];e.each(n[i],function(e,n){o.push([n,t])}),r.aaSorting=o})}),Kt("search()",function(t,n,r,i){var a=this.context;return t===o?0!==a.length?a[0].oPreviousSearch.sSearch:o:this.iterator("table",function(o){o.oFeatures.bFilter&&J(o,e.extend({},o.oPreviousSearch,{sSearch:t+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i}),1)})}),Qt("columns().search()","column().search()",function(t,n,r,i){return this.iterator("column",function(a,s){var l=a.aoPreSearchCols;return t===o?l[s].sSearch:void(a.oFeatures.bFilter&&(e.extend(l[s],{sSearch:t+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i}),J(a,a.oPreviousSearch,1)))})}),Kt("state()",function(){return this.context.length?this.context[0].oSavedState:null}),Kt("state.clear()",function(){return this.iterator("table",function(e){e.fnStateSaveCallback.call(e.oInstance,e,{})})}),Kt("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null}),Kt("state.save()",function(){return this.iterator("table",function(e){jt(e)})}),$t.versionCheck=$t.fnVersionCheck=function(e){for(var t,n,r=$t.version.split("."),i=e.split("."),o=0,a=i.length;a>o;o++)if(t=parseInt(r[o],10)||0,n=parseInt(i[o],10)||0,t!==n)return t>n;return!0},$t.isDataTable=$t.fnIsDataTable=function(t){var n=e(t).get(0),r=!1;return e.each($t.settings,function(e,t){(t.nTable===n||t.nScrollHead===n||t.nScrollFoot===n)&&(r=!0)}),r},$t.tables=$t.fnTables=function(t){return jQuery.map($t.settings,function(n){return!t||t&&e(n.nTable).is(":visible")?n.nTable:void 0})},$t.camelToHungarian=r,Kt("$()",function(t,n){var r=this.rows(n).nodes(),i=e(r);return e([].concat(i.filter(t).toArray(),i.find(t).toArray()))}),e.each(["on","one","off"],function(t,n){Kt(n+"()",function(){var t=Array.prototype.slice.call(arguments);t[0].match(/\.dt\b/)||(t[0]+=".dt");var r=e(this.tables().nodes());return r[n].apply(r,t),this})}),Kt("clear()",function(){return this.iterator("table",function(e){_(e)})}),Kt("settings()",function(){return new Yt(this.context,this.context)}),Kt("data()",function(){return this.iterator("table",function(e){return hn(e.aoData,"_aData")}).flatten()}),Kt("destroy()",function(t){return t=t||!1,this.iterator("table",function(r){var i,o=r.nTableWrapper.parentNode,a=r.oClasses,s=r.nTable,l=r.nTBody,u=r.nTHead,c=r.nTFoot,f=e(s),d=e(l),h=e(r.nTableWrapper),p=e.map(r.aoData,function(e){return e.nTr});r.bDestroying=!0,zt(r,"aoDestroyCallback","destroy",[r]),t||new Yt(r).columns().visible(!0),h.unbind(".DT").find(":not(tbody *)").unbind(".DT"),e(n).unbind(".DT-"+r.sInstance),s!=u.parentNode&&(f.children("thead").detach(),f.append(u)),c&&s!=c.parentNode&&(f.children("tfoot").detach(),f.append(c)),f.detach(),h.detach(),r.aaSorting=[],r.aaSortingFixed=[],Mt(r),e(p).removeClass(r.asStripeClasses.join(" ")),e("th, td",u).removeClass(a.sSortable+" "+a.sSortableAsc+" "+a.sSortableDesc+" "+a.sSortableNone),r.bJUI&&(e("th span."+a.sSortIcon+", td span."+a.sSortIcon,u).detach(),e("th, td",u).each(function(){var t=e("div."+a.sSortJUIWrapper,this);e(this).append(t.contents()),t.detach()})),!t&&o&&o.insertBefore(s,r.nTableReinsertBefore),d.children().detach(),d.append(p),f.css("width",r.sDestroyWidth).removeClass(a.sTable),i=r.asDestroyStripes.length,i&&d.children().each(function(t){e(this).addClass(r.asDestroyStripes[t%i])});var g=e.inArray(r,$t.settings);-1!==g&&$t.settings.splice(g,1)})}),$t.version="1.10.2",$t.settings=[],$t.models={},$t.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0},$t.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null},$t.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null},$t.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(e){return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(e){try{return JSON.parse((-1===e.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+e.sInstance+"_"+location.pathname))}catch(t){}},fnStateLoadParams:null,fnStateLoaded:null,fnStateSaveCallback:function(e,t){try{(-1===e.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+e.sInstance+"_"+location.pathname,JSON.stringify(t))}catch(n){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:e.extend({},$t.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null},t($t.defaults),$t.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null},t($t.defaults.column),$t.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,json:o,oAjaxData:o,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==Ut(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==Ut(this)?1*this._iRecordsDisplay:this.aiDisplay.length},fnDisplayEnd:function(){var e=this._iDisplayLength,t=this._iDisplayStart,n=t+e,r=this.aiDisplay.length,i=this.oFeatures,o=i.bPaginate;return i.bServerSide?o===!1||-1===e?t+r:Math.min(t+e,this._iRecordsDisplay):!o||n>r||-1===e?r:n},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}},$t.ext=Jt={classes:{},errMode:"alert",feature:[],search:[],internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:$t.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:$t.version},e.extend(Jt,{afnFiltering:Jt.search,aTypes:Jt.type.detect,ofnSearch:Jt.type.search,oSort:Jt.type.order,afnSortData:Jt.order,aoFeatures:Jt.feature,oApi:Jt.internal,oStdClasses:Jt.classes,oPagination:Jt.pager}),e.extend($t.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""}),function(){var t="";t="";var n=t+"ui-state-default",r=t+"css_right ui-icon ui-icon-",i=t+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";e.extend($t.ext.oJUIClasses,$t.ext.classes,{sPageButton:"fg-button ui-button "+n,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:n+" sorting_asc",sSortDesc:n+" sorting_desc",sSortable:n+" sorting",sSortableAsc:n+" sorting_asc_disabled",sSortableDesc:n+" sorting_desc_disabled",sSortableNone:n+" sorting_disabled",sSortJUIAsc:r+"triangle-1-n",sSortJUIDesc:r+"triangle-1-s",sSortJUI:r+"carat-2-n-s",sSortJUIAscAllowed:r+"carat-1-n",sSortJUIDescAllowed:r+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+n,sScrollFoot:"dataTables_scrollFoot "+n,sHeaderTH:n,sFooterTH:n,sJUIHeader:i+" ui-corner-tl ui-corner-tr",sJUIFooter:i+" ui-corner-bl ui-corner-br"})}();var Vn=$t.ext.pager;e.extend(Vn,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(e,t){return["previous",Vt(e,t),"next"]},full_numbers:function(e,t){return["first","previous",Vt(e,t),"next","last"]},_numbers:Vt,numbers_length:7}),e.extend(!0,$t.ext.renderer,{pageButton:{_:function(t,n,r,o,a,s){var l,u,c=t.oClasses,f=t.oLanguage.oPaginate,d=0,h=function(n,i){var o,p,g,m,v=function(e){dt(t,e.data.action,!0)};for(o=0,p=i.length;p>o;o++)if(m=i[o],e.isArray(m)){var y=e("<"+(m.DT_el||"div")+"/>").appendTo(n);h(y,m)}else{switch(l="",u="",m){case"ellipsis":n.append("<span>&hellip;</span>");break;case"first":l=f.sFirst,u=m+(a>0?"":" "+c.sPageButtonDisabled);break;case"previous":l=f.sPrevious,u=m+(a>0?"":" "+c.sPageButtonDisabled);break;case"next":l=f.sNext,u=m+(s-1>a?"":" "+c.sPageButtonDisabled);break;case"last":l=f.sLast,u=m+(s-1>a?"":" "+c.sPageButtonDisabled);break;default:l=m+1,u=a===m?c.sPageButtonActive:""}l&&(g=e("<a>",{"class":c.sPageButton+" "+u,"aria-controls":t.sTableId,"data-dt-idx":d,tabindex:t.iTabIndex,id:0===r&&"string"==typeof m?t.sTableId+"_"+m:null}).html(l).appendTo(n),Ft(g,{action:m},v),d++)}};try{var p=e(i.activeElement).data("dt-idx");h(e(n).empty(),o),null!==p&&e(n).find("[data-dt-idx="+p+"]").focus()}catch(g){}}}});var Xn=function(e,t,n,r){return e&&"-"!==e?(t&&(e=un(e,t)),e.replace&&(n&&(e=e.replace(n,"")),r&&(e=e.replace(r,""))),1*e):-1/0};return e.extend(Jt.type.order,{"date-pre":function(e){return Date.parse(e)||0},"html-pre":function(e){return sn(e)?"":e.replace?e.replace(/<.*?>/g,"").toLowerCase():e+""},"string-pre":function(e){return sn(e)?"":"string"==typeof e?e.toLowerCase():e.toString?e.toString():""},"string-asc":function(e,t){return t>e?-1:e>t?1:0},"string-desc":function(e,t){return t>e?1:e>t?-1:0}}),Xt(""),e.extend($t.ext.type.detect,[function(e,t){var n=t.oLanguage.sDecimal;return cn(e,n)?"num"+n:null},function(e){if(e&&(!nn.test(e)||!rn.test(e)))return null;var t=Date.parse(e);return null!==t&&!isNaN(t)||sn(e)?"date":null},function(e,t){var n=t.oLanguage.sDecimal;return cn(e,n,!0)?"num-fmt"+n:null},function(e,t){var n=t.oLanguage.sDecimal;return dn(e,n)?"html-num"+n:null},function(e,t){var n=t.oLanguage.sDecimal;return dn(e,n,!0)?"html-num-fmt"+n:null},function(e){return sn(e)||"string"==typeof e&&-1!==e.indexOf("<")?"html":null}]),e.extend($t.ext.type.search,{html:function(e){return sn(e)?e:"string"==typeof e?e.replace(en," ").replace(tn,""):""},string:function(e){return sn(e)?e:"string"==typeof e?e.replace(en," "):e}}),e.extend(!0,$t.ext.renderer,{header:{_:function(t,n,r,i){e(t.nTable).on("order.dt.DT",function(e,o,a,s){if(t===o){var l=r.idx;n.removeClass(r.sSortingClass+" "+i.sSortAsc+" "+i.sSortDesc).addClass("asc"==s[l]?i.sSortAsc:"desc"==s[l]?i.sSortDesc:r.sSortingClass)}})},jqueryui:function(t,n,r,i){var o=r.idx;e("<div/>").addClass(i.sSortJUIWrapper).append(n.contents()).append(e("<span/>").addClass(i.sSortIcon+" "+r.sSortingClassJUI)).appendTo(n),e(t.nTable).on("order.dt.DT",function(e,a,s,l){t===a&&(n.removeClass(i.sSortAsc+" "+i.sSortDesc).addClass("asc"==l[o]?i.sSortAsc:"desc"==l[o]?i.sSortDesc:r.sSortingClass),n.find("span."+i.sSortIcon).removeClass(i.sSortJUIAsc+" "+i.sSortJUIDesc+" "+i.sSortJUI+" "+i.sSortJUIAscAllowed+" "+i.sSortJUIDescAllowed).addClass("asc"==l[o]?i.sSortJUIAsc:"desc"==l[o]?i.sSortJUIDesc:r.sSortingClassJUI))})}}}),$t.render={number:function(e,t,n,r){return{display:function(i){var o=0>i?"-":"";i=Math.abs(parseFloat(i));var a=parseInt(i,10),s=n?t+(i-a).toFixed(n).substring(2):"";return o+(r||"")+a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,e)+s}}}},e.extend($t.ext.internal,{_fnExternApiFunc:Gt,_fnBuildAjax:q,_fnAjaxUpdate:U,_fnAjaxParameters:V,_fnAjaxUpdateDraw:X,_fnAjaxDataSrc:G,_fnAddColumn:f,_fnColumnOptions:d,_fnAdjustColumnSizing:h,_fnVisibleToColumnIndex:p,_fnColumnIndexToVisible:g,_fnVisbleColumns:m,_fnGetColumns:v,_fnColumnTypes:y,_fnApplyColumnDefs:b,_fnHungarianMap:t,_fnCamelToHungarian:r,_fnLanguageCompat:a,_fnBrowserDetect:u,_fnAddData:x,_fnAddTr:w,_fnNodeToDataIndex:S,_fnNodeToColumnIndex:C,_fnGetCellData:T,_fnSetCellData:D,_fnSplitObjNotation:k,_fnGetObjectDataFn:L,_fnSetObjectDataFn:A,_fnGetDataMaster:N,_fnClearTable:_,_fnDeleteIndex:M,_fnInvalidateRow:E,_fnGetRowElements:j,_fnCreateTr:I,_fnBuildHead:O,_fnDrawHead:R,_fnDraw:P,_fnReDraw:F,_fnAddOptionsHtml:W,_fnDetectHeader:z,_fnGetUniqueThs:B,_fnFeatureHtmlFilter:$,_fnFilterComplete:J,_fnFilterCustom:Y,_fnFilterColumn:K,_fnFilter:Q,_fnFilterCreateSearch:Z,_fnEscapeRegex:et,_fnFilterData:tt,_fnFeatureHtmlInfo:it,_fnUpdateInfo:ot,_fnInfoMacros:at,_fnInitialise:st,_fnInitComplete:lt,_fnLengthChange:ut,_fnFeatureHtmlLength:ct,_fnFeatureHtmlPaginate:ft,_fnPageChange:dt,_fnFeatureHtmlProcessing:ht,_fnProcessingDisplay:pt,_fnFeatureHtmlTable:gt,_fnScrollDraw:mt,_fnApplyToChildren:vt,_fnCalculateColumnWidths:yt,_fnThrottle:bt,_fnConvertToWidth:xt,_fnScrollingWidthAdjust:wt,_fnGetWidestNode:St,_fnGetMaxLenString:Ct,_fnStringToCss:Tt,_fnScrollBarWidth:Dt,_fnSortFlatten:kt,_fnSort:Lt,_fnSortAria:At,_fnSortListener:Nt,_fnSortAttachListener:_t,_fnSortingClasses:Mt,_fnSortData:Et,_fnSaveState:jt,_fnLoadState:It,_fnSettingsFromNode:Ht,_fnLog:Ot,_fnMap:Rt,_fnBindAction:Ft,_fnCallbackReg:Wt,_fnCallbackFire:zt,_fnLengthOverflow:Bt,_fnRenderer:qt,_fnDataSource:Ut,_fnRowAttributes:H,_fnCalculateEnd:function(){}}),e.fn.dataTable=$t,e.fn.dataTableSettings=$t.settings,e.fn.dataTableExt=$t.ext,e.fn.DataTable=function(t){return e(this).dataTable(t).api()},e.each($t,function(t,n){e.fn.DataTable[t]=n}),e.fn.dataTable})}(window,document)},{jquery:8}],3:[function(){RegExp.escape=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")},function(e){"use strict";e.csv={defaults:{separator:",",delimiter:'"',headers:!0},hooks:{castToScalar:function(e){var t=/\./;if(isNaN(e))return e;if(t.test(e))return parseFloat(e);var n=parseInt(e);return isNaN(n)?null:n}},parsers:{parse:function(e,t){function n(){if(l=0,u="",t.start&&t.state.rowNum<t.start)return s=[],t.state.rowNum++,void(t.state.colNum=1);if(void 0===t.onParseEntry)a.push(s);else{var e=t.onParseEntry(s,t.state);e!==!1&&a.push(e)}s=[],t.end&&t.state.rowNum>=t.end&&(c=!0),t.state.rowNum++,t.state.colNum=1}function r(){if(void 0===t.onParseValue)s.push(u);else{var e=t.onParseValue(u,t.state);e!==!1&&s.push(e)}u="",l=0,t.state.colNum++}var i=t.separator,o=t.delimiter;t.state.rowNum||(t.state.rowNum=1),t.state.colNum||(t.state.colNum=1);var a=[],s=[],l=0,u="",c=!1,f=RegExp.escape(i),d=RegExp.escape(o),h=/(D|S|\n|\r|[^DS\r\n]+)/,p=h.source;return p=p.replace(/S/g,f),p=p.replace(/D/g,d),h=RegExp(p,"gm"),e.replace(h,function(e){if(!c)switch(l){case 0:if(e===i){u+="",r();break}if(e===o){l=1;break}if("\n"===e){r(),n();break}if(/^\r$/.test(e))break;u+=e,l=3;break;case 1:if(e===o){l=2;break}u+=e,l=1;break;case 2:if(e===o){u+=e,l=1;break}if(e===i){r();break}if("\n"===e){r(),n();break}if(/^\r$/.test(e))break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===i){r();break}if("\n"===e){r(),n();break}if(/^\r$/.test(e))break;if(e===o)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}}),0!==s.length&&(r(),n()),a},splitLines:function(e,t){function n(){if(a=0,t.start&&t.state.rowNum<t.start)return s="",void t.state.rowNum++;if(void 0===t.onParseEntry)o.push(s);else{var e=t.onParseEntry(s,t.state);e!==!1&&o.push(e)}s="",t.end&&t.state.rowNum>=t.end&&(l=!0),t.state.rowNum++}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1);var o=[],a=0,s="",l=!1,u=RegExp.escape(r),c=RegExp.escape(i),f=/(D|S|\n|\r|[^DS\r\n]+)/,d=f.source;return d=d.replace(/S/g,u),d=d.replace(/D/g,c),f=RegExp(d,"gm"),e.replace(f,function(e){if(!l)switch(a){case 0:if(e===r){s+=e,a=0;break}if(e===i){s+=e,a=1;break}if("\n"===e){n();break}if(/^\r$/.test(e))break;s+=e,a=3;break;case 1:if(e===i){s+=e,a=2;break}s+=e,a=1;break;case 2:var o=s.substr(s.length-1);if(e===i&&o===i){s+=e,a=1;break}if(e===r){s+=e,a=0;break}if("\n"===e){n();break}if("\r"===e)break;throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");case 3:if(e===r){s+=e,a=0;break}if("\n"===e){n();break}if("\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal quote [Row:"+t.state.rowNum+"]");throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");default:throw new Error("CSVDataError: Unknown state [Row:"+t.state.rowNum+"]")}}),""!==s&&n(),o},parseEntry:function(e,t){function n(){if(void 0===t.onParseValue)o.push(s);else{var e=t.onParseValue(s,t.state);e!==!1&&o.push(e)}s="",a=0,t.state.colNum++}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1),t.state.colNum||(t.state.colNum=1);var o=[],a=0,s="";if(!t.match){var l=RegExp.escape(r),u=RegExp.escape(i),c=/(D|S|\n|\r|[^DS\r\n]+)/,f=c.source;f=f.replace(/S/g,l),f=f.replace(/D/g,u),t.match=RegExp(f,"gm")}return e.replace(t.match,function(e){switch(a){case 0:if(e===r){s+="",n();break}if(e===i){a=1;break}if("\n"===e||"\r"===e)break;s+=e,a=3;break;case 1:if(e===i){a=2;break}s+=e,a=1;break;case 2:if(e===i){s+=e,a=1;break}if(e===r){n();break}if("\n"===e||"\r"===e)break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===r){n();break}if("\n"===e||"\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}}),n(),o}},toArray:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1,i.separator="separator"in n?n.separator:e.csv.defaults.separator,i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;var o=void 0!==n.state?n.state:{},n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,state:o},a=e.csv.parsers.parseEntry(t,n);return i.callback?void i.callback("",a):a},toArrays:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1,i.separator="separator"in n?n.separator:e.csv.defaults.separator,i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;var o=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1}};return o=e.csv.parsers.parse(t,n),i.callback?void i.callback("",o):o},toObjects:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1,i.separator="separator"in n?n.separator:e.csv.defaults.separator,i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter,i.headers="headers"in n?n.headers:e.csv.defaults.headers,n.start="start"in n?n.start:1,i.headers&&n.start++,n.end&&i.headers&&n.end++;var o=[],a=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1},match:!1},s={delimiter:i.delimiter,separator:i.separator,start:1,end:1,state:{rowNum:1,colNum:1}},l=e.csv.parsers.splitLines(t,s),u=e.csv.toArray(l[0],n),o=e.csv.parsers.splitLines(t,n);n.state.colNum=1,n.state.rowNum=u?2:1;for(var c=0,f=o.length;f>c;c++){var d=e.csv.toArray(o[c],n),h={};for(var p in u)h[u[p]]=d[p];a.push(h),n.state.rowNum++}return i.callback?void i.callback("",a):a},fromArrays:function(t,n,r){var n=void 0!==n?n:{},o={};if(o.callback=void 0!==r&&"function"==typeof r?r:!1,o.separator="separator"in n?n.separator:e.csv.defaults.separator,o.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter,o.escaper="escaper"in n?n.escaper:e.csv.defaults.escaper,o.experimental="experimental"in n?n.experimental:!1,!o.experimental)throw new Error("not implemented");var a=[];for(i in t)a.push(t[i]);return o.callback?void o.callback("",a):a},fromObjects2CSV:function(t,n,r){var n=void 0!==n?n:{},o={};if(o.callback=void 0!==r&&"function"==typeof r?r:!1,o.separator="separator"in n?n.separator:e.csv.defaults.separator,o.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter,o.experimental="experimental"in n?n.experimental:!1,!o.experimental)throw new Error("not implemented");var a=[];for(i in t)a.push(arrays[i]);return o.callback?void o.callback("",a):a}},e.csvEntry2Array=e.csv.toArray,e.csv2Array=e.csv.toArrays,e.csv2Dictionary=e.csv.toObjects}(jQuery)},{}],4:[function(t,n,r){!function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)}(function(e){function t(e,t,r,i){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&s[o.text.charAt(l)]||s[o.text.charAt(++l)];if(!u)return null;var c=">"==u.charAt(1)?1:-1;if(r&&c>0!=(l==t.ch))return null;var f=e.getTokenTypeAt(a(t.line,l+1)),d=n(e,a(t.line,l+(c>0?1:0)),c,f||null,i);return null==d?null:{from:a(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:c>0}}function n(e,t,n,r,i){for(var o=i&&i.maxScanLineLength||1e4,l=i&&i.maxScanLines||1e3,u=[],c=i&&i.bracketRegex?i.bracketRegex:/[(){}[\]]/,f=n>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=f;d+=n){var h=e.getLine(d);if(h){var p=n>0?0:h.length-1,g=n>0?h.length:-1;if(!(h.length>o))for(d==t.line&&(p=t.ch-(0>n?1:0));p!=g;p+=n){var m=h.charAt(p);if(c.test(m)&&(void 0===r||e.getTokenTypeAt(a(d,p+1))==r)){var v=s[m];if(">"==v.charAt(1)==n>0)u.push(m);else{if(!u.length)return{pos:a(d,p),ch:m};u.pop()}}}}}return d-n==(n>0?e.lastLine():e.firstLine())?!1:null}function r(e,n,r){for(var i=e.state.matchBrackets.maxHighlightLineLength||1e3,s=[],l=e.listSelections(),u=0;u<l.length;u++){var c=l[u].empty()&&t(e,l[u].head,!1,r);if(c&&e.getLine(c.from.line).length<=i){var f=c.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";s.push(e.markText(c.from,a(c.from.line,c.from.ch+1),{className:f})),c.to&&e.getLine(c.to.line).length<=i&&s.push(e.markText(c.to,a(c.to.line,c.to.ch+1),{className:f}))}}if(s.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<s.length;e++)s[e].clear()})};if(!n)return d;setTimeout(d,800)}}function i(e){e.operation(function(){l&&(l(),l=null),l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),a=e.Pos,s={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,n,r){r&&r!=e.Init&&t.off("cursorActivity",i),n&&(t.state.matchBrackets="object"==typeof n?n:{},t.on("cursorActivity",i))}),e.defineExtension("matchBrackets",function(){r(this,!0)}),e.defineExtension("findMatchingBracket",function(e,n,r){return t(this,e,n,r)}),e.defineExtension("scanForBracket",function(e,t,r,i){return n(this,e,t,r,i)})})},{"../../lib/codemirror":5}],5:[function(t,n,r){!function(t){if("object"==typeof r&&"object"==typeof n)n.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}}(function(){"use strict";function e(n,r){if(!(this instanceof e))return new e(n,r);this.options=r=r?mo(r):{},mo(ja,r,!1),p(r);var i=r.value;"string"==typeof i&&(i=new rs(i,r.mode)),this.doc=i;var o=this.display=new t(n,i);o.wrapper.CodeMirror=this,c(this),l(this),r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),r.autofocus&&!ca&&kn(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new lo},Zo&&11>ea&&setTimeout(vo(Dn,this,!0),20),Nn(this),Mo(),Zt(this),this.curOp.forceUpdate=!0,Ni(this,i),r.autofocus&&!ca||Do()==o.input?setTimeout(vo(Qn,this),20):Zn(this);for(var a in Ia)Ia.hasOwnProperty(a)&&Ia[a](this,r[a],Ha);x(this);for(var s=0;s<Fa.length;++s)Fa[s](this);tn(this)}function t(e,t){var n=this,r=n.input=wo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ta?r.style.width="1000px":r.setAttribute("wrap","off"),ua&&(r.style.border="1px solid black"),r.setAttribute("autocorrect","off"),r.setAttribute("autocapitalize","off"),r.setAttribute("spellcheck","false"),n.inputDiv=wo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;"),n.scrollbarH=wo("div",[wo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar"),n.scrollbarV=wo("div",[wo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),n.scrollbarFiller=wo("div",null,"CodeMirror-scrollbar-filler"),n.gutterFiller=wo("div",null,"CodeMirror-gutter-filler"),n.lineDiv=wo("div",null,"CodeMirror-code"),n.selectionDiv=wo("div",null,null,"position: relative; z-index: 1"),n.cursorDiv=wo("div",null,"CodeMirror-cursors"),n.measure=wo("div",null,"CodeMirror-measure"),n.lineMeasure=wo("div",null,"CodeMirror-measure"),n.lineSpace=wo("div",[n.measure,n.lineMeasure,n.selectionDiv,n.cursorDiv,n.lineDiv],null,"position: relative; outline: none"),n.mover=wo("div",[wo("div",[n.lineSpace],"CodeMirror-lines")],null,"position: relative"),n.sizer=wo("div",[n.mover],"CodeMirror-sizer"),n.heightForcer=wo("div",null,null,"position: absolute; height: "+hs+"px; width: 1px;"),n.gutters=wo("div",null,"CodeMirror-gutters"),n.lineGutter=null,n.scroller=wo("div",[n.sizer,n.heightForcer,n.gutters],"CodeMirror-scroll"),n.scroller.setAttribute("tabIndex","-1"),n.wrapper=wo("div",[n.inputDiv,n.scrollbarH,n.scrollbarV,n.scrollbarFiller,n.gutterFiller,n.scroller],"CodeMirror"),Zo&&8>ea&&(n.gutters.style.zIndex=-1,n.scroller.style.paddingRight=0),ua&&(r.style.width="0px"),ta||(n.scroller.draggable=!0),aa&&(n.inputDiv.style.height="1px",n.inputDiv.style.position="absolute"),Zo&&8>ea&&(n.scrollbarH.style.minHeight=n.scrollbarV.style.minWidth="18px"),e.appendChild?e.appendChild(n.wrapper):e(n.wrapper),n.viewFrom=n.viewTo=t.first,n.view=[],n.externalMeasured=null,n.viewOffset=0,n.lastSizeC=0,n.updateLineNumbers=null,n.lineNumWidth=n.lineNumInnerWidth=n.lineNumChars=null,n.prevInput="",n.alignWidgets=!1,n.pollingFast=!1,n.poll=new lo,n.cachedCharWidth=n.cachedTextHeight=n.cachedPaddingH=null,n.inaccurateSelection=!1,n.maxLine=null,n.maxLineLength=0,n.maxLineChanged=!1,n.wheelDX=n.wheelDY=n.wheelStartX=n.wheelStartY=null,n.shift=!1,n.selForContextMenu=null}function n(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption),r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null)}),e.doc.frontier=e.doc.first,St(e,100),e.state.modeGen++,e.curOp&&gn(e) }function i(e){e.options.lineWrapping?(Ao(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth=""):(Lo(e.display.wrapper,"CodeMirror-wrap"),h(e)),a(e),gn(e),Wt(e),setTimeout(function(){v(e)},100)}function o(e){var t=Kt(e.display),n=e.options.lineWrapping,r=n&&Math.max(5,e.display.scroller.clientWidth/Qt(e.display)-3);return function(i){if(ni(e.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a<i.widgets.length;a++)i.widgets[a].height&&(o+=i.widgets[a].height);return n?o+(Math.ceil(i.text.length/r)||1)*t:o+t}}function a(e){var t=e.doc,n=o(e);t.iter(function(e){var t=n(e);t!=e.height&&ji(e,t)})}function s(e){var t=Ua[e.options.keyMap],n=t.style;e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-keymap-\S+/g,"")+(n?" cm-keymap-"+n:"")}function l(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Wt(e)}function u(e){c(e),gn(e),setTimeout(function(){b(e)},20)}function c(e){var t=e.display.gutters,n=e.options.gutters;So(t);for(var r=0;r<n.length;++r){var i=n[r],o=t.appendChild(wo("div",null,"CodeMirror-gutter "+i));"CodeMirror-linenumbers"==i&&(e.display.lineGutter=o,o.style.width=(e.display.lineNumWidth||1)+"px")}t.style.display=r?"":"none",f(e)}function f(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px",e.display.scrollbarH.style.left=e.options.fixedGutter?t+"px":0}function d(e){if(0==e.height)return 0;for(var t,n=e.text.length,r=e;t=Jr(r);){var i=t.find(0,!0);r=i.from.line,n+=i.from.ch-i.to.ch}for(r=e;t=Yr(r);){var i=t.find(0,!0);n-=r.text.length-i.from.ch,r=i.to.line,n+=r.text.length-i.to.ch}return n}function h(e){var t=e.display,n=e.doc;t.maxLine=_i(n,n.first),t.maxLineLength=d(t.maxLine),t.maxLineChanged=!0,n.iter(function(e){var n=d(e);n>t.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)})}function p(e){var t=ho(e.gutters,"CodeMirror-linenumbers");-1==t&&e.lineNumbers?e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]):t>-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function g(e){return e.display.scroller.clientHeight-e.display.wrapper.clientHeight<hs-3}function m(e){var t=e.display.scroller;return{clientHeight:t.clientHeight,barHeight:e.display.scrollbarV.clientHeight,scrollWidth:t.scrollWidth,clientWidth:t.clientWidth,hScrollbarTakesSpace:g(e),barWidth:e.display.scrollbarH.clientWidth,docHeight:Math.round(e.doc.height+Lt(e.display))}}function v(e,t){t||(t=m(e));var n=e.display,r=jo(n.measure),i=t.docHeight+hs,o=t.scrollWidth>t.clientWidth;o&&t.scrollWidth<=t.clientWidth+1&&r>0&&!t.hScrollbarTakesSpace&&(o=!1);var a=i>t.clientHeight;if(a?(n.scrollbarV.style.display="block",n.scrollbarV.style.bottom=o?r+"px":"0",n.scrollbarV.firstChild.style.height=Math.max(0,i-t.clientHeight+(t.barHeight||n.scrollbarV.clientHeight))+"px"):(n.scrollbarV.style.display="",n.scrollbarV.firstChild.style.height="0"),o?(n.scrollbarH.style.display="block",n.scrollbarH.style.right=a?r+"px":"0",n.scrollbarH.firstChild.style.width=t.scrollWidth-t.clientWidth+(t.barWidth||n.scrollbarH.clientWidth)+"px"):(n.scrollbarH.style.display="",n.scrollbarH.firstChild.style.width="0"),o&&a?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=n.scrollbarFiller.style.width=r+"px"):n.scrollbarFiller.style.display="",o&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r+"px",n.gutterFiller.style.width=n.gutters.offsetWidth+"px"):n.gutterFiller.style.display="",!e.state.checkedOverlayScrollbar&&t.clientHeight>0){if(0===r){var s=fa&&!sa?"12px":"18px";n.scrollbarV.style.minWidth=n.scrollbarH.style.minHeight=s;var l=function(t){eo(t)!=n.scrollbarV&&eo(t)!=n.scrollbarH&&cn(e,jn)(t)};us(n.scrollbarV,"mousedown",l),us(n.scrollbarH,"mousedown",l)}e.state.checkedOverlayScrollbar=!0}}function y(e,t,n){var r=n&&null!=n.top?Math.max(0,n.top):e.scroller.scrollTop;r=Math.floor(r-kt(e));var i=n&&null!=n.bottom?n.bottom:r+e.wrapper.clientHeight,o=Hi(t,r),a=Hi(t,i);if(n&&n.ensure){var s=n.ensure.from.line,l=n.ensure.to.line;if(o>s)return{from:s,to:Hi(t,Oi(_i(t,s))+e.wrapper.clientHeight)};if(Math.min(l,t.lastLine())>=a)return{from:Hi(t,Oi(_i(t,l))-e.wrapper.clientHeight),to:l}}return{from:o,to:Math.max(a,o+1)}}function b(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=S(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=r+"px",a=0;a<n.length;a++)if(!n[a].hidden){e.options.fixedGutter&&n[a].gutter&&(n[a].gutter.style.left=o);var s=n[a].alignable;if(s)for(var l=0;l<s.length;l++)s[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+i+"px")}}function x(e){if(!e.options.lineNumbers)return!1;var t=e.doc,n=w(e.options,t.first+t.size-1),r=e.display;if(n.length!=r.lineNumChars){var i=r.measure.appendChild(wo("div",[wo("div",n)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=i.firstChild.offsetWidth,a=i.offsetWidth-o;return r.lineGutter.style.width="",r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-a),r.lineNumWidth=r.lineNumInnerWidth+a,r.lineNumChars=r.lineNumInnerWidth?n.length:-1,r.lineGutter.style.width=r.lineNumWidth+"px",f(e),!0}return!1}function w(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function S(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function C(e,t,n){var r=e.display;this.viewport=t,this.visible=y(r,e.doc,t),this.editorIsHidden=!r.wrapper.offsetWidth,this.wrapperHeight=r.wrapper.clientHeight,this.oldViewFrom=r.viewFrom,this.oldViewTo=r.viewTo,this.oldScrollerWidth=r.scroller.clientWidth,this.force=n,this.dims=M(e)}function T(e,t){var n=e.display,r=e.doc;if(t.editorIsHidden)return vn(e),!1;if(!t.force&&t.visible.from>=n.viewFrom&&t.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&0==wn(e))return!1;x(e)&&(vn(e),t.dims=M(e));var i=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),a=Math.min(i,t.visible.to+e.options.viewportMargin);n.viewFrom<o&&o-n.viewFrom<20&&(o=Math.max(r.first,n.viewFrom)),n.viewTo>a&&n.viewTo-a<20&&(a=Math.min(i,n.viewTo)),va&&(o=ei(e.doc,o),a=ti(e.doc,a));var s=o!=n.viewFrom||a!=n.viewTo||n.lastSizeC!=t.wrapperHeight;xn(e,o,a),n.viewOffset=Oi(_i(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var l=wn(e);if(!s&&0==l&&!t.force&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=Do();return l>4&&(n.lineDiv.style.display="none"),E(e,n.updateLineNumbers,t.dims),l>4&&(n.lineDiv.style.display=""),u&&Do()!=u&&u.offsetHeight&&u.focus(),So(n.cursorDiv),So(n.selectionDiv),s&&(n.lastSizeC=t.wrapperHeight,St(e,400)),n.updateLineNumbers=null,!0}function D(e,t){for(var n=t.force,r=t.viewport,i=!0;;i=!1){if(i&&e.options.lineWrapping&&t.oldScrollerWidth!=e.display.scroller.clientWidth)n=!0;else if(n=!1,r&&null!=r.top&&(r={top:Math.min(e.doc.height+Lt(e.display)-hs-e.display.scroller.clientHeight,r.top)}),t.visible=y(e.display,e.doc,r),t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break;if(!T(e,t))break;N(e);var o=m(e);yt(e),L(e,o),v(e,o)}no(e,"update",e),(e.display.viewFrom!=t.oldViewFrom||e.display.viewTo!=t.oldViewTo)&&no(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo)}function k(e,t){var n=new C(e,t);if(T(e,n)){N(e),D(e,n);var r=m(e);yt(e),L(e,r),v(e,r)}}function L(e,t){e.display.sizer.style.minHeight=e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=Math.max(t.docHeight,t.clientHeight-hs)+"px"}function A(e,t){e.display.sizer.offsetWidth+e.display.gutters.offsetWidth<e.display.scroller.clientWidth-1&&(e.display.sizer.style.minHeight=e.display.heightForcer.style.top="0px",e.display.gutters.style.height=t.docHeight+"px")}function N(e){for(var t=e.display,n=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var i,o=t.view[r];if(!o.hidden){if(Zo&&8>ea){var a=o.node.offsetTop+o.node.offsetHeight;i=a-n,n=a}else{var s=o.node.getBoundingClientRect();i=s.bottom-s.top}var l=o.line.height-i;if(2>i&&(i=Kt(t)),(l>.001||-.001>l)&&(ji(o.line,i),_(o.line),o.rest))for(var u=0;u<o.rest.length;u++)_(o.rest[u])}}}function _(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function M(e){for(var t=e.display,n={},r={},i=t.gutters.clientLeft,o=t.gutters.firstChild,a=0;o;o=o.nextSibling,++a)n[e.options.gutters[a]]=o.offsetLeft+o.clientLeft+i,r[e.options.gutters[a]]=o.clientWidth;return{fixedPos:S(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function E(e,t,n){function r(t){var n=t.nextSibling;return ta&&fa&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),n}for(var i=e.display,o=e.options.lineNumbers,a=i.lineDiv,s=a.firstChild,l=i.view,u=i.viewFrom,c=0;c<l.length;c++){var f=l[c];if(f.hidden);else if(f.node){for(;s!=f.node;)s=r(s);var d=o&&null!=t&&u>=t&&f.lineNumber;f.changes&&(ho(f.changes,"gutter")>-1&&(d=!1),j(e,f,u,n)),d&&(So(f.lineNumber),f.lineNumber.appendChild(document.createTextNode(w(e.options,u)))),s=f.node.nextSibling}else{var h=z(e,f,u,n);a.insertBefore(h,s)}u+=f.size}for(;s;)s=r(s)}function j(e,t,n,r){for(var i=0;i<t.changes.length;i++){var o=t.changes[i];"text"==o?R(e,t):"gutter"==o?F(e,t,n,r):"class"==o?P(t):"widget"==o&&W(t,r)}t.changes=null}function I(e){return e.node==e.text&&(e.node=wo("div",null,null,"position: relative"),e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text),e.node.appendChild(e.text),Zo&&8>ea&&(e.node.style.zIndex=2)),e.node}function H(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;if(t&&(t+=" CodeMirror-linebackground"),e.background)t?e.background.className=t:(e.background.parentNode.removeChild(e.background),e.background=null);else if(t){var n=I(e);e.background=n.insertBefore(wo("div",null,t),n.firstChild)}}function O(e,t){var n=e.display.externalMeasured;return n&&n.line==t.line?(e.display.externalMeasured=null,t.measure=n.measure,n.built):vi(e,t)}function R(e,t){var n=t.text.className,r=O(e,t);t.text==t.node&&(t.node=r.pre),t.text.parentNode.replaceChild(r.pre,t.text),t.text=r.pre,r.bgClass!=t.bgClass||r.textClass!=t.textClass?(t.bgClass=r.bgClass,t.textClass=r.textClass,P(t)):n&&(t.text.className=n)}function P(e){H(e),e.line.wrapClass?I(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function F(e,t,n,r){t.gutter&&(t.node.removeChild(t.gutter),t.gutter=null);var i=t.line.gutterMarkers;if(e.options.lineNumbers||i){var o=I(t),a=t.gutter=o.insertBefore(wo("div",null,"CodeMirror-gutter-wrapper","position: absolute; left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px"),t.text);if(!e.options.lineNumbers||i&&i["CodeMirror-linenumbers"]||(t.lineNumber=a.appendChild(wo("div",w(e.options,n),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px"))),i)for(var s=0;s<e.options.gutters.length;++s){var l=e.options.gutters[s],u=i.hasOwnProperty(l)&&i[l];u&&a.appendChild(wo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function W(e,t){e.alignable&&(e.alignable=null);for(var n,r=e.node.firstChild;r;r=n){var n=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}B(e,t)}function z(e,t,n,r){var i=O(e,t);return t.text=t.node=i.pre,i.bgClass&&(t.bgClass=i.bgClass),i.textClass&&(t.textClass=i.textClass),P(t),F(e,t,n,r),B(t,r),t.node}function B(e,t){if(q(e.line,e,t,!0),e.rest)for(var n=0;n<e.rest.length;n++)q(e.rest[n],e,t,!1)}function q(e,t,n,r){if(e.widgets)for(var i=I(t),o=0,a=e.widgets;o<a.length;++o){var s=a[o],l=wo("div",[s.node],"CodeMirror-linewidget");s.handleMouseEvents||(l.ignoreEvents=!0),U(s,l,t,n),r&&s.above?i.insertBefore(l,t.gutter||t.text):i.appendChild(l),no(s,"redraw")}}function U(e,t,n,r){if(e.noHScroll){(n.alignable||(n.alignable=[])).push(t);var i=r.wrapperWidth;t.style.left=r.fixedPos+"px",e.coverGutter||(i-=r.gutterTotalWidth,t.style.paddingLeft=r.gutterTotalWidth+"px"),t.style.width=i+"px"}e.coverGutter&&(t.style.zIndex=5,t.style.position="relative",e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px"))}function V(e){return ya(e.line,e.ch)}function X(e,t){return ba(e,t)<0?t:e}function G(e,t){return ba(e,t)<0?e:t}function $(e,t){this.ranges=e,this.primIndex=t}function J(e,t){this.anchor=e,this.head=t}function Y(e,t){var n=e[t];e.sort(function(e,t){return ba(e.from(),t.from())}),t=ho(e,n);for(var r=1;r<e.length;r++){var i=e[r],o=e[r-1];if(ba(o.to(),i.from())>=0){var a=G(o.from(),i.from()),s=X(o.to(),i.to()),l=o.empty()?i.from()==i.head:o.from()==o.head;t>=r&&--t,e.splice(--r,2,new J(l?s:a,l?a:s))}}return new $(e,t)}function K(e,t){return new $([new J(e,t||e)],0)}function Q(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function Z(e,t){if(t.line<e.first)return ya(e.first,0);var n=e.first+e.size-1;return t.line>n?ya(n,_i(e,n).text.length):et(t,_i(e,t.line).text.length)}function et(e,t){var n=e.ch;return null==n||n>t?ya(e.line,t):0>n?ya(e.line,0):e}function tt(e,t){return t>=e.first&&t<e.first+e.size}function nt(e,t){for(var n=[],r=0;r<t.length;r++)n[r]=Z(e,t[r]);return n}function rt(e,t,n,r){if(e.cm&&e.cm.display.shift||e.extend){var i=t.anchor;if(r){var o=ba(n,i)<0;o!=ba(r,i)<0?(i=n,n=r):o!=ba(n,r)<0&&(n=r)}return new J(i,n)}return new J(r||n,n)}function it(e,t,n,r){ct(e,new $([rt(e,e.sel.primary(),t,n)],0),r)}function ot(e,t,n){for(var r=[],i=0;i<e.sel.ranges.length;i++)r[i]=rt(e,e.sel.ranges[i],t[i],null);var o=Y(r,e.sel.primIndex);ct(e,o,n)}function at(e,t,n,r){var i=e.sel.ranges.slice(0);i[t]=n,ct(e,Y(i,e.sel.primIndex),r)}function st(e,t,n,r){ct(e,K(t,n),r)}function lt(e,t){var n={ranges:t.ranges,update:function(t){this.ranges=[];for(var n=0;n<t.length;n++)this.ranges[n]=new J(Z(e,t[n].anchor),Z(e,t[n].head))}};return fs(e,"beforeSelectionChange",e,n),e.cm&&fs(e.cm,"beforeSelectionChange",e.cm,n),n.ranges!=t.ranges?Y(n.ranges,n.ranges.length-1):t}function ut(e,t,n){var r=e.history.done,i=fo(r);i&&i.ranges?(r[r.length-1]=t,ft(e,t,n)):ct(e,t,n)}function ct(e,t,n){ft(e,t,n),Ui(e,e.sel,e.cm?e.cm.curOp.id:0/0,n)}function ft(e,t,n){(ao(e,"beforeSelectionChange")||e.cm&&ao(e.cm,"beforeSelectionChange"))&&(t=lt(e,t));var r=n&&n.bias||(ba(t.primary().head,e.sel.primary().head)<0?-1:1);dt(e,pt(e,t,r,!0)),n&&n.scroll===!1||!e.cm||br(e.cm)}function dt(e,t){t.equals(e.sel)||(e.sel=t,e.cm&&(e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0,oo(e.cm)),no(e,"cursorActivity",e))}function ht(e){dt(e,pt(e,e.sel,null,!1),gs)}function pt(e,t,n,r){for(var i,o=0;o<t.ranges.length;o++){var a=t.ranges[o],s=gt(e,a.anchor,n,r),l=gt(e,a.head,n,r);(i||s!=a.anchor||l!=a.head)&&(i||(i=t.ranges.slice(0,o)),i[o]=new J(s,l))}return i?Y(i,t.primIndex):t}function gt(e,t,n,r){var i=!1,o=t,a=n||1;e.cantEdit=!1;e:for(;;){var s=_i(e,o.line);if(s.markedSpans)for(var l=0;l<s.markedSpans.length;++l){var u=s.markedSpans[l],c=u.marker;if((null==u.from||(c.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(c.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r&&(fs(c,"beforeCursorEnter"),c.explicitlyCleared)){if(s.markedSpans){--l;continue}break}if(!c.atomic)continue;var f=c.find(0>a?-1:1);if(0==ba(f,o)&&(f.ch+=a,f.ch<0?f=f.line>e.first?Z(e,ya(f.line-1)):null:f.ch>s.text.length&&(f=f.line<e.first+e.size-1?ya(f.line+1,0):null),!f)){if(i)return r?(e.cantEdit=!0,ya(e.first,0)):gt(e,t,n,!0);i=!0,f=t,a=-a}o=f;continue e}}return o}}function mt(e){for(var t=e.display,n=e.doc,r={},i=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),a=0;a<n.sel.ranges.length;a++){var s=n.sel.ranges[a],l=s.empty();(l||e.options.showCursorWhenSelecting)&&bt(e,s,i),l||xt(e,s,o)}if(e.options.moveInputWithCursor){var u=Xt(e,n.sel.primary().head,"div"),c=t.wrapper.getBoundingClientRect(),f=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+f.top-c.top)),r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+f.left-c.left))}return r}function vt(e,t){Co(e.display.cursorDiv,t.cursors),Co(e.display.selectionDiv,t.selection),null!=t.teTop&&(e.display.inputDiv.style.top=t.teTop+"px",e.display.inputDiv.style.left=t.teLeft+"px")}function yt(e){vt(e,mt(e))}function bt(e,t,n){var r=Xt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),i=n.appendChild(wo("div"," ","CodeMirror-cursor"));if(i.style.left=r.left+"px",i.style.top=r.top+"px",i.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px",r.other){var o=n.appendChild(wo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="",o.style.left=r.other.left+"px",o.style.top=r.other.top+"px",o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function xt(e,t,n){function r(e,t,n,r){0>t&&(t=0),t=Math.round(t),r=Math.round(r),s.appendChild(wo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==n?c-e:n)+"px; height: "+(r-t)+"px"))}function i(t,n,i){function o(n,r){return Vt(e,ya(t,n),"div",f,r)}var s,l,f=_i(a,t),d=f.text.length;return Ro(Ri(f),n||0,null==i?d:i,function(e,t,a){var f,h,p,g=o(e,"left");if(e==t)f=g,h=p=g.left;else{if(f=o(t-1,"right"),"rtl"==a){var m=g;g=f,f=m}h=g.left,p=f.right}null==n&&0==e&&(h=u),f.top-g.top>3&&(r(h,g.top,null,g.bottom),h=u,g.bottom<f.top&&r(h,g.bottom,null,f.top)),null==i&&t==d&&(p=c),(!s||g.top<s.top||g.top==s.top&&g.left<s.left)&&(s=g),(!l||f.bottom>l.bottom||f.bottom==l.bottom&&f.right>l.right)&&(l=f),u+1>h&&(h=u),r(h,f.top,p-h,f.bottom)}),{start:s,end:l}}var o=e.display,a=e.doc,s=document.createDocumentFragment(),l=At(e.display),u=l.left,c=o.lineSpace.offsetWidth-l.right,f=t.from(),d=t.to();if(f.line==d.line)i(f.line,f.ch,d.ch);else{var h=_i(a,f.line),p=_i(a,d.line),g=Qr(h)==Qr(p),m=i(f.line,f.ch,g?h.text.length+1:null).end,v=i(d.line,g?0:null,d.ch).start;g&&(m.top<v.top-2?(r(m.right,m.top,null,m.bottom),r(u,v.top,v.left,v.bottom)):r(m.right,m.top,v.left-m.right,m.bottom)),m.bottom<v.top&&r(u,m.bottom,null,v.top)}n.appendChild(s)}function wt(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var n=!0;t.cursorDiv.style.visibility="",e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function St(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,vo(Ct,e))}function Ct(e){var t=e.doc;if(t.frontier<t.first&&(t.frontier=t.first),!(t.frontier>=e.display.viewTo)){var n=+new Date+e.options.workTime,r=za(t.mode,Dt(e,t.frontier)),i=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(t.frontier>=e.display.viewFrom){var a=o.styles,s=hi(e,o,r,!0);o.styles=s.styles;var l=o.styleClasses,u=s.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var c=!a||a.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),f=0;!c&&f<a.length;++f)c=a[f]!=o.styles[f];c&&i.push(t.frontier),o.stateAfter=za(t.mode,r)}else gi(e,o.text,r),o.stateAfter=t.frontier%5==0?za(t.mode,r):null;return++t.frontier,+new Date>n?(St(e,e.options.workDelay),!0):void 0}),i.length&&un(e,function(){for(var t=0;t<i.length;t++)mn(e,i[t],"text")})}}function Tt(e,t,n){for(var r,i,o=e.doc,a=n?-1:t-(e.doc.mode.innerMode?1e3:100),s=t;s>a;--s){if(s<=o.first)return o.first;var l=_i(o,s-1);if(l.stateAfter&&(!n||s<=o.frontier))return s;var u=ys(l.text,null,e.options.tabSize);(null==i||r>u)&&(i=s-1,r=u)}return i}function Dt(e,t,n){var r=e.doc,i=e.display;if(!r.mode.startState)return!0;var o=Tt(e,t,n),a=o>r.first&&_i(r,o-1).stateAfter;return a=a?za(r.mode,a):Ba(r.mode),r.iter(o,t,function(n){gi(e,n.text,a);var s=o==t-1||o%5==0||o>=i.viewFrom&&o<i.viewTo;n.stateAfter=s?za(r.mode,a):null,++o}),n&&(r.frontier=o),a}function kt(e){return e.lineSpace.offsetTop}function Lt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function At(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Co(e.measure,wo("pre","x")),n=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(n.paddingLeft),right:parseInt(n.paddingRight)};return isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r),r}function Nt(e,t,n){var r=e.options.lineWrapping,i=r&&e.display.scroller.clientWidth;if(!t.measure.heights||r&&t.measure.width!=i){var o=t.measure.heights=[];if(r){t.measure.width=i;for(var a=t.text.firstChild.getClientRects(),s=0;s<a.length-1;s++){var l=a[s],u=a[s+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-n.top)}}o.push(n.bottom-n.top)}}function _t(e,t,n){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(Ii(e.rest[r])>n)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function Mt(e,t){t=Qr(t);var n=Ii(t),r=e.display.externalMeasured=new hn(e.doc,t,n);r.lineN=n;var i=r.built=vi(e,r);return r.text=i.pre,Co(e.display.lineMeasure,i.pre),r}function Et(e,t,n,r){return Ht(e,It(e,t),n,r)}function jt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[yn(e,t)];var n=e.display.externalMeasured;return n&&t>=n.lineN&&t<n.lineN+n.size?n:void 0}function It(e,t){var n=Ii(t),r=jt(e,n);r&&!r.text?r=null:r&&r.changes&&j(e,r,n,M(e)),r||(r=Mt(e,t));var i=_t(r,t,n);return{line:t,view:r,rect:null,map:i.map,cache:i.cache,before:i.before,hasHeights:!1}}function Ht(e,t,n,r,i){t.before&&(n=-1);var o,a=n+(r||"");return t.cache.hasOwnProperty(a)?o=t.cache[a]:(t.rect||(t.rect=t.view.text.getBoundingClientRect()),t.hasHeights||(Nt(e,t.view,t.rect),t.hasHeights=!0),o=Ot(e,t,n,r),o.bogus||(t.cache[a]=o)),{left:o.left,right:o.right,top:i?o.rtop:o.top,bottom:i?o.rbottom:o.bottom}}function Ot(e,t,n,r){for(var i,o,a,s,l=t.map,u=0;u<l.length;u+=3){var c=l[u],f=l[u+1];if(c>n?(o=0,a=1,s="left"):f>n?(o=n-c,a=o+1):(u==l.length-3||n==f&&l[u+3]>n)&&(a=f-c,o=a-1,n>=f&&(s="right")),null!=o){if(i=l[u+2],c==f&&r==(i.insertLeft?"left":"right")&&(s=r),"left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;)i=l[(u-=3)+2],s="left";if("right"==r&&o==f-c)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;)i=l[(u+=3)+2],s="right";break}}var d;if(3==i.nodeType){for(var u=0;4>u;u++){for(;o&&xo(t.line.text.charAt(c+o));)--o;for(;f>c+a&&xo(t.line.text.charAt(c+a));)++a;if(Zo&&9>ea&&0==o&&a==f-c)d=i.parentNode.getBoundingClientRect();else if(Zo&&e.options.lineWrapping){var h=ws(i,o,a).getClientRects();d=h.length?h["right"==r?h.length-1:0]:Ca}else d=ws(i,o,a).getBoundingClientRect()||Ca;if(d.left||d.right||0==o)break;a=o,o-=1,s="right"}Zo&&11>ea&&(d=Rt(e.display.measure,d))}else{o>0&&(s=r="right");var h;d=e.options.lineWrapping&&(h=i.getClientRects()).length>1?h["right"==r?h.length-1:0]:i.getBoundingClientRect()}if(Zo&&9>ea&&!o&&(!d||!d.left&&!d.right)){var p=i.parentNode.getClientRects()[0];d=p?{left:p.left,right:p.left+Qt(e.display),top:p.top,bottom:p.bottom}:Ca}for(var g=d.top-t.rect.top,m=d.bottom-t.rect.top,v=(g+m)/2,y=t.view.measure.heights,u=0;u<y.length-1&&!(v<y[u]);u++);var b=u?y[u-1]:0,x=y[u],w={left:("right"==s?d.right:d.left)-t.rect.left,right:("left"==s?d.left:d.right)-t.rect.left,top:b,bottom:x};return d.left||d.right||(w.bogus=!0),e.options.singleCursorHeightPerLine||(w.rtop=g,w.rbottom=m),w}function Rt(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Oo(e))return t;var n=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*n,right:t.right*n,top:t.top*r,bottom:t.bottom*r}}function Pt(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}function Ft(e){e.display.externalMeasure=null,So(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)Pt(e.display.view[t])}function Wt(e){Ft(e),e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null,e.options.lineWrapping||(e.display.maxLineChanged=!0),e.display.lineNumChars=null}function zt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Bt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function qt(e,t,n,r){if(t.widgets)for(var i=0;i<t.widgets.length;++i)if(t.widgets[i].above){var o=oi(t.widgets[i]);n.top+=o,n.bottom+=o}if("line"==r)return n;r||(r="local");var a=Oi(t);if("local"==r?a+=kt(e.display):a-=e.display.viewOffset,"page"==r||"window"==r){var s=e.display.lineSpace.getBoundingClientRect();a+=s.top+("window"==r?0:Bt());var l=s.left+("window"==r?0:zt());n.left+=l,n.right+=l}return n.top+=a,n.bottom+=a,n}function Ut(e,t,n){if("div"==n)return t;var r=t.left,i=t.top;if("page"==n)r-=zt(),i-=Bt();else if("local"==n||!n){var o=e.display.sizer.getBoundingClientRect();r+=o.left,i+=o.top}var a=e.display.lineSpace.getBoundingClientRect();return{left:r-a.left,top:i-a.top}}function Vt(e,t,n,r,i){return r||(r=_i(e.doc,t.line)),qt(e,r,Et(e,r,t.ch,i),n)}function Xt(e,t,n,r,i,o){function a(t,a){var s=Ht(e,i,t,a?"right":"left",o);return a?s.left=s.right:s.right=s.left,qt(e,r,s,n)}function s(e,t){var n=l[t],r=n.level%2;return e==Po(n)&&t&&n.level<l[t-1].level?(n=l[--t],e=Fo(n)-(n.level%2?0:1),r=!0):e==Fo(n)&&t<l.length-1&&n.level<l[t+1].level&&(n=l[++t],e=Po(n)-n.level%2,r=!1),r&&e==n.to&&e>n.from?a(e-1):a(e,r)}r=r||_i(e.doc,t.line),i||(i=It(e,r));var l=Ri(r),u=t.ch;if(!l)return a(u);var c=Xo(l,u),f=s(u,c);return null!=Hs&&(f.other=s(u,Hs)),f}function Gt(e,t){var n=0,t=Z(e.doc,t);e.options.lineWrapping||(n=Qt(e.display)*t.ch);var r=_i(e.doc,t.line),i=Oi(r)+kt(e.display);return{left:n,right:n,top:i,bottom:i+r.height}}function $t(e,t,n,r){var i=ya(e,t);return i.xRel=r,n&&(i.outside=!0),i}function Jt(e,t,n){var r=e.doc;if(n+=e.display.viewOffset,0>n)return $t(r.first,0,!0,-1);var i=Hi(r,n),o=r.first+r.size-1;if(i>o)return $t(r.first+r.size-1,_i(r,o).text.length,!0,1);0>t&&(t=0);for(var a=_i(r,i);;){var s=Yt(e,a,i,t,n),l=Yr(a),u=l&&l.find(0,!0);if(!l||!(s.ch>u.from.ch||s.ch==u.from.ch&&s.xRel>0))return s;i=Ii(a=u.to.line)}}function Yt(e,t,n,r,i){function o(r){var i=Xt(e,ya(n,r),"line",t,u);return s=!0,a>i.bottom?i.left-l:a<i.top?i.left+l:(s=!1,i.left)}var a=i-Oi(t),s=!1,l=2*e.display.wrapper.clientWidth,u=It(e,t),c=Ri(t),f=t.text.length,d=Wo(t),h=zo(t),p=o(d),g=s,m=o(h),v=s;if(r>m)return $t(n,h,v,1);for(;;){if(c?h==d||h==$o(t,d,1):1>=h-d){for(var y=p>r||m-r>=r-p?d:h,b=r-(y==d?p:m);xo(t.text.charAt(y));)++y;var x=$t(n,y,y==d?g:v,-1>b?-1:b>1?1:0);return x}var w=Math.ceil(f/2),S=d+w;if(c){S=d;for(var C=0;w>C;++C)S=$o(t,S,1)}var T=o(S);T>r?(h=S,m=T,(v=s)&&(m+=1e3),f=w):(d=S,p=T,g=s,f-=w)}}function Kt(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==xa){xa=wo("pre");for(var t=0;49>t;++t)xa.appendChild(document.createTextNode("x")),xa.appendChild(wo("br"));xa.appendChild(document.createTextNode("x"))}Co(e.measure,xa);var n=xa.offsetHeight/50;return n>3&&(e.cachedTextHeight=n),So(e.measure),n||1}function Qt(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=wo("span","xxxxxxxxxx"),n=wo("pre",[t]);Co(e.measure,n);var r=t.getBoundingClientRect(),i=(r.right-r.left)/10;return i>2&&(e.cachedCharWidth=i),i||10}function Zt(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Da},Ta?Ta.ops.push(e.curOp):e.curOp.ownsGroup=Ta={ops:[e.curOp],delayedCallbacks:[]}}function en(e){var t=e.delayedCallbacks,n=0;do{for(;n<t.length;n++)t[n]();for(var r=0;r<e.ops.length;r++){var i=e.ops[r];if(i.cursorActivityHandlers)for(;i.cursorActivityCalled<i.cursorActivityHandlers.length;)i.cursorActivityHandlers[i.cursorActivityCalled++](i.cm)}}while(n<t.length)}function tn(e){var t=e.curOp,n=t.ownsGroup;if(n)try{en(n)}finally{Ta=null;for(var r=0;r<n.ops.length;r++)n.ops[r].cm.curOp=null;nn(n)}}function nn(e){for(var t=e.ops,n=0;n<t.length;n++)rn(t[n]);for(var n=0;n<t.length;n++)on(t[n]);for(var n=0;n<t.length;n++)an(t[n]);for(var n=0;n<t.length;n++)sn(t[n]);for(var n=0;n<t.length;n++)ln(t[n])}function rn(e){var t=e.cm,n=t.display;e.updateMaxLine&&h(t),e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<n.viewFrom||e.scrollToPos.to.line>=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new C(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function on(e){e.updatedDisplay=e.mustUpdate&&T(e.cm,e.update)}function an(e){var t=e.cm,n=t.display;e.updatedDisplay&&N(t),e.barMeasure=m(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=Et(t,n.maxLine,n.maxLine.text.length).left+3,e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo+hs-n.scroller.clientWidth)),(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=mt(t))}function sn(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft<t.doc.scrollLeft&&Bn(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0),t.display.maxLineChanged=!1),e.newSelectionNodes&&vt(t,e.newSelectionNodes),e.updatedDisplay&&L(t,e.barMeasure),(e.updatedDisplay||e.startHeight!=t.doc.height)&&v(t,e.barMeasure),e.selectionChanged&&wt(t),t.state.focused&&e.updateInput&&Dn(t,e.typing)}function ln(e){var t=e.cm,n=t.display,r=t.doc;if(null!=e.adjustWidthTo&&Math.abs(e.barMeasure.scrollWidth-t.display.scroller.scrollWidth)>1&&v(t),e.updatedDisplay&&D(t,e.update),null==n.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(n.wheelStartX=n.wheelStartY=null),null!=e.scrollTop&&(n.scroller.scrollTop!=e.scrollTop||e.forceScroll)){var i=Math.max(0,Math.min(n.scroller.scrollHeight-n.scroller.clientHeight,e.scrollTop));n.scroller.scrollTop=n.scrollbarV.scrollTop=r.scrollTop=i}if(null!=e.scrollLeft&&(n.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){var o=Math.max(0,Math.min(n.scroller.scrollWidth-n.scroller.clientWidth,e.scrollLeft));n.scroller.scrollLeft=n.scrollbarH.scrollLeft=r.scrollLeft=o,b(t)}if(e.scrollToPos){var a=gr(t,Z(r,e.scrollToPos.from),Z(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&pr(t,a)}var s=e.maybeHiddenMarkers,l=e.maybeUnhiddenMarkers;if(s)for(var u=0;u<s.length;++u)s[u].lines.length||fs(s[u],"hide");if(l)for(var u=0;u<l.length;++u)l[u].lines.length&&fs(l[u],"unhide");n.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop),e.updatedDisplay&&ta&&(t.options.lineWrapping&&A(t,e.barMeasure),e.barMeasure.scrollWidth>e.barMeasure.clientWidth&&e.barMeasure.scrollWidth<e.barMeasure.clientWidth+1&&!g(t)&&v(t)),e.changeObjs&&fs(t,"changes",t,e.changeObjs)}function un(e,t){if(e.curOp)return t();Zt(e);try{return t()}finally{tn(e)}}function cn(e,t){return function(){if(e.curOp)return t.apply(e,arguments);Zt(e);try{return t.apply(e,arguments)}finally{tn(e)}}}function fn(e){return function(){if(this.curOp)return e.apply(this,arguments);Zt(this);try{return e.apply(this,arguments)}finally{tn(this)}}}function dn(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);Zt(t);try{return e.apply(this,arguments)}finally{tn(t)}}}function hn(e,t,n){this.line=t,this.rest=Zr(t),this.size=this.rest?Ii(fo(this.rest))-n+1:1,this.node=this.text=null,this.hidden=ni(e,t)}function pn(e,t,n){for(var r,i=[],o=t;n>o;o=r){var a=new hn(e.doc,_i(e.doc,o),o);r=o+a.size,i.push(a)}return i}function gn(e,t,n,r){null==t&&(t=e.doc.first),null==n&&(n=e.doc.first+e.doc.size),r||(r=0);var i=e.display;if(r&&n<i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>t)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=i.viewTo)va&&ei(e.doc,t)<i.viewTo&&vn(e);else if(n<=i.viewFrom)va&&ti(e.doc,n+r)>i.viewFrom?vn(e):(i.viewFrom+=r,i.viewTo+=r); else if(t<=i.viewFrom&&n>=i.viewTo)vn(e);else if(t<=i.viewFrom){var o=bn(e,n,n+r,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=r):vn(e)}else if(n>=i.viewTo){var o=bn(e,t,t,-1);o?(i.view=i.view.slice(0,o.index),i.viewTo=o.lineN):vn(e)}else{var a=bn(e,t,t,-1),s=bn(e,n,n+r,1);a&&s?(i.view=i.view.slice(0,a.index).concat(pn(e,a.lineN,s.lineN)).concat(i.view.slice(s.index)),i.viewTo+=r):vn(e)}var l=i.externalMeasured;l&&(n<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(i.externalMeasured=null))}function mn(e,t,n){e.curOp.viewChanged=!0;var r=e.display,i=e.display.externalMeasured;if(i&&t>=i.lineN&&t<i.lineN+i.size&&(r.externalMeasured=null),!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[yn(e,t)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==ho(a,n)&&a.push(n)}}}function vn(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function yn(e,t){if(t>=e.display.viewTo)return null;if(t-=e.display.viewFrom,0>t)return null;for(var n=e.display.view,r=0;r<n.length;r++)if(t-=n[r].size,0>t)return r}function bn(e,t,n,r){var i,o=yn(e,t),a=e.display.view;if(!va||n==e.doc.first+e.doc.size)return{index:o,lineN:n};for(var s=0,l=e.display.viewFrom;o>s;s++)l+=a[s].size;if(l!=t){if(r>0){if(o==a.length-1)return null;i=l+a[o].size-t,o++}else i=l-t;t+=i,n+=i}for(;ei(e.doc,n)!=n;){if(o==(0>r?0:a.length-1))return null;n+=r*a[o-(0>r?1:0)].size,o+=r}return{index:o,lineN:n}}function xn(e,t,n){var r=e.display,i=r.view;0==i.length||t>=r.viewTo||n<=r.viewFrom?(r.view=pn(e,t,n),r.viewFrom=t):(r.viewFrom>t?r.view=pn(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(yn(e,t))),r.viewFrom=t,r.viewTo<n?r.view=r.view.concat(pn(e,r.viewTo,n)):r.viewTo>n&&(r.view=r.view.slice(0,yn(e,n)))),r.viewTo=n}function wn(e){for(var t=e.display.view,n=0,r=0;r<t.length;r++){var i=t[r];i.hidden||i.node&&!i.changes||++n}return n}function Sn(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){Tn(e),e.state.focused&&Sn(e)})}function Cn(e){function t(){var r=Tn(e);r||n?(e.display.pollingFast=!1,Sn(e)):(n=!0,e.display.poll.set(60,t))}var n=!1;e.display.pollingFast=!0,e.display.poll.set(20,t)}function Tn(e){var t=e.display.input,n=e.display.prevInput,r=e.doc;if(!e.state.focused||Ms(t)&&!n||An(e)||e.options.disableInput)return!1;e.state.pasteIncoming&&e.state.fakedLastChar&&(t.value=t.value.substring(0,t.value.length-1),e.state.fakedLastChar=!1);var i=t.value;if(i==n&&!e.somethingSelected())return!1;if(Zo&&ea>=9&&e.display.inputHasSelection===i||fa&&/[\uf700-\uf7ff]/.test(i))return Dn(e),!1;var o=!e.curOp;o&&Zt(e),e.display.shift=!1,8203!=i.charCodeAt(0)||r.sel!=e.display.selForContextMenu||n||(n="​");for(var a=0,s=Math.min(n.length,i.length);s>a&&n.charCodeAt(a)==i.charCodeAt(a);)++a;var l=i.slice(a),u=_s(l),c=null;e.state.pasteIncoming&&r.sel.ranges.length>1&&(ka&&ka.join("\n")==l?c=r.sel.ranges.length%ka.length==0&&po(ka,_s):u.length==r.sel.ranges.length&&(c=po(u,function(e){return[e]})));for(var f=r.sel.ranges.length-1;f>=0;f--){var d=r.sel.ranges[f],h=d.from(),p=d.to();a<n.length?h=ya(h.line,h.ch-(n.length-a)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(p=ya(p.line,Math.min(_i(r,p.line).text.length,p.ch+fo(u).length)));var g=e.curOp.updateInput,m={from:h,to:p,text:c?c[f%c.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};if(sr(e.doc,m),no(e,"inputRead",e,m),l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!f||r.sel.ranges[f-1].head.line!=d.head.line)){var v=e.getModeAt(d.head),y=Ea(m);if(v.electricChars){for(var b=0;b<v.electricChars.length;b++)if(l.indexOf(v.electricChars.charAt(b))>-1){wr(e,y.line,"smart");break}}else v.electricInput&&v.electricInput.test(_i(r,y.line).text.slice(0,y.ch))&&wr(e,y.line,"smart")}}return br(e),e.curOp.updateInput=g,e.curOp.typing=!0,i.length>1e3||i.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=i,o&&tn(e),e.state.pasteIncoming=e.state.cutIncoming=!1,!0}function Dn(e,t){var n,r,i=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=i.sel.primary();n=Es&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var a=n?"-":r||e.getSelection();e.display.input.value=a,e.state.focused&&xs(e.display.input),Zo&&ea>=9&&(e.display.inputHasSelection=a)}else t||(e.display.prevInput=e.display.input.value="",Zo&&ea>=9&&(e.display.inputHasSelection=null));e.display.inaccurateSelection=n}function kn(e){"nocursor"==e.options.readOnly||ca&&Do()==e.display.input||e.display.input.focus()}function Ln(e){e.state.focused||(kn(e),Qn(e))}function An(e){return e.options.readOnly||e.doc.cantEdit}function Nn(e){function t(){e.state.focused&&setTimeout(vo(kn,e),0)}function n(t){io(e,t)||ls(t)}function r(t){if(e.somethingSelected())ka=e.getSelections(),i.inaccurateSelection&&(i.prevInput="",i.inaccurateSelection=!1,i.input.value=ka.join("\n"),xs(i.input));else{for(var n=[],r=[],o=0;o<e.doc.sel.ranges.length;o++){var a=e.doc.sel.ranges[o].head.line,s={anchor:ya(a,0),head:ya(a+1,0)};r.push(s),n.push(e.getRange(s.anchor,s.head))}"cut"==t.type?e.setSelections(r,null,gs):(i.prevInput="",i.input.value=n.join("\n"),xs(i.input)),ka=n}"cut"==t.type&&(e.state.cutIncoming=!0)}var i=e.display;us(i.scroller,"mousedown",cn(e,jn)),Zo&&11>ea?us(i.scroller,"dblclick",cn(e,function(t){if(!io(e,t)){var n=En(e,t);if(n&&!Pn(e,t)&&!Mn(e.display,t)){as(t);var r=e.findWordAt(n);it(e.doc,r.anchor,r.head)}}})):us(i.scroller,"dblclick",function(t){io(e,t)||as(t)}),us(i.lineSpace,"selectstart",function(e){Mn(i,e)||as(e)}),ga||us(i.scroller,"contextmenu",function(t){er(e,t)}),us(i.scroller,"scroll",function(){i.scroller.clientHeight&&(zn(e,i.scroller.scrollTop),Bn(e,i.scroller.scrollLeft,!0),fs(e,"scroll",e))}),us(i.scrollbarV,"scroll",function(){i.scroller.clientHeight&&zn(e,i.scrollbarV.scrollTop)}),us(i.scrollbarH,"scroll",function(){i.scroller.clientHeight&&Bn(e,i.scrollbarH.scrollLeft)}),us(i.scroller,"mousewheel",function(t){qn(e,t)}),us(i.scroller,"DOMMouseScroll",function(t){qn(e,t)}),us(i.scrollbarH,"mousedown",t),us(i.scrollbarV,"mousedown",t),us(i.wrapper,"scroll",function(){i.wrapper.scrollTop=i.wrapper.scrollLeft=0}),us(i.input,"keyup",function(t){Yn.call(e,t)}),us(i.input,"input",function(){Zo&&ea>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null),Cn(e)}),us(i.input,"keydown",cn(e,$n)),us(i.input,"keypress",cn(e,Kn)),us(i.input,"focus",vo(Qn,e)),us(i.input,"blur",vo(Zn,e)),e.options.dragDrop&&(us(i.scroller,"dragstart",function(t){Wn(e,t)}),us(i.scroller,"dragenter",n),us(i.scroller,"dragover",n),us(i.scroller,"drop",cn(e,Fn))),us(i.scroller,"paste",function(t){Mn(i,t)||(e.state.pasteIncoming=!0,kn(e),Cn(e))}),us(i.input,"paste",function(){if(ta&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=i.input.selectionStart,n=i.input.selectionEnd;i.input.value+="$",i.input.selectionEnd=n,i.input.selectionStart=t,e.state.fakedLastChar=!0}e.state.pasteIncoming=!0,Cn(e)}),us(i.input,"cut",r),us(i.input,"copy",r),aa&&us(i.sizer,"mouseup",function(){Do()==i.input&&i.input.blur(),kn(e)})}function _n(e){var t=e.display;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,e.setSize()}function Mn(e,t){for(var n=eo(t);n!=e.wrapper;n=n.parentNode)if(!n||n.ignoreEvents||n.parentNode==e.sizer&&n!=e.mover)return!0}function En(e,t,n,r){var i=e.display;if(!n){var o=eo(t);if(o==i.scrollbarH||o==i.scrollbarV||o==i.scrollbarFiller||o==i.gutterFiller)return null}var a,s,l=i.lineSpace.getBoundingClientRect();try{a=t.clientX-l.left,s=t.clientY-l.top}catch(t){return null}var u,c=Jt(e,a,s);if(r&&1==c.xRel&&(u=_i(e.doc,c.line).text).length==c.ch){var f=ys(u,u.length,e.options.tabSize)-u.length;c=ya(c.line,Math.max(0,Math.round((a-At(e.display).left)/Qt(e.display))-f))}return c}function jn(e){if(!io(this,e)){var t=this,n=t.display;if(n.shift=e.shiftKey,Mn(n,e))return void(ta||(n.scroller.draggable=!1,setTimeout(function(){n.scroller.draggable=!0},100)));if(!Pn(t,e)){var r=En(t,e);switch(window.focus(),to(e)){case 1:r?In(t,e,r):eo(e)==n.scroller&&as(e);break;case 2:ta&&(t.state.lastMiddleDown=+new Date),r&&it(t.doc,r),setTimeout(vo(kn,t),20),as(e);break;case 3:ga&&er(t,e)}}}}function In(e,t,n){setTimeout(vo(Ln,e),0);var r,i=+new Date;Sa&&Sa.time>i-400&&0==ba(Sa.pos,n)?r="triple":wa&&wa.time>i-400&&0==ba(wa.pos,n)?(r="double",Sa={time:i,pos:n}):(r="single",wa={time:i,pos:n});var o=e.doc.sel,a=fa?t.metaKey:t.ctrlKey;e.options.dragDrop&&Ns&&!An(e)&&"single"==r&&o.contains(n)>-1&&o.somethingSelected()?Hn(e,t,n,a):On(e,t,n,r,a)}function Hn(e,t,n,r){var i=e.display,o=cn(e,function(a){ta&&(i.scroller.draggable=!1),e.state.draggingText=!1,cs(document,"mouseup",o),cs(i.scroller,"drop",o),Math.abs(t.clientX-a.clientX)+Math.abs(t.clientY-a.clientY)<10&&(as(a),r||it(e.doc,n),kn(e),Zo&&9==ea&&setTimeout(function(){document.body.focus(),kn(e)},20))});ta&&(i.scroller.draggable=!0),e.state.draggingText=o,i.scroller.dragDrop&&i.scroller.dragDrop(),us(document,"mouseup",o),us(i.scroller,"drop",o)}function On(e,t,n,r,i){function o(t){if(0!=ba(g,t))if(g=t,"rect"==r){for(var i=[],o=e.options.tabSize,a=ys(_i(u,n.line).text,n.ch,o),s=ys(_i(u,t.line).text,t.ch,o),l=Math.min(a,s),h=Math.max(a,s),p=Math.min(n.line,t.line),m=Math.min(e.lastLine(),Math.max(n.line,t.line));m>=p;p++){var v=_i(u,p).text,y=uo(v,l,o);l==h?i.push(new J(ya(p,y),ya(p,y))):v.length>y&&i.push(new J(ya(p,y),ya(p,uo(v,h,o))))}i.length||i.push(new J(n,n)),ct(u,Y(d.ranges.slice(0,f).concat(i),f),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var b=c,x=b.anchor,w=t;if("single"!=r){if("double"==r)var S=e.findWordAt(t);else var S=new J(ya(t.line,0),Z(u,ya(t.line+1,0)));ba(S.anchor,x)>0?(w=S.head,x=G(b.from(),S.anchor)):(w=S.anchor,x=X(b.to(),S.head))}var i=d.ranges.slice(0);i[f]=new J(Z(u,x),w),ct(u,Y(i,f),ms)}}function a(t){var n=++v,i=En(e,t,!0,"rect"==r);if(i)if(0!=ba(i,g)){Ln(e),o(i);var s=y(l,u);(i.line>=s.to||i.line<s.from)&&setTimeout(cn(e,function(){v==n&&a(t)}),150)}else{var c=t.clientY<m.top?-20:t.clientY>m.bottom?20:0;c&&setTimeout(cn(e,function(){v==n&&(l.scroller.scrollTop+=c,a(t))}),50)}}function s(t){v=1/0,as(t),kn(e),cs(document,"mousemove",b),cs(document,"mouseup",x),u.history.lastSelOrigin=null}var l=e.display,u=e.doc;as(t);var c,f,d=u.sel;if(i&&!t.shiftKey?(f=u.sel.contains(n),c=f>-1?u.sel.ranges[f]:new J(n,n)):c=u.sel.primary(),t.altKey)r="rect",i||(c=new J(n,n)),n=En(e,t,!0,!0),f=-1;else if("double"==r){var h=e.findWordAt(n);c=e.display.shift||u.extend?rt(u,c,h.anchor,h.head):h}else if("triple"==r){var p=new J(ya(n.line,0),Z(u,ya(n.line+1,0)));c=e.display.shift||u.extend?rt(u,c,p.anchor,p.head):p}else c=rt(u,c,n);i?f>-1?at(u,f,c,ms):(f=u.sel.ranges.length,ct(u,Y(u.sel.ranges.concat([c]),f),{scroll:!1,origin:"*mouse"})):(f=0,ct(u,new $([c],0),ms),d=u.sel);var g=n,m=l.wrapper.getBoundingClientRect(),v=0,b=cn(e,function(e){to(e)?a(e):s(e)}),x=cn(e,s);us(document,"mousemove",b),us(document,"mouseup",x)}function Rn(e,t,n,r,i){try{var o=t.clientX,a=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&as(t);var s=e.display,l=s.lineDiv.getBoundingClientRect();if(a>l.bottom||!ao(e,n))return Zi(t);a-=l.top-s.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var c=s.gutters.childNodes[u];if(c&&c.getBoundingClientRect().right>=o){var f=Hi(e.doc,a),d=e.options.gutters[u];return i(e,n,e,f,d,t),Zi(t)}}}function Pn(e,t){return Rn(e,t,"gutterClick",!0,no)}function Fn(e){var t=this;if(!io(t,e)&&!Mn(t.display,e)){as(e),Zo&&(La=+new Date);var n=En(t,e,!0),r=e.dataTransfer.files;if(n&&!An(t))if(r&&r.length&&window.FileReader&&window.File)for(var i=r.length,o=Array(i),a=0,s=function(e,r){var s=new FileReader;s.onload=cn(t,function(){if(o[r]=s.result,++a==i){n=Z(t.doc,n);var e={from:n,to:n,text:_s(o.join("\n")),origin:"paste"};sr(t.doc,e),ut(t.doc,K(n,Ea(e)))}}),s.readAsText(e)},l=0;i>l;++l)s(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(n)>-1)return t.state.draggingText(e),void setTimeout(vo(kn,t),20);try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(fa?e.metaKey:e.ctrlKey))var u=t.listSelections();if(ft(t.doc,K(n,n)),u)for(var l=0;l<u.length;++l)hr(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste"),kn(t)}}catch(e){}}}}function Wn(e,t){if(Zo&&(!e.state.draggingText||+new Date-La<100))return void ls(t);if(!io(e,t)&&!Mn(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.setDragImage&&!oa)){var n=wo("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",ia&&(n.width=n.height=1,e.display.wrapper.appendChild(n),n._top=n.offsetTop),t.dataTransfer.setDragImage(n,0,0),ia&&n.parentNode.removeChild(n)}}function zn(e,t){Math.abs(e.doc.scrollTop-t)<2||(e.doc.scrollTop=t,Yo||k(e,{top:t}),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t),e.display.scrollbarV.scrollTop!=t&&(e.display.scrollbarV.scrollTop=t),Yo&&k(e),St(e,100))}function Bn(e,t,n){(n?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)||(t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth),e.doc.scrollLeft=t,b(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbarH.scrollLeft!=t&&(e.display.scrollbarH.scrollLeft=t))}function qn(e,t){var n=t.wheelDeltaX,r=t.wheelDeltaY;null==n&&t.detail&&t.axis==t.HORIZONTAL_AXIS&&(n=t.detail),null==r&&t.detail&&t.axis==t.VERTICAL_AXIS?r=t.detail:null==r&&(r=t.wheelDelta);var i=e.display,o=i.scroller;if(n&&o.scrollWidth>o.clientWidth||r&&o.scrollHeight>o.clientHeight){if(r&&fa&&ta)e:for(var a=t.target,s=i.view;a!=o;a=a.parentNode)for(var l=0;l<s.length;l++)if(s[l].node==a){e.display.currentWheelTarget=a;break e}if(n&&!Yo&&!ia&&null!=Na)return r&&zn(e,Math.max(0,Math.min(o.scrollTop+r*Na,o.scrollHeight-o.clientHeight))),Bn(e,Math.max(0,Math.min(o.scrollLeft+n*Na,o.scrollWidth-o.clientWidth))),as(t),void(i.wheelStartX=null);if(r&&null!=Na){var u=r*Na,c=e.doc.scrollTop,f=c+i.wrapper.clientHeight;0>u?c=Math.max(0,c+u-50):f=Math.min(e.doc.height,f+u+50),k(e,{top:c,bottom:f})}20>Aa&&(null==i.wheelStartX?(i.wheelStartX=o.scrollLeft,i.wheelStartY=o.scrollTop,i.wheelDX=n,i.wheelDY=r,setTimeout(function(){if(null!=i.wheelStartX){var e=o.scrollLeft-i.wheelStartX,t=o.scrollTop-i.wheelStartY,n=t&&i.wheelDY&&t/i.wheelDY||e&&i.wheelDX&&e/i.wheelDX;i.wheelStartX=i.wheelStartY=null,n&&(Na=(Na*Aa+n)/(Aa+1),++Aa)}},200)):(i.wheelDX+=n,i.wheelDY+=r))}}function Un(e,t,n){if("string"==typeof t&&(t=qa[t],!t))return!1;e.display.pollingFast&&Tn(e)&&(e.display.pollingFast=!1);var r=e.display.shift,i=!1;try{An(e)&&(e.state.suppressEdits=!0),n&&(e.display.shift=!1),i=t(e)!=ps}finally{e.display.shift=r,e.state.suppressEdits=!1}return i}function Vn(e){var t=e.state.keyMaps.slice(0);return e.options.extraKeys&&t.push(e.options.extraKeys),t.push(e.options.keyMap),t}function Xn(e,t){var n=Lr(e.options.keyMap),r=n.auto;clearTimeout(_a),r&&!Xa(t)&&(_a=setTimeout(function(){Lr(e.options.keyMap)==n&&(e.options.keyMap=r.call?r.call(null,e):r,s(e))},50));var i=Ga(t,!0),o=!1;if(!i)return!1;var a=Vn(e);return o=t.shiftKey?Va("Shift-"+i,a,function(t){return Un(e,t,!0)})||Va(i,a,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Un(e,t):void 0}):Va(i,a,function(t){return Un(e,t)}),o&&(as(t),wt(e),no(e,"keyHandled",e,i,t)),o}function Gn(e,t,n){var r=Va("'"+n+"'",Vn(e),function(t){return Un(e,t,!0)});return r&&(as(t),wt(e),no(e,"keyHandled",e,"'"+n+"'",t)),r}function $n(e){var t=this;if(Ln(t),!io(t,e)){Zo&&11>ea&&27==e.keyCode&&(e.returnValue=!1);var n=e.keyCode;t.display.shift=16==n||e.shiftKey;var r=Xn(t,e);ia&&(Ma=r?n:null,!r&&88==n&&!Es&&(fa?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")),18!=n||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||Jn(t)}}function Jn(e){function t(e){18!=e.keyCode&&e.altKey||(Lo(n,"CodeMirror-crosshair"),cs(document,"keyup",t),cs(document,"mouseover",t))}var n=e.display.lineDiv;Ao(n,"CodeMirror-crosshair"),us(document,"keyup",t),us(document,"mouseover",t)}function Yn(e){16==e.keyCode&&(this.doc.sel.shift=!1),io(this,e)}function Kn(e){var t=this;if(!(io(t,e)||e.ctrlKey&&!e.altKey||fa&&e.metaKey)){var n=e.keyCode,r=e.charCode;if(ia&&n==Ma)return Ma=null,void as(e);if(!(ia&&(!e.which||e.which<10)||aa)||!Xn(t,e)){var i=String.fromCharCode(null==r?n:r);Gn(t,e,i)||(Zo&&ea>=9&&(t.display.inputHasSelection=null),Cn(t))}}}function Qn(e){"nocursor"!=e.options.readOnly&&(e.state.focused||(fs(e,"focus",e),e.state.focused=!0,Ao(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(Dn(e),ta&&setTimeout(vo(Dn,e,!0),0))),Sn(e),wt(e))}function Zn(e){e.state.focused&&(fs(e,"blur",e),e.state.focused=!1,Lo(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function er(e,t){function n(){if(null!=i.input.selectionStart){var t=e.somethingSelected(),n=i.input.value="​"+(t?i.input.value:"");i.prevInput=t?"":"​",i.input.selectionStart=1,i.input.selectionEnd=n.length,i.selForContextMenu=e.doc.sel}}function r(){if(i.inputDiv.style.position="relative",i.input.style.cssText=l,Zo&&9>ea&&(i.scrollbarV.scrollTop=i.scroller.scrollTop=a),Sn(e),null!=i.input.selectionStart){(!Zo||Zo&&9>ea)&&n();var t=0,r=function(){i.selForContextMenu==e.doc.sel&&0==i.input.selectionStart?cn(e,qa.selectAll)(e):t++<10?i.detectingSelectAll=setTimeout(r,500):Dn(e)};i.detectingSelectAll=setTimeout(r,200)}}if(!io(e,t,"contextmenu")){var i=e.display;if(!Mn(i,t)&&!tr(e,t)){var o=En(e,t),a=i.scroller.scrollTop;if(o&&!ia){var s=e.options.resetSelectionOnContextMenu;s&&-1==e.doc.sel.contains(o)&&cn(e,ct)(e.doc,K(o),gs);var l=i.input.style.cssText;if(i.inputDiv.style.position="absolute",i.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(Zo?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",ta)var u=window.scrollY;if(kn(e),ta&&window.scrollTo(null,u),Dn(e),e.somethingSelected()||(i.input.value=i.prevInput=" "),i.selForContextMenu=e.doc.sel,clearTimeout(i.detectingSelectAll),Zo&&ea>=9&&n(),ga){ls(t);var c=function(){cs(window,"mouseup",c),setTimeout(r,20)};us(window,"mouseup",c)}else setTimeout(r,50)}}}}function tr(e,t){return ao(e,"gutterContextMenu")?Rn(e,t,"gutterContextMenu",!1,fs):!1}function nr(e,t){if(ba(e,t.from)<0)return e;if(ba(e,t.to)<=0)return Ea(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=Ea(t).ch-t.to.ch),ya(n,r)}function rr(e,t){for(var n=[],r=0;r<e.sel.ranges.length;r++){var i=e.sel.ranges[r];n.push(new J(nr(i.anchor,t),nr(i.head,t)))}return Y(n,e.sel.primIndex)}function ir(e,t,n){return e.line==t.line?ya(n.line,e.ch-t.ch+n.ch):ya(n.line+(e.line-t.line),e.ch)}function or(e,t,n){for(var r=[],i=ya(e.first,0),o=i,a=0;a<t.length;a++){var s=t[a],l=ir(s.from,i,o),u=ir(Ea(s),i,o);if(i=s.to,o=u,"around"==n){var c=e.sel.ranges[a],f=ba(c.head,c.anchor)<0;r[a]=new J(f?u:l,f?l:u)}else r[a]=new J(l,l)}return new $(r,e.sel.primIndex)}function ar(e,t,n){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};return n&&(r.update=function(t,n,r,i){t&&(this.from=Z(e,t)),n&&(this.to=Z(e,n)),r&&(this.text=r),void 0!==i&&(this.origin=i)}),fs(e,"beforeChange",e,r),e.cm&&fs(e.cm,"beforeChange",e.cm,r),r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function sr(e,t,n){if(e.cm){if(!e.cm.curOp)return cn(e.cm,sr)(e,t,n);if(e.cm.state.suppressEdits)return}if(!(ao(e,"beforeChange")||e.cm&&ao(e.cm,"beforeChange"))||(t=ar(e,t,!0))){var r=ma&&!n&&Br(e,t.from,t.to);if(r)for(var i=r.length-1;i>=0;--i)lr(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text});else lr(e,t)}}function lr(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ba(t.from,t.to)){var n=rr(e,t);Bi(e,t,n,e.cm?e.cm.curOp.id:0/0),fr(e,t,n,Fr(e,t));var r=[];Ai(e,function(e,n){n||-1!=ho(r,e.history)||(Qi(e.history,t),r.push(e.history)),fr(e,t,null,Fr(e,t))})}}function ur(e,t,n){if(!e.cm||!e.cm.state.suppressEdits){for(var r,i=e.history,o=e.sel,a="undo"==t?i.done:i.undone,s="undo"==t?i.undone:i.done,l=0;l<a.length&&(r=a[l],n?!r.ranges||r.equals(e.sel):r.ranges);l++);if(l!=a.length){for(i.lastOrigin=i.lastSelOrigin=null;r=a.pop(),r.ranges;){if(Vi(r,s),n&&!r.equals(e.sel))return void ct(e,r,{clearRedo:!1});o=r}var u=[];Vi(o,s),s.push({changes:u,generation:i.generation}),i.generation=r.generation||++i.maxGeneration;for(var c=ao(e,"beforeChange")||e.cm&&ao(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var f=r.changes[l];if(f.origin=t,c&&!ar(e,f,!1))return void(a.length=0);u.push(Fi(e,f));var d=l?rr(e,f):fo(a);fr(e,f,d,zr(e,f)),!l&&e.cm&&e.cm.scrollIntoView({from:f.from,to:Ea(f)});var h=[];Ai(e,function(e,t){t||-1!=ho(h,e.history)||(Qi(e.history,f),h.push(e.history)),fr(e,f,null,zr(e,f))})}}}}function cr(e,t){if(0!=t&&(e.first+=t,e.sel=new $(po(e.sel.ranges,function(e){return new J(ya(e.anchor.line+t,e.anchor.ch),ya(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){gn(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;r<n.viewTo;r++)mn(e.cm,r,"gutter")}}function fr(e,t,n,r){if(e.cm&&!e.cm.curOp)return cn(e.cm,fr)(e,t,n,r);if(t.to.line<e.first)return void cr(e,t.text.length-1-(t.to.line-t.from.line));if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var i=t.text.length-1-(e.first-t.from.line);cr(e,i),t={from:ya(e.first,0),to:ya(t.to.line+i,t.to.ch),text:[fo(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:ya(o,_i(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=Mi(e,t.from,t.to),n||(n=rr(e,t)),e.cm?dr(e.cm,t,r):Di(e,t,r),ft(e,n,gs)}}function dr(e,t,n){var r=e.doc,i=e.display,a=t.from,s=t.to,l=!1,u=a.line;e.options.lineWrapping||(u=Ii(Qr(_i(r,a.line))),r.iter(u,s.line+1,function(e){return e==i.maxLine?(l=!0,!0):void 0})),r.sel.contains(t.from,t.to)>-1&&oo(e),Di(r,t,n,o(e)),e.options.lineWrapping||(r.iter(u,a.line+t.text.length,function(e){var t=d(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0)),r.frontier=Math.min(r.frontier,a.line),St(e,400);var c=t.text.length-(s.line-a.line)-1;a.line!=s.line||1!=t.text.length||Ti(e.doc,t)?gn(e,a.line,s.line+1,c):mn(e,a.line,"text");var f=ao(e,"changes"),h=ao(e,"change");if(h||f){var p={from:a,to:s,text:t.text,removed:t.removed,origin:t.origin};h&&no(e,"change",e,p),f&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(p)}e.display.selForContextMenu=null}function hr(e,t,n,r,i){if(r||(r=n),ba(r,n)<0){var o=r;r=n,n=o}"string"==typeof t&&(t=_s(t)),sr(e,{from:n,to:r,text:t,origin:i})}function pr(e,t){var n=e.display,r=n.sizer.getBoundingClientRect(),i=null;if(t.top+r.top<0?i=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!la){var o=wo("div","​",null,"position: absolute; top: "+(t.top-n.viewOffset-kt(e.display))+"px; height: "+(t.bottom-t.top+hs)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(i),e.display.lineSpace.removeChild(o)}}function gr(e,t,n,r){null==r&&(r=0);for(var i=0;5>i;i++){var o=!1,a=Xt(e,t),s=n&&n!=t?Xt(e,n):a,l=vr(e,Math.min(a.left,s.left),Math.min(a.top,s.top)-r,Math.max(a.left,s.left),Math.max(a.bottom,s.bottom)+r),u=e.doc.scrollTop,c=e.doc.scrollLeft;if(null!=l.scrollTop&&(zn(e,l.scrollTop),Math.abs(e.doc.scrollTop-u)>1&&(o=!0)),null!=l.scrollLeft&&(Bn(e,l.scrollLeft),Math.abs(e.doc.scrollLeft-c)>1&&(o=!0)),!o)return a}}function mr(e,t,n,r,i){var o=vr(e,t,n,r,i);null!=o.scrollTop&&zn(e,o.scrollTop),null!=o.scrollLeft&&Bn(e,o.scrollLeft)}function vr(e,t,n,r,i){var o=e.display,a=Kt(e.display);0>n&&(n=0);var s=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=o.scroller.clientHeight-hs,u={};i-n>l&&(i=n+l);var c=e.doc.height+Lt(o),f=a>n,d=i>c-a;if(s>n)u.scrollTop=f?0:n;else if(i>s+l){var h=Math.min(n,(d?c:i)-l);h!=s&&(u.scrollTop=h)}var p=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,g=o.scroller.clientWidth-hs-o.gutters.offsetWidth,m=r-t>g;return m&&(r=t+g),10>t?u.scrollLeft=0:p>t?u.scrollLeft=Math.max(0,t-(m?0:10)):r>g+p-3&&(u.scrollLeft=r+(m?0:10)-g),u}function yr(e,t,n){(null!=t||null!=n)&&xr(e),null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t),null!=n&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+n)}function br(e){xr(e);var t=e.getCursor(),n=t,r=t;e.options.lineWrapping||(n=t.ch?ya(t.line,t.ch-1):t,r=ya(t.line,t.ch+1)),e.curOp.scrollToPos={from:n,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function xr(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var n=Gt(e,t.from),r=Gt(e,t.to),i=vr(e,Math.min(n.left,r.left),Math.min(n.top,r.top)-t.margin,Math.max(n.right,r.right),Math.max(n.bottom,r.bottom)+t.margin);e.scrollTo(i.scrollLeft,i.scrollTop)}}function wr(e,t,n,r){var i,o=e.doc;null==n&&(n="add"),"smart"==n&&(o.mode.indent?i=Dt(e,t):n="prev");var a=e.options.tabSize,s=_i(o,t),l=ys(s.text,null,a);s.stateAfter&&(s.stateAfter=null);var u,c=s.text.match(/^\s*/)[0];if(r||/\S/.test(s.text)){if("smart"==n&&(u=o.mode.indent(i,s.text.slice(c.length),s.text),u==ps||u>150)){if(!r)return;n="prev"}}else u=0,n="not";"prev"==n?u=t>o.first?ys(_i(o,t-1).text,null,a):0:"add"==n?u=l+e.options.indentUnit:"subtract"==n?u=l-e.options.indentUnit:"number"==typeof n&&(u=l+n),u=Math.max(0,u);var f="",d=0;if(e.options.indentWithTabs)for(var h=Math.floor(u/a);h;--h)d+=a,f+=" ";if(u>d&&(f+=co(u-d)),f!=c)hr(o,f,ya(t,0),ya(t,c.length),"+input");else for(var h=0;h<o.sel.ranges.length;h++){var p=o.sel.ranges[h];if(p.head.line==t&&p.head.ch<c.length){var d=ya(t,c.length);at(o,h,new J(d,d));break}}s.stateAfter=null}function Sr(e,t,n,r){var i=t,o=t;return"number"==typeof t?o=_i(e,Q(e,t)):i=Ii(t),null==i?null:(r(o,i)&&e.cm&&mn(e.cm,i,n),o)}function Cr(e,t){for(var n=e.doc.sel.ranges,r=[],i=0;i<n.length;i++){for(var o=t(n[i]);r.length&&ba(o.from,fo(r).to)<=0;){var a=r.pop();if(ba(a.from,o.from)<0){o.from=a.from;break}}r.push(o)}un(e,function(){for(var t=r.length-1;t>=0;t--)hr(e.doc,"",r[t].from,r[t].to,"+delete");br(e)})}function Tr(e,t,n,r,i){function o(){var t=s+n;return t<e.first||t>=e.first+e.size?f=!1:(s=t,c=_i(e,t))}function a(e){var t=(i?$o:Jo)(c,l,n,!0);if(null==t){if(e||!o())return f=!1;l=i?(0>n?zo:Wo)(c):0>n?c.text.length:0}else l=t;return!0}var s=t.line,l=t.ch,u=n,c=_i(e,s),f=!0;if("char"==r)a();else if("column"==r)a(!0);else if("word"==r||"group"==r)for(var d=null,h="group"==r,p=e.cm&&e.cm.getHelper(t,"wordChars"),g=!0;!(0>n)||a(!g);g=!1){var m=c.text.charAt(l)||"\n",v=yo(m,p)?"w":h&&"\n"==m?"n":!h||/\s/.test(m)?null:"p";if(!h||g||v||(v="s"),d&&d!=v){0>n&&(n=1,a());break}if(v&&(d=v),n>0&&!a(!g))break}var y=gt(e,ya(s,l),u,!0);return f||(y.hitSide=!0),y}function Dr(e,t,n,r){var i,o=e.doc,a=t.left;if("page"==r){var s=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);i=t.top+n*(s-(0>n?1.5:.5)*Kt(e.display))}else"line"==r&&(i=n>0?t.bottom+3:t.top-3);for(;;){var l=Jt(e,a,i);if(!l.outside)break;if(0>n?0>=i:i>=o.height){l.hitSide=!0;break}i+=5*n}return l}function kr(t,n,r,i){e.defaults[t]=n,r&&(Ia[t]=i?function(e,t,n){n!=Ha&&r(e,t,n)}:r)}function Lr(e){return"string"==typeof e?Ua[e]:e}function Ar(e,t,n,r,i){if(r&&r.shared)return Nr(e,t,n,r,i);if(e.cm&&!e.cm.curOp)return cn(e.cm,Ar)(e,t,n,r,i);var o=new Ja(e,i),a=ba(t,n);if(r&&mo(r,o,!1),a>0||0==a&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=wo("span",[o.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||(o.widgetNode.ignoreEvents=!0),r.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(Kr(e,t.line,t,n,o)||t.line!=n.line&&Kr(e,n.line,t,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");va=!0}o.addToHistory&&Bi(e,{from:t,to:n,origin:"markText"},e.sel,0/0);var s,l=t.line,u=e.cm;if(e.iter(l,n.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&Qr(e)==u.display.maxLine&&(s=!0),o.collapsed&&l!=t.line&&ji(e,0),Or(e,new jr(o,l==t.line?t.ch:null,l==n.line?n.ch:null)),++l}),o.collapsed&&e.iter(t.line,n.line+1,function(t){ni(e,t)&&ji(t,0)}),o.clearOnEnter&&us(o,"beforeCursorEnter",function(){o.clear()}),o.readOnly&&(ma=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),o.collapsed&&(o.id=++Ya,o.atomic=!0),u){if(s&&(u.curOp.updateMaxLine=!0),o.collapsed)gn(u,t.line,n.line+1);else if(o.className||o.title||o.startStyle||o.endStyle)for(var c=t.line;c<=n.line;c++)mn(u,c,"text");o.atomic&&ht(u.doc),no(u,"markerAdded",u,o)}return o}function Nr(e,t,n,r,i){r=mo(r),r.shared=!1;var o=[Ar(e,t,n,r,i)],a=o[0],s=r.widgetNode;return Ai(e,function(e){s&&(r.widgetNode=s.cloneNode(!0)),o.push(Ar(e,Z(e,t),Z(e,n),r,i));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;a=fo(o)}),new Ka(o,a)}function _r(e){return e.findMarks(ya(e.first,0),e.clipPos(ya(e.lastLine())),function(e){return e.parent})}function Mr(e,t){for(var n=0;n<t.length;n++){var r=t[n],i=r.find(),o=e.clipPos(i.from),a=e.clipPos(i.to);if(ba(o,a)){var s=Ar(e,o,a,r.primary,r.primary.type);r.markers.push(s),s.parent=r}}}function Er(e){for(var t=0;t<e.length;t++){var n=e[t],r=[n.primary.doc];Ai(n.primary.doc,function(e){r.push(e)});for(var i=0;i<n.markers.length;i++){var o=n.markers[i];-1==ho(r,o.doc)&&(o.parent=null,n.markers.splice(i--,1))}}}function jr(e,t,n){this.marker=e,this.from=t,this.to=n}function Ir(e,t){if(e)for(var n=0;n<e.length;++n){var r=e[n];if(r.marker==t)return r}}function Hr(e,t){for(var n,r=0;r<e.length;++r)e[r]!=t&&(n||(n=[])).push(e[r]);return n}function Or(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],t.marker.attachLine(e)}function Rr(e,t,n){if(e)for(var r,i=0;i<e.length;++i){var o=e[i],a=o.marker,s=null==o.from||(a.inclusiveLeft?o.from<=t:o.from<t);if(s||o.from==t&&"bookmark"==a.type&&(!n||!o.marker.insertLeft)){var l=null==o.to||(a.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new jr(a,o.from,l?null:o.to))}}return r}function Pr(e,t,n){if(e)for(var r,i=0;i<e.length;++i){var o=e[i],a=o.marker,s=null==o.to||(a.inclusiveRight?o.to>=t:o.to>t);if(s||o.from==t&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var l=null==o.from||(a.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new jr(a,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function Fr(e,t){var n=tt(e,t.from.line)&&_i(e,t.from.line).markedSpans,r=tt(e,t.to.line)&&_i(e,t.to.line).markedSpans;if(!n&&!r)return null;var i=t.from.ch,o=t.to.ch,a=0==ba(t.from,t.to),s=Rr(n,i,a),l=Pr(r,o,a),u=1==t.text.length,c=fo(t.text).length+(u?i:0);if(s)for(var f=0;f<s.length;++f){var d=s[f];if(null==d.to){var h=Ir(l,d.marker);h?u&&(d.to=null==h.to?null:h.to+c):d.to=i}}if(l)for(var f=0;f<l.length;++f){var d=l[f];if(null!=d.to&&(d.to+=c),null==d.from){var h=Ir(s,d.marker);h||(d.from=c,u&&(s||(s=[])).push(d))}else d.from+=c,u&&(s||(s=[])).push(d)}s&&(s=Wr(s)),l&&l!=s&&(l=Wr(l));var p=[s];if(!u){var g,m=t.text.length-2;if(m>0&&s)for(var f=0;f<s.length;++f)null==s[f].to&&(g||(g=[])).push(new jr(s[f].marker,null,null));for(var f=0;m>f;++f)p.push(g);p.push(l)}return p}function Wr(e){for(var t=0;t<e.length;++t){var n=e[t];null!=n.from&&n.from==n.to&&n.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function zr(e,t){var n=$i(e,t),r=Fr(e,t);if(!n)return r;if(!r)return n;for(var i=0;i<n.length;++i){var o=n[i],a=r[i];if(o&&a)e:for(var s=0;s<a.length;++s){for(var l=a[s],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else a&&(n[i]=a)}return n}function Br(e,t,n){var r=null;if(e.iter(t.line,n.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var n=e.markedSpans[t].marker;!n.readOnly||r&&-1!=ho(r,n)||(r||(r=[])).push(n)}}),!r)return null;for(var i=[{from:t,to:n}],o=0;o<r.length;++o)for(var a=r[o],s=a.find(0),l=0;l<i.length;++l){var u=i[l]; if(!(ba(u.to,s.from)<0||ba(u.from,s.to)>0)){var c=[l,1],f=ba(u.from,s.from),d=ba(u.to,s.to);(0>f||!a.inclusiveLeft&&!f)&&c.push({from:u.from,to:s.from}),(d>0||!a.inclusiveRight&&!d)&&c.push({from:s.to,to:u.to}),i.splice.apply(i,c),l+=c.length-1}}return i}function qr(e){var t=e.markedSpans;if(t){for(var n=0;n<t.length;++n)t[n].marker.detachLine(e);e.markedSpans=null}}function Ur(e,t){if(t){for(var n=0;n<t.length;++n)t[n].marker.attachLine(e);e.markedSpans=t}}function Vr(e){return e.inclusiveLeft?-1:0}function Xr(e){return e.inclusiveRight?1:0}function Gr(e,t){var n=e.lines.length-t.lines.length;if(0!=n)return n;var r=e.find(),i=t.find(),o=ba(r.from,i.from)||Vr(e)-Vr(t);if(o)return-o;var a=ba(r.to,i.to)||Xr(e)-Xr(t);return a?a:t.id-e.id}function $r(e,t){var n,r=va&&e.markedSpans;if(r)for(var i,o=0;o<r.length;++o)i=r[o],i.marker.collapsed&&null==(t?i.from:i.to)&&(!n||Gr(n,i.marker)<0)&&(n=i.marker);return n}function Jr(e){return $r(e,!0)}function Yr(e){return $r(e,!1)}function Kr(e,t,n,r,i){var o=_i(e,t),a=va&&o.markedSpans;if(a)for(var s=0;s<a.length;++s){var l=a[s];if(l.marker.collapsed){var u=l.marker.find(0),c=ba(u.from,n)||Vr(l.marker)-Vr(i),f=ba(u.to,r)||Xr(l.marker)-Xr(i);if(!(c>=0&&0>=f||0>=c&&f>=0)&&(0>=c&&(ba(u.to,n)>0||l.marker.inclusiveRight&&i.inclusiveLeft)||c>=0&&(ba(u.from,r)<0||l.marker.inclusiveLeft&&i.inclusiveRight)))return!0}}}function Qr(e){for(var t;t=Jr(e);)e=t.find(-1,!0).line;return e}function Zr(e){for(var t,n;t=Yr(e);)e=t.find(1,!0).line,(n||(n=[])).push(e);return n}function ei(e,t){var n=_i(e,t),r=Qr(n);return n==r?t:Ii(r)}function ti(e,t){if(t>e.lastLine())return t;var n,r=_i(e,t);if(!ni(e,r))return t;for(;n=Yr(r);)r=n.find(1,!0).line;return Ii(r)+1}function ni(e,t){var n=va&&t.markedSpans;if(n)for(var r,i=0;i<n.length;++i)if(r=n[i],r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&ri(e,t,r))return!0}}function ri(e,t,n){if(null==n.to){var r=n.marker.find(1,!0);return ri(e,r.line,Ir(r.line.markedSpans,n.marker))}if(n.marker.inclusiveRight&&n.to==t.text.length)return!0;for(var i,o=0;o<t.markedSpans.length;++o)if(i=t.markedSpans[o],i.marker.collapsed&&!i.marker.widgetNode&&i.from==n.to&&(null==i.to||i.to!=n.from)&&(i.marker.inclusiveLeft||n.marker.inclusiveRight)&&ri(e,t,i))return!0}function ii(e,t,n){Oi(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&yr(e,null,n)}function oi(e){if(null!=e.height)return e.height;if(!To(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.getGutterElement().offsetWidth+"px;"),Co(e.cm.display.measure,wo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function ai(e,t,n,r){var i=new Qa(e,n,r);return i.noHScroll&&(e.display.alignWidgets=!0),Sr(e.doc,t,"widget",function(t){var n=t.widgets||(t.widgets=[]);if(null==i.insertAt?n.push(i):n.splice(Math.min(n.length-1,Math.max(0,i.insertAt)),0,i),i.line=t,!ni(e.doc,t)){var r=Oi(t)<e.doc.scrollTop;ji(t,t.height+oi(i)),r&&yr(e,null,i.height),e.curOp.forceUpdate=!0}return!0}),i}function si(e,t,n,r){e.text=t,e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null),null!=e.order&&(e.order=null),qr(e),Ur(e,n);var i=r?r(e):1;i!=e.height&&ji(e,i)}function li(e){e.parent=null,qr(e)}function ui(e,t){if(e)for(;;){var n=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!n)break;e=e.slice(0,n.index)+e.slice(n.index+n[0].length);var r=n[1]?"bgClass":"textClass";null==t[r]?t[r]=n[2]:new RegExp("(?:^|s)"+n[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+n[2])}return e}function ci(t,n){if(t.blankLine)return t.blankLine(n);if(t.innerMode){var r=e.innerMode(t,n);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function fi(e,t,n){for(var r=0;10>r;r++){var i=e.token(t,n);if(t.pos>t.start)return i}throw new Error("Mode "+e.name+" failed to advance stream.")}function di(t,n,r,i,o,a,s){var l=r.flattenSpans;null==l&&(l=t.options.flattenSpans);var u,c=0,f=null,d=new $a(n,t.options.tabSize);for(""==n&&ui(ci(r,i),a);!d.eol();){if(d.pos>t.options.maxHighlightLength?(l=!1,s&&gi(t,n,i,d.pos),d.pos=n.length,u=null):u=ui(fi(r,d,i),a),t.options.addModeClass){var h=e.innerMode(r,i).mode.name;h&&(u="m-"+(u?h+" "+u:h))}l&&f==u||(c<d.start&&o(d.start,f),c=d.start,f=u),d.start=d.pos}for(;c<d.pos;){var p=Math.min(d.pos,c+5e4);o(p,f),c=p}}function hi(e,t,n,r){var i=[e.state.modeGen],o={};di(e,t.text,e.doc.mode,n,function(e,t){i.push(e,t)},o,r);for(var a=0;a<e.state.overlays.length;++a){var s=e.state.overlays[a],l=1,u=0;di(e,t.text,s.mode,!0,function(e,t){for(var n=l;e>u;){var r=i[l];r>e&&i.splice(l,1,e,i[l+1],r),l+=2,u=Math.min(e,r)}if(t)if(s.opaque)i.splice(n,l-n,e,"cm-overlay "+t),l=n+2;else for(;l>n;n+=2){var o=i[n+1];i[n+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:i,classes:o.bgClass||o.textClass?o:null}}function pi(e,t){if(!t.styles||t.styles[0]!=e.state.modeGen){var n=hi(e,t,t.stateAfter=Dt(e,Ii(t)));t.styles=n.styles,n.classes?t.styleClasses=n.classes:t.styleClasses&&(t.styleClasses=null)}return t.styles}function gi(e,t,n,r){var i=e.doc.mode,o=new $a(t,e.options.tabSize);for(o.start=o.pos=r||0,""==t&&ci(i,n);!o.eol()&&o.pos<=e.options.maxHighlightLength;)fi(i,o,n),o.start=o.pos}function mi(e,t){if(!e||/^\s*$/.test(e))return null;var n=t.addModeClass?ts:es;return n[e]||(n[e]=e.replace(/\S+/g,"cm-$&"))}function vi(e,t){var n=wo("span",null,null,ta?"padding-right: .1px":null),r={pre:wo("pre",[n]),content:n,col:0,pos:0,cm:e};t.measure={};for(var i=0;i<=(t.rest?t.rest.length:0);i++){var o,a=i?t.rest[i-1]:t.line;r.pos=0,r.addToken=bi,(Zo||ta)&&e.getOption("lineWrapping")&&(r.addToken=xi(r.addToken)),Ho(e.display.measure)&&(o=Ri(a))&&(r.addToken=wi(r.addToken,o)),r.map=[],Ci(a,r,pi(e,a)),a.styleClasses&&(a.styleClasses.bgClass&&(r.bgClass=No(a.styleClasses.bgClass,r.bgClass||"")),a.styleClasses.textClass&&(r.textClass=No(a.styleClasses.textClass,r.textClass||""))),0==r.map.length&&r.map.push(0,0,r.content.appendChild(Io(e.display.measure))),0==i?(t.measure.map=r.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(r.map),(t.measure.caches||(t.measure.caches=[])).push({}))}return fs(e,"renderLine",e,t.line,r.pre),r.pre.className&&(r.textClass=No(r.pre.className,r.textClass||"")),r}function yi(e){var t=wo("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t}function bi(e,t,n,r,i,o){if(t){var a=e.cm.options.specialChars,s=!1;if(a.test(t))for(var l=document.createDocumentFragment(),u=0;;){a.lastIndex=u;var c=a.exec(t),f=c?c.index-u:t.length-u;if(f){var d=document.createTextNode(t.slice(u,u+f));l.appendChild(Zo&&9>ea?wo("span",[d]):d),e.map.push(e.pos,e.pos+f,d),e.col+=f,e.pos+=f}if(!c)break;if(u+=f+1," "==c[0]){var h=e.cm.options.tabSize,p=h-e.col%h,d=l.appendChild(wo("span",co(p),"cm-tab"));e.col+=p}else{var d=e.cm.options.specialCharPlaceholder(c[0]);l.appendChild(Zo&&9>ea?wo("span",[d]):d),e.col+=1}e.map.push(e.pos,e.pos+1,d),e.pos++}else{e.col+=t.length;var l=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,l),Zo&&9>ea&&(s=!0),e.pos+=t.length}if(n||r||i||s){var g=n||"";r&&(g+=r),i&&(g+=i);var m=wo("span",[l],g);return o&&(m.title=o),e.content.appendChild(m)}e.content.appendChild(l)}}function xi(e){function t(e){for(var t=" ",n=0;n<e.length-2;++n)t+=n%2?" ":" ";return t+=" "}return function(n,r,i,o,a,s){e(n,r.replace(/ {3,}/g,t),i,o,a,s)}}function wi(e,t){return function(n,r,i,o,a,s){i=i?i+" cm-force-border":"cm-force-border";for(var l=n.pos,u=l+r.length;;){for(var c=0;c<t.length;c++){var f=t[c];if(f.to>l&&f.from<=l)break}if(f.to>=u)return e(n,r,i,o,a,s);e(n,r.slice(0,f.to-l),i,o,null,s),o=null,r=r.slice(f.to-l),l=f.to}}}function Si(e,t,n,r){var i=!r&&n.widgetNode;i&&(e.map.push(e.pos,e.pos+t,i),e.content.appendChild(i)),e.pos+=t}function Ci(e,t,n){var r=e.markedSpans,i=e.text,o=0;if(r)for(var a,s,l,u,c,f,d=i.length,h=0,p=1,g="",m=0;;){if(m==h){s=l=u=c="",f=null,m=1/0;for(var v=[],y=0;y<r.length;++y){var b=r[y],x=b.marker;b.from<=h&&(null==b.to||b.to>h)?(null!=b.to&&m>b.to&&(m=b.to,l=""),x.className&&(s+=" "+x.className),x.startStyle&&b.from==h&&(u+=" "+x.startStyle),x.endStyle&&b.to==m&&(l+=" "+x.endStyle),x.title&&!c&&(c=x.title),x.collapsed&&(!f||Gr(f.marker,x)<0)&&(f=b)):b.from>h&&m>b.from&&(m=b.from),"bookmark"==x.type&&b.from==h&&x.widgetNode&&v.push(x)}if(f&&(f.from||0)==h&&(Si(t,(null==f.to?d+1:f.to)-h,f.marker,null==f.from),null==f.to))return;if(!f&&v.length)for(var y=0;y<v.length;++y)Si(t,0,v[y])}if(h>=d)break;for(var w=Math.min(d,m);;){if(g){var S=h+g.length;if(!f){var C=S>w?g.slice(0,w-h):g;t.addToken(t,C,a?a+s:s,u,h+C.length==m?l:"",c)}if(S>=w){g=g.slice(w-h),h=w;break}h=S,u=""}g=i.slice(o,o=n[p++]),a=mi(n[p++],t.cm.options)}}else for(var p=1;p<n.length;p+=2)t.addToken(t,i.slice(o,o=n[p]),mi(n[p+1],t.cm.options))}function Ti(e,t){return 0==t.from.ch&&0==t.to.ch&&""==fo(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function Di(e,t,n,r){function i(e){return n?n[e]:null}function o(e,n,i){si(e,n,i,r),no(e,"change",e,t)}var a=t.from,s=t.to,l=t.text,u=_i(e,a.line),c=_i(e,s.line),f=fo(l),d=i(l.length-1),h=s.line-a.line;if(Ti(e,t)){for(var p=0,g=[];p<l.length-1;++p)g.push(new Za(l[p],i(p),r));o(c,c.text,d),h&&e.remove(a.line,h),g.length&&e.insert(a.line,g)}else if(u==c)if(1==l.length)o(u,u.text.slice(0,a.ch)+f+u.text.slice(s.ch),d);else{for(var g=[],p=1;p<l.length-1;++p)g.push(new Za(l[p],i(p),r));g.push(new Za(f+u.text.slice(s.ch),d,r)),o(u,u.text.slice(0,a.ch)+l[0],i(0)),e.insert(a.line+1,g)}else if(1==l.length)o(u,u.text.slice(0,a.ch)+l[0]+c.text.slice(s.ch),i(0)),e.remove(a.line+1,h);else{o(u,u.text.slice(0,a.ch)+l[0],i(0)),o(c,f+c.text.slice(s.ch),d);for(var p=1,g=[];p<l.length-1;++p)g.push(new Za(l[p],i(p),r));h>1&&e.remove(a.line+1,h-1),e.insert(a.line+1,g)}no(e,"change",e,t)}function ki(e){this.lines=e,this.parent=null;for(var t=0,n=0;t<e.length;++t)e[t].parent=this,n+=e[t].height;this.height=n}function Li(e){this.children=e;for(var t=0,n=0,r=0;r<e.length;++r){var i=e[r];t+=i.chunkSize(),n+=i.height,i.parent=this}this.size=t,this.height=n,this.parent=null}function Ai(e,t,n){function r(e,i,o){if(e.linked)for(var a=0;a<e.linked.length;++a){var s=e.linked[a];if(s.doc!=i){var l=o&&s.sharedHist;(!n||l)&&(t(s.doc,l),r(s.doc,e,l))}}}r(e,null,!0)}function Ni(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t,t.cm=e,a(e),n(e),e.options.lineWrapping||h(e),e.options.mode=t.modeOption,gn(e)}function _i(e,t){if(t-=e.first,0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(o>t){n=i;break}t-=o}return n.lines[t]}function Mi(e,t,n){var r=[],i=t.line;return e.iter(t.line,n.line+1,function(e){var o=e.text;i==n.line&&(o=o.slice(0,n.ch)),i==t.line&&(o=o.slice(t.ch)),r.push(o),++i}),r}function Ei(e,t,n){var r=[];return e.iter(t,n,function(e){r.push(e.text)}),r}function ji(e,t){var n=t-e.height;if(n)for(var r=e;r;r=r.parent)r.height+=n}function Ii(e){if(null==e.parent)return null;for(var t=e.parent,n=ho(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var i=0;r.children[i]!=t;++i)n+=r.children[i].chunkSize();return n+t.first}function Hi(e,t){var n=e.first;e:do{for(var r=0;r<e.children.length;++r){var i=e.children[r],o=i.height;if(o>t){e=i;continue e}t-=o,n+=i.chunkSize()}return n}while(!e.lines);for(var r=0;r<e.lines.length;++r){var a=e.lines[r],s=a.height;if(s>t)break;t-=s}return n+r}function Oi(e){e=Qr(e);for(var t=0,n=e.parent,r=0;r<n.lines.length;++r){var i=n.lines[r];if(i==e)break;t+=i.height}for(var o=n.parent;o;n=o,o=n.parent)for(var r=0;r<o.children.length;++r){var a=o.children[r];if(a==n)break;t+=a.height}return t}function Ri(e){var t=e.order;return null==t&&(t=e.order=Os(e.text)),t}function Pi(e){this.done=[],this.undone=[],this.undoDepth=1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=this.lastSelOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=e||1}function Fi(e,t){var n={from:V(t.from),to:Ea(t),text:Mi(e,t.from,t.to)};return Xi(e,n,t.from.line,t.to.line+1),Ai(e,function(e){Xi(e,n,t.from.line,t.to.line+1)},!0),n}function Wi(e){for(;e.length;){var t=fo(e);if(!t.ranges)break;e.pop()}}function zi(e,t){return t?(Wi(e.done),fo(e.done)):e.done.length&&!fo(e.done).ranges?fo(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),fo(e.done)):void 0}function Bi(e,t,n,r){var i=e.history;i.undone.length=0;var o,a=+new Date;if((i.lastOp==r||i.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&i.lastModTime>a-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=zi(i,i.lastOp==r))){var s=fo(o.changes);0==ba(t.from,t.to)&&0==ba(t.from,s.to)?s.to=Ea(t):o.changes.push(Fi(e,t))}else{var l=fo(i.done);for(l&&l.ranges||Vi(e.sel,i.done),o={changes:[Fi(e,t)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=a,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=t.origin,s||fs(e,"historyAdded")}function qi(e,t,n,r){var i=t.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Ui(e,t,n,r){var i=e.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||qi(e,o,fo(i.done),t))?i.done[i.done.length-1]=t:Vi(t,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=n,r&&r.clearRedo!==!1&&Wi(i.undone)}function Vi(e,t){var n=fo(t);n&&n.ranges&&n.equals(e)||t.push(e)}function Xi(e,t,n,r){var i=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,r),function(n){n.markedSpans&&((i||(i=t["spans_"+e.id]={}))[o]=n.markedSpans),++o})}function Gi(e){if(!e)return null;for(var t,n=0;n<e.length;++n)e[n].marker.explicitlyCleared?t||(t=e.slice(0,n)):t&&t.push(e[n]);return t?t.length?t:null:e}function $i(e,t){var n=t["spans_"+e.id];if(!n)return null;for(var r=0,i=[];r<t.text.length;++r)i.push(Gi(n[r]));return i}function Ji(e,t,n){for(var r=0,i=[];r<e.length;++r){var o=e[r];if(o.ranges)i.push(n?$.prototype.deepCopy.call(o):o);else{var a=o.changes,s=[];i.push({changes:s});for(var l=0;l<a.length;++l){var u,c=a[l];if(s.push({from:c.from,to:c.to,text:c.text}),t)for(var f in c)(u=f.match(/^spans_(\d+)$/))&&ho(t,Number(u[1]))>-1&&(fo(s)[f]=c[f],delete c[f])}}}return i}function Yi(e,t,n,r){n<e.line?e.line+=r:t<e.line&&(e.line=t,e.ch=0)}function Ki(e,t,n,r){for(var i=0;i<e.length;++i){var o=e[i],a=!0;if(o.ranges){o.copied||(o=e[i]=o.deepCopy(),o.copied=!0);for(var s=0;s<o.ranges.length;s++)Yi(o.ranges[s].anchor,t,n,r),Yi(o.ranges[s].head,t,n,r)}else{for(var s=0;s<o.changes.length;++s){var l=o.changes[s];if(n<l.from.line)l.from=ya(l.from.line+r,l.from.ch),l.to=ya(l.to.line+r,l.to.ch);else if(t<=l.to.line){a=!1;break}}a||(e.splice(0,i+1),i=0)}}}function Qi(e,t){var n=t.from.line,r=t.to.line,i=t.text.length-(r-n)-1;Ki(e.done,n,r,i),Ki(e.undone,n,r,i)}function Zi(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function eo(e){return e.target||e.srcElement}function to(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),fa&&e.ctrlKey&&1==t&&(t=3),t}function no(e,t){function n(e){return function(){e.apply(null,o)}}var r=e._handlers&&e._handlers[t];if(r){var i,o=Array.prototype.slice.call(arguments,2);Ta?i=Ta.delayedCallbacks:ds?i=ds:(i=ds=[],setTimeout(ro,0));for(var a=0;a<r.length;++a)i.push(n(r[a]))}}function ro(){var e=ds;ds=null;for(var t=0;t<e.length;++t)e[t]()}function io(e,t,n){return fs(e,n||t.type,e,t),Zi(t)||t.codemirrorIgnore}function oo(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var n=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==ho(n,t[r])&&n.push(t[r])}function ao(e,t){var n=e._handlers&&e._handlers[t];return n&&n.length>0}function so(e){e.prototype.on=function(e,t){us(this,e,t)},e.prototype.off=function(e,t){cs(this,e,t)}}function lo(){this.id=null}function uo(e,t,n){for(var r=0,i=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var a=o-r;if(o==e.length||i+a>=t)return r+Math.min(a,t-i);if(i+=o-r,i+=n-i%n,r=o+1,i>=t)return r}}function co(e){for(;bs.length<=e;)bs.push(fo(bs)+" ");return bs[e]}function fo(e){return e[e.length-1]}function ho(e,t){for(var n=0;n<e.length;++n)if(e[n]==t)return n;return-1}function po(e,t){for(var n=[],r=0;r<e.length;r++)n[r]=t(e[r],r);return n}function go(e,t){var n;if(Object.create)n=Object.create(e);else{var r=function(){};r.prototype=e,n=new r}return t&&mo(t,n),n}function mo(e,t,n){t||(t={});for(var r in e)!e.hasOwnProperty(r)||n===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function vo(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function yo(e,t){return t?t.source.indexOf("\\w")>-1&&Cs(e)?!0:t.test(e):Cs(e)}function bo(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function xo(e){return e.charCodeAt(0)>=768&&Ts.test(e)}function wo(e,t,n,r){var i=document.createElement(e);if(n&&(i.className=n),r&&(i.style.cssText=r),"string"==typeof t)i.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)i.appendChild(t[o]);return i}function So(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Co(e,t){return So(e).appendChild(t)}function To(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function Do(){return document.activeElement}function ko(e){return new RegExp("\\b"+e+"\\b\\s*")}function Lo(e,t){var n=ko(t);n.test(e.className)&&(e.className=e.className.replace(n,""))}function Ao(e,t){ko(t).test(e.className)||(e.className+=" "+t)}function No(e,t){for(var n=e.split(" "),r=0;r<n.length;r++)n[r]&&!ko(n[r]).test(t)&&(t+=" "+n[r]);return t}function _o(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),n=0;n<t.length;n++){var r=t[n].CodeMirror;r&&e(r)}}function Mo(){As||(Eo(),As=!0)}function Eo(){var e;us(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null,Ds=null,_o(_n)},100))}),us(window,"blur",function(){_o(Zn)})}function jo(e){if(null!=Ds)return Ds;var t=wo("div",null,null,"width: 50px; height: 50px; overflow-x: scroll");return Co(e,t),t.offsetWidth&&(Ds=t.offsetHeight-t.clientHeight),Ds||0}function Io(e){if(null==ks){var t=wo("span","​");Co(e,wo("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(ks=t.offsetWidth<=1&&t.offsetHeight>2&&!(Zo&&8>ea))}return ks?wo("span","​"):wo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Ho(e){if(null!=Ls)return Ls;var t=Co(e,document.createTextNode("AخA")),n=ws(t,0,1).getBoundingClientRect();if(!n||n.left==n.right)return!1;var r=ws(t,1,2).getBoundingClientRect();return Ls=r.right-n.right<3}function Oo(e){if(null!=js)return js;var t=Co(e,wo("span","x")),n=t.getBoundingClientRect(),r=ws(t,0,1).getBoundingClientRect();return js=Math.abs(n.left-r.left)>1}function Ro(e,t,n,r){if(!e)return r(t,n,"ltr");for(var i=!1,o=0;o<e.length;++o){var a=e[o];(a.from<n&&a.to>t||t==n&&a.to==t)&&(r(Math.max(a.from,t),Math.min(a.to,n),1==a.level?"rtl":"ltr"),i=!0)}i||r(t,n,"ltr")}function Po(e){return e.level%2?e.to:e.from}function Fo(e){return e.level%2?e.from:e.to}function Wo(e){var t=Ri(e);return t?Po(t[0]):0}function zo(e){var t=Ri(e);return t?Fo(fo(t)):e.text.length}function Bo(e,t){var n=_i(e.doc,t),r=Qr(n);r!=n&&(t=Ii(r));var i=Ri(r),o=i?i[0].level%2?zo(r):Wo(r):0;return ya(t,o)}function qo(e,t){for(var n,r=_i(e.doc,t);n=Yr(r);)r=n.find(1,!0).line,t=null;var i=Ri(r),o=i?i[0].level%2?Wo(r):zo(r):r.text.length;return ya(null==t?Ii(r):t,o)}function Uo(e,t){var n=Bo(e,t.line),r=_i(e.doc,n.line),i=Ri(r);if(!i||0==i[0].level){var o=Math.max(0,r.text.search(/\S/)),a=t.line==n.line&&t.ch<=o&&t.ch;return ya(n.line,a?0:o)}return n}function Vo(e,t,n){var r=e[0].level;return t==r?!0:n==r?!1:n>t}function Xo(e,t){Hs=null;for(var n,r=0;r<e.length;++r){var i=e[r];if(i.from<t&&i.to>t)return r;if(i.from==t||i.to==t){if(null!=n)return Vo(e,i.level,e[n].level)?(i.from!=i.to&&(Hs=n),r):(i.from!=i.to&&(Hs=r),n);n=r}}return n}function Go(e,t,n,r){if(!r)return t+n;do t+=n;while(t>0&&xo(e.text.charAt(t)));return t}function $o(e,t,n,r){var i=Ri(e);if(!i)return Jo(e,t,n,r);for(var o=Xo(i,t),a=i[o],s=Go(e,t,a.level%2?-n:n,r);;){if(s>a.from&&s<a.to)return s;if(s==a.from||s==a.to)return Xo(i,s)==o?s:(a=i[o+=n],n>0==a.level%2?a.to:a.from);if(a=i[o+=n],!a)return null;s=n>0==a.level%2?Go(e,a.to,-1,r):Go(e,a.from,1,r)}}function Jo(e,t,n,r){var i=t+n;if(r)for(;i>0&&xo(e.text.charAt(i));)i+=n;return 0>i||i>e.text.length?null:i}var Yo=/gecko\/\d/i.test(navigator.userAgent),Ko=/MSIE \d/.test(navigator.userAgent),Qo=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Zo=Ko||Qo,ea=Zo&&(Ko?document.documentMode||6:Qo[1]),ta=/WebKit\//.test(navigator.userAgent),na=ta&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ra=/Chrome\//.test(navigator.userAgent),ia=/Opera\//.test(navigator.userAgent),oa=/Apple Computer/.test(navigator.vendor),aa=/KHTML\//.test(navigator.userAgent),sa=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),la=/PhantomJS/.test(navigator.userAgent),ua=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),ca=ua||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),fa=ua||/Mac/.test(navigator.platform),da=/win/i.test(navigator.platform),ha=ia&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);ha&&(ha=Number(ha[1])),ha&&ha>=15&&(ia=!1,ta=!0);var pa=fa&&(na||ia&&(null==ha||12.11>ha)),ga=Yo||Zo&&ea>=9,ma=!1,va=!1,ya=e.Pos=function(e,t){return this instanceof ya?(this.line=e,void(this.ch=t)):new ya(e,t)},ba=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};$.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var n=this.ranges[t],r=e.ranges[t];if(0!=ba(n.anchor,r.anchor)||0!=ba(n.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new J(V(this.ranges[t].anchor),V(this.ranges[t].head));return new $(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var n=0;n<this.ranges.length;n++){var r=this.ranges[n];if(ba(t,r.from())>=0&&ba(e,r.to())<=0)return n}return-1}},J.prototype={from:function(){return G(this.anchor,this.head)},to:function(){return X(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var xa,wa,Sa,Ca={left:0,right:0,top:0,bottom:0},Ta=null,Da=0,ka=null,La=0,Aa=0,Na=null;Zo?Na=-.53:Yo?Na=15:ra?Na=-.7:oa&&(Na=-1/3);var _a,Ma=null,Ea=e.changeEnd=function(e){return e.text?ya(e.from.line+e.text.length-1,fo(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus(),kn(this),Cn(this)},setOption:function(e,t){var n=this.options,r=n[e];(n[e]!=t||"mode"==e)&&(n[e]=t,Ia.hasOwnProperty(e)&&cn(this,Ia[e])(this,t,r))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](e)},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;n<t.length;++n)if(t[n]==e||"string"!=typeof t[n]&&t[n].name==e)return t.splice(n,1),!0},addOverlay:fn(function(t,n){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:n&&n.opaque}),this.state.modeGen++,gn(this)}),removeOverlay:fn(function(e){for(var t=this.state.overlays,n=0;n<t.length;++n){var r=t[n].modeSpec;if(r==e||"string"==typeof e&&r.name==e)return t.splice(n,1),this.state.modeGen++,void gn(this)}}),indentLine:fn(function(e,t,n){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract"),tt(this.doc,e)&&wr(this,e,t,n)}),indentSelection:fn(function(e){for(var t=this.doc.sel.ranges,n=-1,r=0;r<t.length;r++){var i=t[r];if(i.empty())i.head.line>n&&(wr(this,i.head.line,e,!0),n=i.head.line,r==this.doc.sel.primIndex&&br(this));else{var o=i.from(),a=i.to(),s=Math.max(n,o.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var l=s;n>l;++l)wr(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[r].from().ch>0&&at(this.doc,r,new J(o,u[r].to()),gs)}}}),getTokenAt:function(e,t){var n=this.doc;e=Z(n,e);for(var r=Dt(this,e.line,t),i=this.doc.mode,o=_i(n,e.line),a=new $a(o.text,this.options.tabSize);a.pos<e.ch&&!a.eol();){a.start=a.pos;var s=fi(i,a,r)}return{start:a.start,end:a.pos,string:a.current(),type:s||null,state:r}},getTokenTypeAt:function(e){e=Z(this.doc,e);var t,n=pi(this,_i(this.doc,e.line)),r=0,i=(n.length-1)/2,o=e.ch;if(0==o)t=n[2];else for(;;){var a=r+i>>1;if((a?n[2*a-1]:0)>=o)i=a;else{if(!(n[2*a+1]<o)){t=n[2*a+2];break}r=a+1}}var s=t?t.indexOf("cm-overlay "):-1;return 0>s?t:0==s?null:t.slice(0,s-1)},getModeAt:function(t){var n=this.doc.mode;return n.innerMode?e.innerMode(n,this.getTokenAt(t).state).mode:n},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var n=[];if(!Wa.hasOwnProperty(t))return Wa;var r=Wa[t],i=this.getModeAt(e);if("string"==typeof i[t])r[i[t]]&&n.push(r[i[t]]);else if(i[t])for(var o=0;o<i[t].length;o++){var a=r[i[t][o]];a&&n.push(a)}else i.helperType&&r[i.helperType]?n.push(r[i.helperType]):r[i.name]&&n.push(r[i.name]);for(var o=0;o<r._global.length;o++){var s=r._global[o];s.pred(i,this)&&-1==ho(n,s.val)&&n.push(s.val)}return n},getStateAfter:function(e,t){var n=this.doc;return e=Q(n,null==e?n.first+n.size-1:e),Dt(this,e+1,t)},cursorCoords:function(e,t){var n,r=this.doc.sel.primary();return n=null==e?r.head:"object"==typeof e?Z(this.doc,e):e?r.from():r.to(),Xt(this,n,t||"page")},charCoords:function(e,t){return Vt(this,Z(this.doc,e),t||"page")},coordsChar:function(e,t){return e=Ut(this,e,t||"page"),Jt(this,e.left,e.top)},lineAtHeight:function(e,t){return e=Ut(this,{top:e,left:0},t||"page").top,Hi(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var n=!1,r=this.doc.first+this.doc.size-1;e<this.doc.first?e=this.doc.first:e>r&&(e=r,n=!0);var i=_i(this.doc,e);return qt(this,i,{top:0,left:0},t||"page").top+(n?this.doc.height-Oi(i):0)},defaultTextHeight:function(){return Kt(this.display)},defaultCharWidth:function(){return Qt(this.display)},setGutterMarker:fn(function(e,t,n){return Sr(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});return r[t]=n,!n&&bo(r)&&(e.gutterMarkers=null),!0})}),clearGutter:fn(function(e){var t=this,n=t.doc,r=n.first;n.iter(function(n){n.gutterMarkers&&n.gutterMarkers[e]&&(n.gutterMarkers[e]=null,mn(t,r,"gutter"),bo(n.gutterMarkers)&&(n.gutterMarkers=null)),++r})}),addLineWidget:fn(function(e,t,n){return ai(this,e,t,n)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!tt(this.doc,e))return null;var t=e;if(e=_i(this.doc,e),!e)return null}else{var t=Ii(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,r,i){var o=this.display;e=Xt(this,Z(this.doc,e));var a=e.bottom,s=e.left;if(t.style.position="absolute",o.sizer.appendChild(t),"over"==r)a=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?a=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(a=e.bottom),s+t.offsetWidth>u&&(s=u-t.offsetWidth)}t.style.top=a+"px",t.style.left=t.style.right="","right"==i?(s=o.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?s=0:"middle"==i&&(s=(o.sizer.clientWidth-t.offsetWidth)/2),t.style.left=s+"px"),n&&mr(this,s,a,s+t.offsetWidth,a+t.offsetHeight)},triggerOnKeyDown:fn($n),triggerOnKeyPress:fn(Kn),triggerOnKeyUp:Yn,execCommand:function(e){return qa.hasOwnProperty(e)?qa[e](this):void 0},findPosH:function(e,t,n,r){var i=1;0>t&&(i=-1,t=-t);for(var o=0,a=Z(this.doc,e);t>o&&(a=Tr(this.doc,a,i,n,r),!a.hitSide);++o);return a},moveH:fn(function(e,t){var n=this;n.extendSelectionsBy(function(r){return n.display.shift||n.doc.extend||r.empty()?Tr(n.doc,r.head,e,t,n.options.rtlMoveVisually):0>e?r.from():r.to()},vs)}),deleteH:fn(function(e,t){var n=this.doc.sel,r=this.doc;n.somethingSelected()?r.replaceSelection("",null,"+delete"):Cr(this,function(n){var i=Tr(r,n.head,e,t,!1);return 0>e?{from:i,to:n.head}:{from:n.head,to:i}})}),findPosV:function(e,t,n,r){var i=1,o=r;0>t&&(i=-1,t=-t);for(var a=0,s=Z(this.doc,e);t>a;++a){var l=Xt(this,s,"div");if(null==o?o=l.left:l.left=o,s=Dr(this,l,i,n),s.hitSide)break}return s},moveV:fn(function(e,t){var n=this,r=this.doc,i=[],o=!n.display.shift&&!r.extend&&r.sel.somethingSelected();if(r.extendSelectionsBy(function(a){if(o)return 0>e?a.from():a.to();var s=Xt(n,a.head,"div");null!=a.goalColumn&&(s.left=a.goalColumn),i.push(s.left);var l=Dr(n,s,e,t);return"page"==t&&a==r.sel.primary()&&yr(n,null,Vt(n,l,"div").top-s.top),l},vs),i.length)for(var a=0;a<r.sel.ranges.length;a++)r.sel.ranges[a].goalColumn=i[a]}),findWordAt:function(e){var t=this.doc,n=_i(t,e.line).text,r=e.ch,i=e.ch;if(n){var o=this.getHelper(e,"wordChars");(e.xRel<0||i==n.length)&&r?--r:++i;for(var a=n.charAt(r),s=yo(a,o)?function(e){return yo(e,o)}:/\s/.test(a)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!yo(e)};r>0&&s(n.charAt(r-1));)--r;for(;i<n.length&&s(n.charAt(i));)++i}return new J(ya(e.line,r),ya(e.line,i))},toggleOverwrite:function(e){(null==e||e!=this.state.overwrite)&&((this.state.overwrite=!this.state.overwrite)?Ao(this.display.cursorDiv,"CodeMirror-overwrite"):Lo(this.display.cursorDiv,"CodeMirror-overwrite"),fs(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return Do()==this.display.input},scrollTo:fn(function(e,t){(null!=e||null!=t)&&xr(this),null!=e&&(this.curOp.scrollLeft=e),null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller,t=hs;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-t,width:e.scrollWidth-t,clientHeight:e.clientHeight-t,clientWidth:e.clientWidth-t}},scrollIntoView:fn(function(e,t){if(null==e?(e={from:this.doc.sel.primary().head,to:null},null==t&&(t=this.options.cursorScrollMargin)):"number"==typeof e?e={from:ya(e,0),to:null}:null==e.from&&(e={from:e,to:null}),e.to||(e.to=e.from),e.margin=t||0,null!=e.from.line)xr(this),this.curOp.scrollToPos=e;else{var n=vr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(n.scrollLeft,n.scrollTop)}}),setSize:fn(function(e,t){function n(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(r.display.wrapper.style.width=n(e)),null!=t&&(r.display.wrapper.style.height=n(t)),r.options.lineWrapping&&Ft(this);var i=r.display.viewFrom;r.doc.iter(i,r.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){mn(r,i,"widget");break}++i}),r.curOp.forceUpdate=!0,fs(r,"refresh",this)}),operation:function(e){return un(this,e)},refresh:fn(function(){var e=this.display.cachedTextHeight;gn(this),this.curOp.forceUpdate=!0,Wt(this),this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop),f(this),(null==e||Math.abs(e-Kt(this.display))>.5)&&a(this),fs(this,"refresh",this)}),swapDoc:fn(function(e){var t=this.doc;return t.cm=null,Ni(this,e),Wt(this),Dn(this),this.scrollTo(e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,no(this,"swapDoc",this,t),t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper },getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},so(e);var ja=e.defaults={},Ia=e.optionHandlers={},Ha=e.Init={toString:function(){return"CodeMirror.Init"}};kr("value","",function(e,t){e.setValue(t)},!0),kr("mode",null,function(e,t){e.doc.modeOption=t,n(e)},!0),kr("indentUnit",2,n,!0),kr("indentWithTabs",!1),kr("smartIndent",!0),kr("tabSize",4,function(e){r(e),Wt(e),gn(e)},!0),kr("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g"),e.refresh()},!0),kr("specialCharPlaceholder",yi,function(e){e.refresh()},!0),kr("electricChars",!0),kr("rtlMoveVisually",!da),kr("wholeLineUpdateBefore",!0),kr("theme","default",function(e){l(e),u(e)},!0),kr("keyMap","default",s),kr("extraKeys",null),kr("lineWrapping",!1,i,!0),kr("gutters",[],function(e){p(e.options),u(e)},!0),kr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?S(e.display)+"px":"0",e.refresh()},!0),kr("coverGutterNextToScrollbar",!1,v,!0),kr("lineNumbers",!1,function(e){p(e.options),u(e)},!0),kr("firstLineNumber",1,u,!0),kr("lineNumberFormatter",function(e){return e},u,!0),kr("showCursorWhenSelecting",!1,yt,!0),kr("resetSelectionOnContextMenu",!0),kr("readOnly",!1,function(e,t){"nocursor"==t?(Zn(e),e.display.input.blur(),e.display.disabled=!0):(e.display.disabled=!1,t||Dn(e))}),kr("disableInput",!1,function(e,t){t||Dn(e)},!0),kr("dragDrop",!0),kr("cursorBlinkRate",530),kr("cursorScrollMargin",0),kr("cursorHeight",1,yt,!0),kr("singleCursorHeightPerLine",!0,yt,!0),kr("workTime",100),kr("workDelay",100),kr("flattenSpans",!0,r,!0),kr("addModeClass",!1,r,!0),kr("pollInterval",100),kr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t}),kr("historyEventDelay",1250),kr("viewportMargin",10,function(e){e.refresh()},!0),kr("maxHighlightLength",1e4,r,!0),kr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)}),kr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""}),kr("autofocus",null);var Oa=e.modes={},Ra=e.mimeModes={};e.defineMode=function(t,n){e.defaults.mode||"null"==t||(e.defaults.mode=t),arguments.length>2&&(n.dependencies=Array.prototype.slice.call(arguments,2)),Oa[t]=n},e.defineMIME=function(e,t){Ra[e]=t},e.resolveMode=function(t){if("string"==typeof t&&Ra.hasOwnProperty(t))t=Ra[t];else if(t&&"string"==typeof t.name&&Ra.hasOwnProperty(t.name)){var n=Ra[t.name];"string"==typeof n&&(n={name:n}),t=go(n,t),t.name=n.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}},e.getMode=function(t,n){var n=e.resolveMode(n),r=Oa[n.name];if(!r)return e.getMode(t,"text/plain");var i=r(t,n);if(Pa.hasOwnProperty(n.name)){var o=Pa[n.name];for(var a in o)o.hasOwnProperty(a)&&(i.hasOwnProperty(a)&&(i["_"+a]=i[a]),i[a]=o[a])}if(i.name=n.name,n.helperType&&(i.helperType=n.helperType),n.modeProps)for(var a in n.modeProps)i[a]=n.modeProps[a];return i},e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}}),e.defineMIME("text/plain","null");var Pa=e.modeExtensions={};e.extendMode=function(e,t){var n=Pa.hasOwnProperty(e)?Pa[e]:Pa[e]={};mo(t,n)},e.defineExtension=function(t,n){e.prototype[t]=n},e.defineDocExtension=function(e,t){rs.prototype[e]=t},e.defineOption=kr;var Fa=[];e.defineInitHook=function(e){Fa.push(e)};var Wa=e.helpers={};e.registerHelper=function(t,n,r){Wa.hasOwnProperty(t)||(Wa[t]=e[t]={_global:[]}),Wa[t][n]=r},e.registerGlobalHelper=function(t,n,r,i){e.registerHelper(t,n,i),Wa[t]._global.push({pred:r,val:i})};var za=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var n={};for(var r in t){var i=t[r];i instanceof Array&&(i=i.concat([])),n[r]=i}return n},Ba=e.startState=function(e,t,n){return e.startState?e.startState(t,n):!0};e.innerMode=function(e,t){for(;e.innerMode;){var n=e.innerMode(t);if(!n||n.mode==e)break;t=n.state,e=n.mode}return n||{mode:e,state:t}};var qa=e.commands={selectAll:function(e){e.setSelection(ya(e.firstLine(),0),ya(e.lastLine()),gs)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),gs)},killLine:function(e){Cr(e,function(t){if(t.empty()){var n=_i(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line<e.lastLine()?{from:t.head,to:ya(t.head.line+1,0)}:{from:t.head,to:ya(t.head.line,n)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){Cr(e,function(t){return{from:ya(t.from().line,0),to:Z(e.doc,ya(t.to().line+1,0))}})},delLineLeft:function(e){Cr(e,function(e){return{from:ya(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){Cr(e,function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:n},"div");return{from:r,to:t.from()}})},delWrappedLineRight:function(e){Cr(e,function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:n},"div");return{from:t.from(),to:r}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(ya(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(ya(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Bo(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Uo(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return qo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:n},"div")},vs)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:n},"div")},vs)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:n},"div");return r.ch<e.getLine(r.line).search(/\S/)?Uo(e,t.head):r},vs)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],n=e.listSelections(),r=e.options.tabSize,i=0;i<n.length;i++){var o=n[i].from(),a=ys(e.getLine(o.line),o.ch,r);t.push(new Array(r-a%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){un(e,function(){for(var t=e.listSelections(),n=[],r=0;r<t.length;r++){var i=t[r].head,o=_i(e.doc,i.line).text;if(o)if(i.ch==o.length&&(i=new ya(i.line,i.ch-1)),i.ch>0)i=new ya(i.line,i.ch+1),e.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),ya(i.line,i.ch-2),i,"+transpose");else if(i.line>e.doc.first){var a=_i(e.doc,i.line-1).text;a&&e.replaceRange(o.charAt(0)+"\n"+a.charAt(a.length-1),ya(i.line-1,a.length-1),ya(i.line,1),"+transpose")}n.push(new J(i,i))}e.setSelections(n)})},newlineAndIndent:function(e){un(e,function(){for(var t=e.listSelections().length,n=0;t>n;n++){var r=e.listSelections()[n];e.replaceRange("\n",r.anchor,r.head,"+input"),e.indentLine(r.from().line+1,null,!0),br(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},Ua=e.keyMap={};Ua.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Ua.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Ua.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Ua.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"},Ua["default"]=fa?Ua.macDefault:Ua.pcDefault;var Va=e.lookupKey=function(e,t,n){function r(t){t=Lr(t);var i=t[e];if(i===!1)return"stop";if(null!=i&&n(i))return!0;if(t.nofallthrough)return"stop";var o=t.fallthrough;if(null==o)return!1;if("[object Array]"!=Object.prototype.toString.call(o))return r(o);for(var a=0;a<o.length;++a){var s=r(o[a]);if(s)return s}return!1}for(var i=0;i<t.length;++i){var o=r(t[i]);if(o)return"stop"!=o}},Xa=e.isModifierKey=function(e){var t=Is[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Ga=e.keyName=function(e,t){if(ia&&34==e.keyCode&&e["char"])return!1;var n=Is[e.keyCode];return null==n||e.altGraphKey?!1:(e.altKey&&(n="Alt-"+n),(pa?e.metaKey:e.ctrlKey)&&(n="Ctrl-"+n),(pa?e.ctrlKey:e.metaKey)&&(n="Cmd-"+n),!t&&e.shiftKey&&(n="Shift-"+n),n)};e.fromTextArea=function(t,n){function r(){t.value=u.getValue()}if(n||(n={}),n.value=t.value,!n.tabindex&&t.tabindex&&(n.tabindex=t.tabindex),!n.placeholder&&t.placeholder&&(n.placeholder=t.placeholder),null==n.autofocus){var i=Do();n.autofocus=i==t||null!=t.getAttribute("autofocus")&&i==document.body}if(t.form&&(us(t.form,"submit",r),!n.leaveSubmitMethodAlone)){var o=t.form,a=o.submit;try{var s=o.submit=function(){r(),o.submit=a,o.submit(),o.submit=s}}catch(l){}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},n);return u.save=r,u.getTextArea=function(){return t},u.toTextArea=function(){u.toTextArea=isNaN,r(),t.parentNode.removeChild(u.getWrapperElement()),t.style.display="",t.form&&(cs(t.form,"submit",r),"function"==typeof t.form.submit&&(t.form.submit=a))},u};var $a=e.StringStream=function(e,t){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0};$a.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var n=t==e;else var n=t&&(e.test?e.test(t):e(t));return n?(++this.pos,t):void 0},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);return t>-1?(this.pos=t,!0):void 0},backUp:function(e){this.pos-=e},column:function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=ys(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?ys(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ys(this.string,null,this.tabSize)-(this.lineStart?ys(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,n){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);return r&&r.index>0?null:(r&&t!==!1&&(this.pos+=r[0].length),r)}var i=function(e){return n?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);return i(o)==i(e)?(t!==!1&&(this.pos+=e.length),!0):void 0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var Ja=e.TextMarker=function(e,t){this.lines=[],this.type=t,this.doc=e};so(Ja),Ja.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Zt(e),ao(this,"clear")){var n=this.find();n&&no(this,"clear",n.from,n.to)}for(var r=null,i=null,o=0;o<this.lines.length;++o){var a=this.lines[o],s=Ir(a.markedSpans,this);e&&!this.collapsed?mn(e,Ii(a),"text"):e&&(null!=s.to&&(i=Ii(a)),null!=s.from&&(r=Ii(a))),a.markedSpans=Hr(a.markedSpans,s),null==s.from&&this.collapsed&&!ni(this.doc,a)&&e&&ji(a,Kt(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=Qr(this.lines[o]),u=d(l);u>e.display.maxLineLength&&(e.display.maxLine=l,e.display.maxLineLength=u,e.display.maxLineChanged=!0)}null!=r&&e&&this.collapsed&&gn(e,r,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&ht(e.doc)),e&&no(e,"markerCleared",e,this),t&&tn(e),this.parent&&this.parent.clear()}},Ja.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var n,r,i=0;i<this.lines.length;++i){var o=this.lines[i],a=Ir(o.markedSpans,this);if(null!=a.from&&(n=ya(t?o:Ii(o),a.from),-1==e))return n;if(null!=a.to&&(r=ya(t?o:Ii(o),a.to),1==e))return r}return n&&{from:n,to:r}},Ja.prototype.changed=function(){var e=this.find(-1,!0),t=this,n=this.doc.cm;e&&n&&un(n,function(){var r=e.line,i=Ii(e.line),o=jt(n,i);if(o&&(Pt(o),n.curOp.selectionChanged=n.curOp.forceUpdate=!0),n.curOp.updateMaxLine=!0,!ni(t.doc,r)&&null!=t.height){var a=t.height;t.height=null;var s=oi(t)-a;s&&ji(r,r.height+s)}})},Ja.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=ho(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)},Ja.prototype.detachLine=function(e){if(this.lines.splice(ho(this.lines,e),1),!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var Ya=0,Ka=e.SharedTextMarker=function(e,t){this.markers=e,this.primary=t;for(var n=0;n<e.length;++n)e[n].parent=this};so(Ka),Ka.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();no(this,"clear")}},Ka.prototype.find=function(e,t){return this.primary.find(e,t)};var Qa=e.LineWidget=function(e,t,n){if(n)for(var r in n)n.hasOwnProperty(r)&&(this[r]=n[r]);this.cm=e,this.node=t};so(Qa),Qa.prototype.clear=function(){var e=this.cm,t=this.line.widgets,n=this.line,r=Ii(n);if(null!=r&&t){for(var i=0;i<t.length;++i)t[i]==this&&t.splice(i--,1);t.length||(n.widgets=null);var o=oi(this);un(e,function(){ii(e,n,-o),mn(e,r,"widget"),ji(n,Math.max(0,n.height-o))})}},Qa.prototype.changed=function(){var e=this.height,t=this.cm,n=this.line;this.height=null;var r=oi(this)-e;r&&un(t,function(){t.curOp.forceUpdate=!0,ii(t,n,r),ji(n,n.height+r)})};var Za=e.Line=function(e,t,n){this.text=e,Ur(this,t),this.height=n?n(this):1};so(Za),Za.prototype.lineNo=function(){return Ii(this)};var es={},ts={};ki.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var n=e,r=e+t;r>n;++n){var i=this.lines[n];this.height-=i.height,li(i),no(i,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,n){this.height+=n,this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,n){for(var r=e+t;r>e;++e)if(n(this.lines[e]))return!0}},Li.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var n=0;n<this.children.length;++n){var r=this.children[n],i=r.chunkSize();if(i>e){var o=Math.min(t,i-e),a=r.height;if(r.removeInner(e,o),this.height-=a-r.height,i==o&&(this.children.splice(n--,1),r.parent=null),0==(t-=o))break;e=0}else e-=i}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof ki))){var s=[];this.collapse(s),this.children=[new ki(s)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,n){this.size+=t.length,this.height+=n;for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>=e){if(i.insertInner(e,t,n),i.lines&&i.lines.length>50){for(;i.lines.length>50;){var a=i.lines.splice(i.lines.length-25,25),s=new ki(a);i.height-=s.height,this.children.splice(r+1,0,s),s.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),n=new Li(t);if(e.parent){e.size-=n.size,e.height-=n.height;var r=ho(e.parent.children,e);e.parent.children.splice(r+1,0,n)}else{var i=new Li(e.children);i.parent=e,e.children=[i,n],e=i}n.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>e){var a=Math.min(t,o-e);if(i.iterN(e,a,n))return!0;if(0==(t-=a))break;e=0}else e-=o}}};var ns=0,rs=e.Doc=function(e,t,n){if(!(this instanceof rs))return new rs(e,t,n);null==n&&(n=0),Li.call(this,[new ki([new Za("",null)])]),this.first=n,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.frontier=n;var r=ya(n,0);this.sel=K(r),this.history=new Pi(null),this.id=++ns,this.modeOption=t,"string"==typeof e&&(e=_s(e)),Di(this,{from:r,to:r,text:e}),ct(this,K(r),gs)};rs.prototype=go(Li.prototype,{constructor:rs,iter:function(e,t,n){n?this.iterN(e-this.first,t-e,n):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var n=0,r=0;r<t.length;++r)n+=t[r].height;this.insertInner(e-this.first,t,n)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Ei(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:dn(function(e){var t=ya(this.first,0),n=this.first+this.size-1;sr(this,{from:t,to:ya(n,_i(this,n).text.length),text:_s(e),origin:"setValue"},!0),ct(this,K(t))}),replaceRange:function(e,t,n,r){t=Z(this,t),n=n?Z(this,n):t,hr(this,e,t,n,r)},getRange:function(e,t,n){var r=Mi(this,Z(this,e),Z(this,t));return n===!1?r:r.join(n||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return tt(this,e)?_i(this,e):void 0},getLineNumber:function(e){return Ii(e)},getLineHandleVisualStart:function(e){return"number"==typeof e&&(e=_i(this,e)),Qr(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return Z(this,e)},getCursor:function(e){var t,n=this.sel.primary();return t=null==e||"head"==e?n.head:"anchor"==e?n.anchor:"end"==e||"to"==e||e===!1?n.to():n.from()},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:dn(function(e,t,n){st(this,Z(this,"number"==typeof e?ya(e,t||0):e),null,n)}),setSelection:dn(function(e,t,n){st(this,Z(this,e),Z(this,t||e),n)}),extendSelection:dn(function(e,t,n){it(this,Z(this,e),t&&Z(this,t),n)}),extendSelections:dn(function(e,t){ot(this,nt(this,e,t))}),extendSelectionsBy:dn(function(e,t){ot(this,po(this.sel.ranges,e),t)}),setSelections:dn(function(e,t,n){if(e.length){for(var r=0,i=[];r<e.length;r++)i[r]=new J(Z(this,e[r].anchor),Z(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex)),ct(this,Y(i,t),n)}}),addSelection:dn(function(e,t,n){var r=this.sel.ranges.slice(0);r.push(new J(Z(this,e),Z(this,t||e))),ct(this,Y(r,r.length-1),n)}),getSelection:function(e){for(var t,n=this.sel.ranges,r=0;r<n.length;r++){var i=Mi(this,n[r].from(),n[r].to());t=t?t.concat(i):i}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],n=this.sel.ranges,r=0;r<n.length;r++){var i=Mi(this,n[r].from(),n[r].to());e!==!1&&(i=i.join(e||"\n")),t[r]=i}return t},replaceSelection:function(e,t,n){for(var r=[],i=0;i<this.sel.ranges.length;i++)r[i]=e;this.replaceSelections(r,t,n||"+input")},replaceSelections:dn(function(e,t,n){for(var r=[],i=this.sel,o=0;o<i.ranges.length;o++){var a=i.ranges[o];r[o]={from:a.from(),to:a.to(),text:_s(e[o]),origin:n}}for(var s=t&&"end"!=t&&or(this,r,t),o=r.length-1;o>=0;o--)sr(this,r[o]);s?ut(this,s):this.cm&&br(this.cm)}),undo:dn(function(){ur(this,"undo")}),redo:dn(function(){ur(this,"redo")}),undoSelection:dn(function(){ur(this,"undo",!0)}),redoSelection:dn(function(){ur(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++n;return{undo:t,redo:n}},clearHistory:function(){this.history=new Pi(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){return e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null),this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:Ji(this.history.done),undone:Ji(this.history.undone)}},setHistory:function(e){var t=this.history=new Pi(this.history.maxGeneration);t.done=Ji(e.done.slice(0),null,!0),t.undone=Ji(e.undone.slice(0),null,!0)},addLineClass:dn(function(e,t,n){return Sr(this,e,"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"wrapClass";if(e[r]){if(new RegExp("(?:^|\\s)"+n+"(?:$|\\s)").test(e[r]))return!1;e[r]+=" "+n}else e[r]=n;return!0})}),removeLineClass:dn(function(e,t,n){return Sr(this,e,"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"wrapClass",i=e[r];if(!i)return!1;if(null==n)e[r]=null;else{var o=i.match(new RegExp("(?:^|\\s+)"+n+"(?:$|\\s+)"));if(!o)return!1;var a=o.index+o[0].length;e[r]=i.slice(0,o.index)+(o.index&&a!=i.length?" ":"")+i.slice(a)||null}return!0})}),markText:function(e,t,n){return Ar(this,Z(this,e),Z(this,t),n,"range")},setBookmark:function(e,t){var n={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};return e=Z(this,e),Ar(this,e,e,n,"bookmark")},findMarksAt:function(e){e=Z(this,e);var t=[],n=_i(this,e.line).markedSpans;if(n)for(var r=0;r<n.length;++r){var i=n[r];(null==i.from||i.from<=e.ch)&&(null==i.to||i.to>=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,n){e=Z(this,e),t=Z(this,t);var r=[],i=e.line;return this.iter(e.line,t.line+1,function(o){var a=o.markedSpans;if(a)for(var s=0;s<a.length;s++){var l=a[s];i==e.line&&e.ch>l.to||null==l.from&&i!=e.line||i==t.line&&l.from>t.ch||n&&!n(l.marker)||r.push(l.marker.parent||l.marker)}++i}),r},getAllMarks:function(){var e=[];return this.iter(function(t){var n=t.markedSpans;if(n)for(var r=0;r<n.length;++r)null!=n[r].from&&e.push(n[r].marker)}),e},posFromIndex:function(e){var t,n=this.first;return this.iter(function(r){var i=r.text.length+1;return i>e?(t=e,!0):(e-=i,void++n)}),Z(this,ya(n,t))},indexFromPos:function(e){e=Z(this,e);var t=e.ch;return e.line<this.first||e.ch<0?0:(this.iter(this.first,e.line,function(e){t+=e.text.length+1}),t)},copy:function(e){var t=new rs(Ei(this,this.first,this.first+this.size),this.modeOption,this.first);return t.scrollTop=this.scrollTop,t.scrollLeft=this.scrollLeft,t.sel=this.sel,t.extend=!1,e&&(t.history.undoDepth=this.history.undoDepth,t.setHistory(this.getHistory())),t},linkedDoc:function(e){e||(e={});var t=this.first,n=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from),null!=e.to&&e.to<n&&(n=e.to);var r=new rs(Ei(this,t,n),e.mode||this.modeOption,t);return e.sharedHist&&(r.history=this.history),(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist}),r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}],Mr(r,_r(this)),r},unlinkDoc:function(t){if(t instanceof e&&(t=t.doc),this.linked)for(var n=0;n<this.linked.length;++n){var r=this.linked[n];if(r.doc==t){this.linked.splice(n,1),t.unlinkDoc(this),Er(_r(this));break}}if(t.history==this.history){var i=[t.id];Ai(t,function(e){i.push(e.id)},!0),t.history=new Pi(null),t.history.done=Ji(this.history.done,i),t.history.undone=Ji(this.history.undone,i)}},iterLinkedDocs:function(e){Ai(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}}),rs.prototype.eachLine=rs.prototype.iter;var is="iter insert remove copy getEditor".split(" ");for(var os in rs.prototype)rs.prototype.hasOwnProperty(os)&&ho(is,os)<0&&(e.prototype[os]=function(e){return function(){return e.apply(this.doc,arguments)}}(rs.prototype[os]));so(rs);var as=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},ss=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ls=e.e_stop=function(e){as(e),ss(e)},us=e.on=function(e,t,n){if(e.addEventListener)e.addEventListener(t,n,!1);else if(e.attachEvent)e.attachEvent("on"+t,n);else{var r=e._handlers||(e._handlers={}),i=r[t]||(r[t]=[]);i.push(n)}},cs=e.off=function(e,t,n){if(e.removeEventListener)e.removeEventListener(t,n,!1);else if(e.detachEvent)e.detachEvent("on"+t,n);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var i=0;i<r.length;++i)if(r[i]==n){r.splice(i,1);break}}},fs=e.signal=function(e,t){var n=e._handlers&&e._handlers[t];if(n)for(var r=Array.prototype.slice.call(arguments,2),i=0;i<n.length;++i)n[i].apply(null,r)},ds=null,hs=30,ps=e.Pass={toString:function(){return"CodeMirror.Pass"}},gs={scroll:!1},ms={origin:"*mouse"},vs={origin:"+move"};lo.prototype.set=function(e,t){clearTimeout(this.id),this.id=setTimeout(t,e)};var ys=e.countColumn=function(e,t,n,r,i){null==t&&(t=e.search(/[^\s\u00a0]/),-1==t&&(t=e.length));for(var o=r||0,a=i||0;;){var s=e.indexOf(" ",o);if(0>s||s>=t)return a+(t-o);a+=s-o,a+=n-a%n,o=s+1}},bs=[""],xs=function(e){e.select()};ua?xs=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:Zo&&(xs=function(e){try{e.select()}catch(t){}}),[].indexOf&&(ho=function(e,t){return e.indexOf(t)}),[].map&&(po=function(e,t){return e.map(t)});var ws,Ss=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Cs=e.isWordChar=function(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||Ss.test(e))},Ts=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;ws=document.createRange?function(e,t,n){var r=document.createRange();return r.setEnd(e,n),r.setStart(e,t),r}:function(e,t,n){var r=document.body.createTextRange();return r.moveToElementText(e.parentNode),r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",t),r},Zo&&11>ea&&(Do=function(){try{return document.activeElement}catch(e){return document.body}});var Ds,ks,Ls,As=!1,Ns=function(){if(Zo&&9>ea)return!1;var e=wo("div");return"draggable"in e||"dragDrop"in e}(),_s=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,n=[],r=e.length;r>=t;){var i=e.indexOf("\n",t);-1==i&&(i=e.length);var o=e.slice(t,"\r"==e.charAt(i-1)?i-1:i),a=o.indexOf("\r");-1!=a?(n.push(o.slice(0,a)),t+=a+1):(n.push(o),t=i+1)}return n}:function(e){return e.split(/\r\n?|\n/)},Ms=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(n){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Es=function(){var e=wo("div");return"oncopy"in e?!0:(e.setAttribute("oncopy","return;"),"function"==typeof e.oncopy)}(),js=null,Is={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};e.keyNames=Is,function(){for(var e=0;10>e;e++)Is[e+48]=Is[e+96]=String(e);for(var e=65;90>=e;e++)Is[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Is[e+111]=Is[e+63235]="F"+e}();var Hs,Os=function(){function e(e){return 247>=e?n.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L" }function t(e,t,n){this.level=e,this.from=t,this.to=n}var n="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",i=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,a=/[LRr]/,s=/[Lb1n]/,l=/[1n]/,u="L";return function(n){if(!i.test(n))return!1;for(var r,c=n.length,f=[],d=0;c>d;++d)f.push(r=e(n.charCodeAt(d)));for(var d=0,h=u;c>d;++d){var r=f[d];"m"==r?f[d]=h:h=r}for(var d=0,p=u;c>d;++d){var r=f[d];"1"==r&&"r"==p?f[d]="n":a.test(r)&&(p=r,"r"==r&&(f[d]="R"))}for(var d=1,h=f[0];c-1>d;++d){var r=f[d];"+"==r&&"1"==h&&"1"==f[d+1]?f[d]="1":","!=r||h!=f[d+1]||"1"!=h&&"n"!=h||(f[d]=h),h=r}for(var d=0;c>d;++d){var r=f[d];if(","==r)f[d]="N";else if("%"==r){for(var g=d+1;c>g&&"%"==f[g];++g);for(var m=d&&"!"==f[d-1]||c>g&&"1"==f[g]?"1":"N",v=d;g>v;++v)f[v]=m;d=g-1}}for(var d=0,p=u;c>d;++d){var r=f[d];"L"==p&&"1"==r?f[d]="L":a.test(r)&&(p=r)}for(var d=0;c>d;++d)if(o.test(f[d])){for(var g=d+1;c>g&&o.test(f[g]);++g);for(var y="L"==(d?f[d-1]:u),b="L"==(c>g?f[g]:u),m=y||b?"L":"R",v=d;g>v;++v)f[v]=m;d=g-1}for(var x,w=[],d=0;c>d;)if(s.test(f[d])){var S=d;for(++d;c>d&&s.test(f[d]);++d);w.push(new t(0,S,d))}else{var C=d,T=w.length;for(++d;c>d&&"L"!=f[d];++d);for(var v=C;d>v;)if(l.test(f[v])){v>C&&w.splice(T,0,new t(1,C,v));var D=v;for(++v;d>v&&l.test(f[v]);++v);w.splice(T,0,new t(2,D,v)),C=v}else++v;d>C&&w.splice(T,0,new t(1,C,d))}return 1==w[0].level&&(x=n.match(/^\s+/))&&(w[0].from=x[0].length,w.unshift(new t(0,0,x[0].length))),1==fo(w).level&&(x=n.match(/\s+$/))&&(fo(w).to-=x[0].length,w.push(new t(0,c-x[0].length,c))),w[0].level!=fo(w).level&&w.push(new t(w[0].level,c,c)),w}}();return e.version="4.7.0",e})},{}],6:[function(t,n,r){!function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)}(function(e){"use strict";e.defineMode("javascript",function(t,n){function r(e){for(var t,n=!1,r=!1;null!=(t=e.next());){if(!n){if("/"==t&&!r)return;"["==t?r=!0:r&&"]"==t&&(r=!1)}n=!n&&"\\"==t}}function i(e,t,n){return pt=e,gt=n,t}function o(e,t){var n=e.next();if('"'==n||"'"==n)return t.tokenize=a(n),t.tokenize(e,t);if("."==n&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return i("number","number");if("."==n&&e.match(".."))return i("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return i(n);if("="==n&&e.eat(">"))return i("=>","operator");if("0"==n&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),i("number","number");if(/\d/.test(n))return e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),i("number","number");if("/"==n)return e.eat("*")?(t.tokenize=s,s(e,t)):e.eat("/")?(e.skipToEnd(),i("comment","comment")):"operator"==t.lastType||"keyword c"==t.lastType||"sof"==t.lastType||/^[\[{}\(,;:]$/.test(t.lastType)?(r(e),e.eatWhile(/[gimy]/),i("regexp","string-2")):(e.eatWhile(Ct),i("operator","operator",e.current()));if("`"==n)return t.tokenize=l,l(e,t);if("#"==n)return e.skipToEnd(),i("error","error");if(Ct.test(n))return e.eatWhile(Ct),i("operator","operator",e.current());if(wt.test(n)){e.eatWhile(wt);var o=e.current(),u=St.propertyIsEnumerable(o)&&St[o];return u&&"."!=t.lastType?i(u.type,u.style,o):i("variable","variable",o)}}function a(e){return function(t,n){var r,a=!1;if(yt&&"@"==t.peek()&&t.match(Tt))return n.tokenize=o,i("jsonld-keyword","meta");for(;null!=(r=t.next())&&(r!=e||a);)a=!a&&"\\"==r;return a||(n.tokenize=o),i("string","string")}}function s(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=o;break}r="*"==n}return i("comment","comment")}function l(e,t){for(var n,r=!1;null!=(n=e.next());){if(!r&&("`"==n||"$"==n&&e.eat("{"))){t.tokenize=o;break}r=!r&&"\\"==n}return i("quasi","string-2",e.current())}function u(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(!(0>n)){for(var r=0,i=!1,o=n-1;o>=0;--o){var a=e.string.charAt(o),s=Dt.indexOf(a);if(s>=0&&3>s){if(!r){++o;break}if(0==--r)break}else if(s>=3&&6>s)++r;else if(wt.test(a))i=!0;else if(i&&!r){++o;break}}i&&!r&&(t.fatArrowAt=o)}}function c(e,t,n,r,i,o){this.indented=e,this.column=t,this.type=n,this.prev=i,this.info=o,null!=r&&(this.align=r)}function f(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==t)return!0}function d(e,t,n,r,i){var o=e.cc;for(Lt.state=e,Lt.stream=i,Lt.marked=null,Lt.cc=o,Lt.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;){var a=o.length?o.pop():bt?S:w;if(a(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return Lt.marked?Lt.marked:"variable"==n&&f(e,r)?"variable-2":t}}}function h(){for(var e=arguments.length-1;e>=0;e--)Lt.cc.push(arguments[e])}function p(){return h.apply(null,arguments),!0}function g(e){function t(t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}var r=Lt.state;if(r.context){if(Lt.marked="def",t(r.localVars))return;r.localVars={name:e,next:r.localVars}}else{if(t(r.globalVars))return;n.globalVars&&(r.globalVars={name:e,next:r.globalVars})}}function m(){Lt.state.context={prev:Lt.state.context,vars:Lt.state.localVars},Lt.state.localVars=At}function v(){Lt.state.localVars=Lt.state.context.vars,Lt.state.context=Lt.state.context.prev}function y(e,t){var n=function(){var n=Lt.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new c(r,Lt.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function b(){var e=Lt.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function x(e){function t(n){return n==e?p():";"==e?h():p(t)}return t}function w(e,t){return"var"==e?p(y("vardef",t.length),q,x(";"),b):"keyword a"==e?p(y("form"),S,w,b):"keyword b"==e?p(y("form"),w,b):"{"==e?p(y("}"),W,b):";"==e?p():"if"==e?("else"==Lt.state.lexical.info&&Lt.state.cc[Lt.state.cc.length-1]==b&&Lt.state.cc.pop()(),p(y("form"),S,w,b,$)):"function"==e?p(et):"for"==e?p(y("form"),J,w,b):"variable"==e?p(y("stat"),j):"switch"==e?p(y("form"),S,y("}","switch"),x("{"),W,b,b):"case"==e?p(S,x(":")):"default"==e?p(x(":")):"catch"==e?p(y("form"),m,x("("),tt,x(")"),w,b,v):"module"==e?p(y("form"),m,at,v,b):"class"==e?p(y("form"),nt,b):"export"==e?p(y("form"),st,b):"import"==e?p(y("form"),lt,b):h(y("stat"),S,x(";"),b)}function S(e){return T(e,!1)}function C(e){return T(e,!0)}function T(e,t){if(Lt.state.fatArrowAt==Lt.stream.start){var n=t?E:M;if("("==e)return p(m,y(")"),P(U,")"),b,x("=>"),n,v);if("variable"==e)return h(m,U,x("=>"),n,v)}var r=t?A:L;return kt.hasOwnProperty(e)?p(r):"function"==e?p(et,r):"keyword c"==e?p(t?k:D):"("==e?p(y(")"),D,ht,x(")"),b,r):"operator"==e||"spread"==e?p(t?C:S):"["==e?p(y("]"),ft,b,r):"{"==e?F(H,"}",null,r):"quasi"==e?h(N,r):p()}function D(e){return e.match(/[;\}\)\],]/)?h():h(S)}function k(e){return e.match(/[;\}\)\],]/)?h():h(C)}function L(e,t){return","==e?p(S):A(e,t,!1)}function A(e,t,n){var r=0==n?L:A,i=0==n?S:C;return"=>"==e?p(m,n?E:M,v):"operator"==e?/\+\+|--/.test(t)?p(r):"?"==t?p(S,x(":"),i):p(i):"quasi"==e?h(N,r):";"!=e?"("==e?F(C,")","call",r):"."==e?p(I,r):"["==e?p(y("]"),D,x("]"),b,r):void 0:void 0}function N(e,t){return"quasi"!=e?h():"${"!=t.slice(t.length-2)?p(N):p(S,_)}function _(e){return"}"==e?(Lt.marked="string-2",Lt.state.tokenize=l,p(N)):void 0}function M(e){return u(Lt.stream,Lt.state),h("{"==e?w:S)}function E(e){return u(Lt.stream,Lt.state),h("{"==e?w:C)}function j(e){return":"==e?p(b,w):h(L,x(";"),b)}function I(e){return"variable"==e?(Lt.marked="property",p()):void 0}function H(e,t){return"variable"==e||"keyword"==Lt.style?(Lt.marked="property",p("get"==t||"set"==t?O:R)):"number"==e||"string"==e?(Lt.marked=yt?"property":Lt.style+" property",p(R)):"jsonld-keyword"==e?p(R):"["==e?p(S,x("]"),R):void 0}function O(e){return"variable"!=e?h(R):(Lt.marked="property",p(et))}function R(e){return":"==e?p(C):"("==e?h(et):void 0}function P(e,t){function n(r){if(","==r){var i=Lt.state.lexical;return"call"==i.info&&(i.pos=(i.pos||0)+1),p(e,n)}return r==t?p():p(x(t))}return function(r){return r==t?p():h(e,n)}}function F(e,t,n){for(var r=3;r<arguments.length;r++)Lt.cc.push(arguments[r]);return p(y(t,n),P(e,t),b)}function W(e){return"}"==e?p():h(w,W)}function z(e){return xt&&":"==e?p(B):void 0}function B(e){return"variable"==e?(Lt.marked="variable-3",p()):void 0}function q(){return h(U,z,X,G)}function U(e,t){return"variable"==e?(g(t),p()):"["==e?F(U,"]"):"{"==e?F(V,"}"):void 0}function V(e,t){return"variable"!=e||Lt.stream.match(/^\s*:/,!1)?("variable"==e&&(Lt.marked="property"),p(x(":"),U,X)):(g(t),p(X))}function X(e,t){return"="==t?p(C):void 0}function G(e){return","==e?p(q):void 0}function $(e,t){return"keyword b"==e&&"else"==t?p(y("form","else"),w,b):void 0}function J(e){return"("==e?p(y(")"),Y,x(")"),b):void 0}function Y(e){return"var"==e?p(q,x(";"),Q):";"==e?p(Q):"variable"==e?p(K):h(S,x(";"),Q)}function K(e,t){return"in"==t||"of"==t?(Lt.marked="keyword",p(S)):p(L,Q)}function Q(e,t){return";"==e?p(Z):"in"==t||"of"==t?(Lt.marked="keyword",p(S)):h(S,x(";"),Z)}function Z(e){")"!=e&&p(S)}function et(e,t){return"*"==t?(Lt.marked="keyword",p(et)):"variable"==e?(g(t),p(et)):"("==e?p(m,y(")"),P(tt,")"),b,w,v):void 0}function tt(e){return"spread"==e?p(tt):h(U,z)}function nt(e,t){return"variable"==e?(g(t),p(rt)):void 0}function rt(e,t){return"extends"==t?p(S,rt):"{"==e?p(y("}"),it,b):void 0}function it(e,t){return"variable"==e||"keyword"==Lt.style?(Lt.marked="property","get"==t||"set"==t?p(ot,et,it):p(et,it)):"*"==t?(Lt.marked="keyword",p(it)):";"==e?p(it):"}"==e?p():void 0}function ot(e){return"variable"!=e?h():(Lt.marked="property",p())}function at(e,t){return"string"==e?p(w):"variable"==e?(g(t),p(ct)):void 0}function st(e,t){return"*"==t?(Lt.marked="keyword",p(ct,x(";"))):"default"==t?(Lt.marked="keyword",p(S,x(";"))):h(w)}function lt(e){return"string"==e?p():h(ut,ct)}function ut(e,t){return"{"==e?F(ut,"}"):("variable"==e&&g(t),p())}function ct(e,t){return"from"==t?(Lt.marked="keyword",p(S)):void 0}function ft(e){return"]"==e?p():h(C,dt)}function dt(e){return"for"==e?h(ht,x("]")):","==e?p(P(k,"]")):h(P(C,"]"))}function ht(e){return"for"==e?p(J,ht):"if"==e?p(S,ht):void 0}var pt,gt,mt=t.indentUnit,vt=n.statementIndent,yt=n.jsonld,bt=n.json||yt,xt=n.typescript,wt=n.wordCharacters||/[\w$\xa1-\uffff]/,St=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),n=e("keyword b"),r=e("keyword c"),i=e("operator"),o={type:"atom",style:"atom"},a={"if":e("if"),"while":t,"with":t,"else":n,"do":n,"try":n,"finally":n,"return":r,"break":r,"continue":r,"new":r,"delete":r,"throw":r,"debugger":r,"var":e("var"),"const":e("var"),let:e("var"),"function":e("function"),"catch":e("catch"),"for":e("for"),"switch":e("switch"),"case":e("case"),"default":e("default"),"in":i,"typeof":i,"instanceof":i,"true":o,"false":o,"null":o,undefined:o,NaN:o,Infinity:o,"this":e("this"),module:e("module"),"class":e("class"),"super":e("atom"),"yield":r,"export":e("export"),"import":e("import"),"extends":r};if(xt){var s={type:"variable",style:"variable-3"},l={"interface":e("interface"),"extends":e("extends"),constructor:e("constructor"),"public":e("public"),"private":e("private"),"protected":e("protected"),"static":e("static"),string:s,number:s,bool:s,any:s};for(var u in l)a[u]=l[u]}return a}(),Ct=/[+\-*&%=<>!?|~^]/,Tt=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,Dt="([{}])",kt={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},Lt={state:null,column:null,marked:null,cc:null},At={name:"this",next:{name:"arguments"}};return b.lex=!0,{startState:function(e){var t={tokenize:o,lastType:"sof",cc:[],lexical:new c((e||0)-mt,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};return n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),u(e,t)),t.tokenize!=s&&e.eatSpace())return null;var n=t.tokenize(e,t);return"comment"==pt?n:(t.lastType="operator"!=pt||"++"!=gt&&"--"!=gt?pt:"incdec",d(t,n,pt,gt,e))},indent:function(t,r){if(t.tokenize==s)return e.Pass;if(t.tokenize!=o)return 0;var i=r&&r.charAt(0),a=t.lexical;if(!/^\s*else\b/.test(r))for(var l=t.cc.length-1;l>=0;--l){var u=t.cc[l];if(u==b)a=a.prev;else if(u!=$)break}"stat"==a.type&&"}"==i&&(a=a.prev),vt&&")"==a.type&&"stat"==a.prev.type&&(a=a.prev);var c=a.type,f=i==c;return"vardef"==c?a.indented+("operator"==t.lastType||","==t.lastType?a.info+1:0):"form"==c&&"{"==i?a.indented:"form"==c?a.indented+mt:"stat"==c?a.indented+("operator"==t.lastType||","==t.lastType?vt||mt:0):"switch"!=a.info||f||0==n.doubleIndentSwitch?a.align?a.column+(f?0:1):a.indented+(f?0:mt):a.indented+(/^(?:case|default)\b/.test(r)?mt:2*mt)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:bt?null:"/*",blockCommentEnd:bt?null:"*/",lineComment:bt?null:"//",fold:"brace",helperType:bt?"json":"javascript",jsonldMode:yt,jsonMode:bt}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})})},{"../../lib/codemirror":5}],7:[function(t,n,r){!function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)}(function(e){"use strict";e.defineMode("xml",function(t,n){function r(e,t){function n(n){return t.tokenize=n,n(e,t)}var r=e.next();if("<"==r)return e.eat("!")?e.eat("[")?e.match("CDATA[")?n(a("atom","]]>")):null:e.match("--")?n(a("comment","-->")):e.match("DOCTYPE",!0,!0)?(e.eatWhile(/[\w\._\-]/),n(s(1))):null:e.eat("?")?(e.eatWhile(/[\w\._\-]/),t.tokenize=a("meta","?>"),"meta"):(C=e.eat("/")?"closeTag":"openTag",t.tokenize=i,"tag bracket");if("&"==r){var o;return o=e.eat("#")?e.eat("x")?e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):e.eatWhile(/[\d]/)&&e.eat(";"):e.eatWhile(/[\w\.\-:]/)&&e.eat(";"),o?"atom":"error"}return e.eatWhile(/[^&<]/),null}function i(e,t){var n=e.next();if(">"==n||"/"==n&&e.eat(">"))return t.tokenize=r,C=">"==n?"endTag":"selfcloseTag","tag bracket";if("="==n)return C="equals",null;if("<"==n){t.tokenize=r,t.state=f,t.tagName=t.tagStart=null;var i=t.tokenize(e,t);return i?i+" tag error":"tag error"}return/[\'\"]/.test(n)?(t.tokenize=o(n),t.stringStartCol=e.column(),t.tokenize(e,t)):(e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function o(e){var t=function(t,n){for(;!t.eol();)if(t.next()==e){n.tokenize=i;break}return"string"};return t.isInAttribute=!0,t}function a(e,t){return function(n,i){for(;!n.eol();){if(n.match(t)){i.tokenize=r;break}n.next()}return e}}function s(e){return function(t,n){for(var i;null!=(i=t.next());){if("<"==i)return n.tokenize=s(e+1),n.tokenize(t,n);if(">"==i){if(1==e){n.tokenize=r;break}return n.tokenize=s(e-1),n.tokenize(t,n)}}return"meta"}}function l(e,t,n){this.prev=e.context,this.tagName=t,this.indent=e.indented,this.startOfLine=n,(D.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function u(e){e.context&&(e.context=e.context.prev)}function c(e,t){for(var n;;){if(!e.context)return;if(n=e.context.tagName,!D.contextGrabbers.hasOwnProperty(n)||!D.contextGrabbers[n].hasOwnProperty(t))return;u(e)}}function f(e,t,n){return"openTag"==e?(n.tagStart=t.column(),d):"closeTag"==e?h:f}function d(e,t,n){return"word"==e?(n.tagName=t.current(),T="tag",m):(T="error",d)}function h(e,t,n){if("word"==e){var r=t.current();return n.context&&n.context.tagName!=r&&D.implicitlyClosed.hasOwnProperty(n.context.tagName)&&u(n),n.context&&n.context.tagName==r?(T="tag",p):(T="tag error",g)}return T="error",g}function p(e,t,n){return"endTag"!=e?(T="error",p):(u(n),f)}function g(e,t,n){return T="error",p(e,t,n)}function m(e,t,n){if("word"==e)return T="attribute",v;if("endTag"==e||"selfcloseTag"==e){var r=n.tagName,i=n.tagStart;return n.tagName=n.tagStart=null,"selfcloseTag"==e||D.autoSelfClosers.hasOwnProperty(r)?c(n,r):(c(n,r),n.context=new l(n,r,i==n.indented)),f}return T="error",m}function v(e,t,n){return"equals"==e?y:(D.allowMissing||(T="error"),m(e,t,n))}function y(e,t,n){return"string"==e?b:"word"==e&&D.allowUnquoted?(T="string",m):(T="error",m(e,t,n))}function b(e,t,n){return"string"==e?b:m(e,t,n)}var x=t.indentUnit,w=n.multilineTagIndentFactor||1,S=n.multilineTagIndentPastTag;null==S&&(S=!0);var C,T,D=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},k=n.alignCDATA;return{startState:function(){return{tokenize:r,state:f,indented:0,tagName:null,tagStart:null,context:null}},token:function(e,t){if(!t.tagName&&e.sol()&&(t.indented=e.indentation()),e.eatSpace())return null;C=null;var n=t.tokenize(e,t);return(n||C)&&"comment"!=n&&(T=null,t.state=t.state(C||n,e,t),T&&(n="error"==T?n+" error":T)),n},indent:function(t,n,o){var a=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+x;if(a&&a.noIndent)return e.Pass;if(t.tokenize!=i&&t.tokenize!=r)return o?o.match(/^(\s*)/)[0].length:0;if(t.tagName)return S?t.tagStart+t.tagName.length+2:t.tagStart+x*w;if(k&&/<!\[CDATA\[/.test(n))return 0;var s=n&&/^<(\/)?([\w_:\.-]*)/.exec(n);if(s&&s[1])for(;a;){if(a.tagName==s[2]){a=a.prev;break}if(!D.implicitlyClosed.hasOwnProperty(a.tagName))break;a=a.prev}else if(s)for(;a;){var l=D.contextGrabbers[a.tagName];if(!l||!l.hasOwnProperty(s[2]))break;a=a.prev}for(;a&&!a.startOfLine;)a=a.prev;return a?a.indent+x:0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"}}),e.defineMIME("text/xml","xml"),e.defineMIME("application/xml","xml"),e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})})},{"../../lib/codemirror":5}],8:[function(t,n){!function(e,t){"object"==typeof n&&"object"==typeof n.exports?n.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(t,n){function r(e){var t=e.length,n=ot.type(e);return"function"===n||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function i(e,t,n){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return ot.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(ht.test(t))return ot.filter(t,e,n);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==n})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function a(e){var t=wt[e]={};return ot.each(e.match(xt)||[],function(e,n){t[n]=!0}),t}function s(){gt.addEventListener?(gt.removeEventListener("DOMContentLoaded",l,!1),t.removeEventListener("load",l,!1)):(gt.detachEvent("onreadystatechange",l),t.detachEvent("onload",l))}function l(){(gt.addEventListener||"load"===event.type||"complete"===gt.readyState)&&(s(),ot.ready())}function u(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(kt,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Dt.test(n)?ot.parseJSON(n):n}catch(i){}ot.data(e,t,n)}else n=void 0}return n}function c(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function f(e,t,n,r){if(ot.acceptData(e)){var i,o,a=ot.expando,s=e.nodeType,l=s?ot.cache:e,u=s?e[a]:e[a]&&a;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof t)return u||(u=s?e[a]=J.pop()||ot.guid++:a),l[u]||(l[u]=s?{}:{toJSON:ot.noop}),("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[ot.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[ot.camelCase(t)])):i=o,i}}function d(e,t,n){if(ot.acceptData(e)){var r,i,o=e.nodeType,a=o?ot.cache:e,s=o?e[ot.expando]:ot.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){ot.isArray(t)?t=t.concat(ot.map(t,ot.camelCase)):t in r?t=[t]:(t=ot.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!c(r):!ot.isEmptyObject(r))return}(n||(delete a[s].data,c(a[s])))&&(o?ot.cleanData([e],!0):rt.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function h(){return!0}function p(){return!1}function g(){try{return gt.activeElement}catch(e){}}function m(e){var t=Rt.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function v(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Tt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Tt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,v(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function y(e){Mt.test(e.type)&&(e.defaultChecked=e.checked)}function b(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function x(e){return e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type,e}function w(e){var t=$t.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function S(e,t){for(var n,r=0;null!=(n=e[r]);r++)ot._data(n,"globalEval",!t||ot._data(t[r],"globalEval"))}function C(e,t){if(1===t.nodeType&&ot.hasData(e)){var n,r,i,o=ot._data(e),a=ot._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++)ot.event.add(t,n,s[n][r])}a.data&&(a.data=ot.extend({},a.data))}}function T(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!rt.noCloneEvent&&t[ot.expando]){i=ot._data(t);for(r in i.events)ot.removeEvent(t,r,i.handle);t.removeAttribute(ot.expando)}"script"===n&&t.text!==e.text?(x(t).text=e.text,w(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Mt.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)}}function D(e,n){var r,i=ot(n.createElement(e)).appendTo(n.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(i[0]))?r.display:ot.css(i[0],"display");return i.detach(),o}function k(e){var t=gt,n=en[e];return n||(n=D(e,t),"none"!==n&&n||(Zt=(Zt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Zt[0].contentWindow||Zt[0].contentDocument).document,t.write(),t.close(),n=D(e,t),Zt.detach()),en[e]=n),n}function L(e,t){return{get:function(){var n=e();if(null!=n)return n?void delete this.get:(this.get=t).apply(this,arguments)}}}function A(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=pn.length;i--;)if(t=pn[i]+n,t in e)return t;return r}function N(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=ot._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&Nt(r)&&(o[a]=ot._data(r,"olddisplay",k(r.nodeName)))):(i=Nt(r),(n&&"none"!==n||!i)&&ot._data(r,"olddisplay",i?n:ot.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}function _(e,t,n){var r=cn.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function M(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=ot.css(e,n+At[o],!0,i)),r?("content"===n&&(a-=ot.css(e,"padding"+At[o],!0,i)),"margin"!==n&&(a-=ot.css(e,"border"+At[o]+"Width",!0,i))):(a+=ot.css(e,"padding"+At[o],!0,i),"padding"!==n&&(a+=ot.css(e,"border"+At[o]+"Width",!0,i)));return a}function E(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=tn(e),a=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=nn(e,t,o),(0>i||null==i)&&(i=e.style[t]),on.test(i))return i;r=a&&(rt.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+M(e,t,n||(a?"border":"content"),r,o)+"px"}function j(e,t,n,r,i){return new j.prototype.init(e,t,n,r,i)}function I(){return setTimeout(function(){gn=void 0}),gn=ot.now()}function H(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=At[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function O(e,t,n){for(var r,i=(wn[t]||[]).concat(wn["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function R(e,t,n){var r,i,o,a,s,l,u,c,f=this,d={},h=e.style,p=e.nodeType&&Nt(e),g=ot._data(e,"fxshow");n.queue||(s=ot._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,f.always(function(){f.always(function(){s.unqueued--,ot.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],u=ot.css(e,"display"),c="none"===u?ot._data(e,"olddisplay")||k(e.nodeName):u,"inline"===c&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==k(e.nodeName)?h.zoom=1:h.display="inline-block")),n.overflow&&(h.overflow="hidden",rt.shrinkWrapBlocks()||f.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(p?"hide":"show")){if("show"!==i||!g||void 0===g[r])continue;p=!0}d[r]=g&&g[r]||ot.style(e,r)}else u=void 0;if(ot.isEmptyObject(d))"inline"===("none"===u?k(e.nodeName):u)&&(h.display=u);else{g?"hidden"in g&&(p=g.hidden):g=ot._data(e,"fxshow",{}),o&&(g.hidden=!p),p?ot(e).show():f.done(function(){ot(e).hide()}),f.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d)a=O(p?g[r]:0,r,f),r in g||(g[r]=a.start,p&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function P(e,t){var n,r,i,o,a;for(n in e)if(r=ot.camelCase(n),i=t[r],o=e[n],ot.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=ot.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}function F(e,t,n){var r,i,o=0,a=xn.length,s=ot.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var t=gn||I(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;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:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:gn||I(),duration:n.duration,tweens:[],createTween:function(t,n){var r=ot.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(P(c,u.opts.specialEasing);a>o;o++)if(r=xn[o].call(u,e,c,u.opts))return r;return ot.map(c,O,u),ot.isFunction(u.opts.start)&&u.opts.start.call(e,u),ot.fx.timer(ot.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 W(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(xt)||[];if(ot.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function z(e,t,n,r){function i(s){var l;return o[s]=!0,ot.each(e[s]||[],function(e,s){var u=s(t,n,r);return"string"!=typeof u||a||o[u]?a?!(l=u):void 0:(t.dataTypes.unshift(u),i(u),!1)}),l}var o={},a=e===Vn;return i(t.dataTypes[0])||!o["*"]&&i("*")}function B(e,t){var n,r,i=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&ot.extend(!0,e,n),e}function q(e,t,n){for(var r,i,o,a,s=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){l.unshift(a);break}if(l[0]in n)o=l[0];else{for(a in n){if(!l[0]||e.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==l[0]&&l.unshift(o),n[o]):void 0}function U(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];for(o=c.shift();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(f){return{state:"parsererror",error:a?f:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function V(e,t,n,r){var i;if(ot.isArray(t))ot.each(t,function(t,i){n||Jn.test(e)?r(e,i):V(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==ot.type(t))r(e,t);else for(i in t)V(e+"["+i+"]",t[i],n,r)}function X(){try{return new t.XMLHttpRequest}catch(e){}}function G(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function $(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var J=[],Y=J.slice,K=J.concat,Q=J.push,Z=J.indexOf,et={},tt=et.toString,nt=et.hasOwnProperty,rt={},it="1.11.1",ot=function(e,t){return new ot.fn.init(e,t)},at=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,st=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:it,constructor:ot,selector:"",length:0,toArray:function(){return Y.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:Y.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(Y.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]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Q,sort:J.sort,splice:J.splice},ot.extend=ot.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1; for("boolean"==typeof a&&(u=a,a=arguments[s]||{},s++),"object"==typeof a||ot.isFunction(a)||(a={}),s===l&&(a=this,s--);l>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(u&&n&&(ot.isPlainObject(n)||(t=ot.isArray(n)))?(t?(t=!1,o=e&&ot.isArray(e)?e:[]):o=e&&ot.isPlainObject(e)?e:{},a[r]=ot.extend(u,o,n)):void 0!==n&&(a[r]=n));return a},ot.extend({expando:"jQuery"+(it+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!nt.call(e,"constructor")&&!nt.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(rt.ownLast)for(t in e)return nt.call(e,t);for(t in e);return void 0===t||nt.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(st,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var i,o=0,a=e.length,s=r(e);if(n){if(s)for(;a>o&&(i=t.apply(e[o],n),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],n),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(at,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(r(Object(e))?ot.merge(n,"string"==typeof e?[e]:e):Q.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(Z)return Z.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,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,n){var i,o=0,a=e.length,s=r(e),l=[];if(s)for(;a>o;o++)i=t(e[o],o,n),null!=i&&l.push(i);else for(o in e)i=t(e[o],o,n),null!=i&&l.push(i);return K.apply([],l)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),ot.isFunction(e)?(n=Y.call(arguments,2),r=function(){return e.apply(t||this,n.concat(Y.call(arguments)))},r.guid=e.guid=e.guid||ot.guid++,r):void 0},now:function(){return+new Date},support:rt}),ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var ct=function(e){function t(e,t,n,r){var i,o,a,s,l,u,f,h,p,g;if((t?t.ownerDocument||t:W)!==E&&M(t),t=t||E,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(I&&!r){if(i=yt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&P(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&w.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(a)),n}if(w.qsa&&(!H||!H.test(e))){if(h=f=F,p=t,g=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(u=D(e),(f=t.getAttribute("id"))?h=f.replace(xt,"\\$&"):t.setAttribute("id",h),h="[id='"+h+"'] ",l=u.length;l--;)u[l]=h+d(u[l]);p=bt.test(e)&&c(t.parentNode)||t,g=u.join(",")}if(g)try{return Z.apply(n,p.querySelectorAll(g)),n}catch(m){}finally{f||t.removeAttribute("id")}}}return L(e.replace(lt,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>S.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[F]=!0,e}function i(e){var t=E.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)S.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||$)-(~e.sourceIndex||$);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&typeof e.getElementsByTagName!==G&&e}function f(){}function d(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function h(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=B++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,u=[z,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(l=t[F]||(t[F]={}),(s=l[r])&&s[0]===z&&s[1]===o)return u[2]=s[2];if(l[r]=u,u[2]=e(t,n,a))return!0}}}function p(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function g(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function m(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,u=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function v(e,t,n,i,o,a){return i&&!i[F]&&(i=v(i)),o&&!o[F]&&(o=v(o,a)),r(function(r,a,s,l){var u,c,f,d=[],h=[],p=a.length,v=r||g(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:m(v,d,e,s,l),b=n?o||(r?e:p||i)?[]:a:y;if(n&&n(y,b,s,l),i)for(u=m(b,h),i(u,[],s,l),c=u.length;c--;)(f=u[c])&&(b[h[c]]=!(y[h[c]]=f));if(r){if(o||e){if(o){for(u=[],c=b.length;c--;)(f=b[c])&&u.push(y[c]=f);o(null,b=[],u,l)}for(c=b.length;c--;)(f=b[c])&&(u=o?tt.call(r,f):d[c])>-1&&(r[u]=!(a[u]=f))}}else b=m(b===a?b.splice(p,b.length):b),o?o(null,a,b,l):Z.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=S.relative[e[0].type],a=o||S.relative[" "],s=o?1:0,l=h(function(e){return e===t},a,!0),u=h(function(e){return tt.call(t,e)>-1},a,!0),c=[function(e,n,r){return!o&&(r||n!==A)||((t=n).nodeType?l(e,n,r):u(e,n,r))}];i>s;s++)if(n=S.relative[e[s].type])c=[h(p(c),n)];else{if(n=S.filter[e[s].type].apply(null,e[s].matches),n[F]){for(r=++s;i>r&&!S.relative[e[r].type];r++);return v(s>1&&p(c),s>1&&d(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(lt,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&d(e))}c.push(n)}return p(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,l,u){var c,f,d,h=0,p="0",g=r&&[],v=[],y=A,b=r||o&&S.find.TAG("*",u),x=z+=null==y?1:Math.random()||.1,w=b.length;for(u&&(A=a!==E&&a);p!==w&&null!=(c=b[p]);p++){if(o&&c){for(f=0;d=e[f++];)if(d(c,a,s)){l.push(c);break}u&&(z=x)}i&&((c=!d&&c)&&h--,r&&g.push(c))}if(h+=p,i&&p!==h){for(f=0;d=n[f++];)d(g,v,a,s);if(r){if(h>0)for(;p--;)g[p]||v[p]||(v[p]=K.call(l));v=m(v)}Z.apply(l,v),u&&!r&&v.length>0&&h+n.length>1&&t.uniqueSort(l)}return u&&(z=x,A=y),g};return i?r(a):a}var x,w,S,C,T,D,k,L,A,N,_,M,E,j,I,H,O,R,P,F="sizzle"+-new Date,W=e.document,z=0,B=0,q=n(),U=n(),V=n(),X=function(e,t){return e===t&&(_=!0),0},G="undefined",$=1<<31,J={}.hasOwnProperty,Y=[],K=Y.pop,Q=Y.push,Z=Y.push,et=Y.slice,tt=Y.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},nt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",rt="[\\x20\\t\\r\\n\\f]",it="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=it.replace("w","w#"),at="\\["+rt+"*("+it+")(?:"+rt+"*([*^$|!~]?=)"+rt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+rt+"*\\]",st=":("+it+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+at+")*)|.*)\\)|)",lt=new RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=new RegExp("^"+rt+"*,"+rt+"*"),ct=new RegExp("^"+rt+"*([>+~]|"+rt+")"+rt+"*"),ft=new RegExp("="+rt+"*([^\\]'\"]*?)"+rt+"*\\]","g"),dt=new RegExp(st),ht=new RegExp("^"+ot+"$"),pt={ID:new RegExp("^#("+it+")"),CLASS:new RegExp("^\\.("+it+")"),TAG:new RegExp("^("+it.replace("w","w*")+")"),ATTR:new RegExp("^"+at),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),bool:new RegExp("^(?:"+nt+")$","i"),needsContext:new RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},gt=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,vt=/^[^{]+\{\s*\[native \w/,yt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,bt=/[+~]/,xt=/'|\\/g,wt=new RegExp("\\\\([\\da-f]{1,6}"+rt+"?|("+rt+")|.)","ig"),St=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{Z.apply(Y=et.call(W.childNodes),W.childNodes),Y[W.childNodes.length].nodeType}catch(Ct){Z={apply:Y.length?function(e,t){Q.apply(e,et.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},T=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},M=t.setDocument=function(e){var t,n=e?e.ownerDocument||e:W,r=n.defaultView;return n!==E&&9===n.nodeType&&n.documentElement?(E=n,j=n.documentElement,I=!T(n),r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){M()},!1):r.attachEvent&&r.attachEvent("onunload",function(){M()})),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=vt.test(n.getElementsByClassName)&&i(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),w.getById=i(function(e){return j.appendChild(e).id=F,!n.getElementsByName||!n.getElementsByName(F).length}),w.getById?(S.find.ID=function(e,t){if(typeof t.getElementById!==G&&I){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},S.filter.ID=function(e){var t=e.replace(wt,St);return function(e){return e.getAttribute("id")===t}}):(delete S.find.ID,S.filter.ID=function(e){var t=e.replace(wt,St);return function(e){var n=typeof e.getAttributeNode!==G&&e.getAttributeNode("id");return n&&n.value===t}}),S.find.TAG=w.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==G?t.getElementsByTagName(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},S.find.CLASS=w.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==G&&I?t.getElementsByClassName(e):void 0},O=[],H=[],(w.qsa=vt.test(n.querySelectorAll))&&(i(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&H.push("[*^$]="+rt+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||H.push("\\["+rt+"*(?:value|"+nt+")"),e.querySelectorAll(":checked").length||H.push(":checked")}),i(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&H.push("name"+rt+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||H.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),H.push(",.*:")})),(w.matchesSelector=vt.test(R=j.matches||j.webkitMatchesSelector||j.mozMatchesSelector||j.oMatchesSelector||j.msMatchesSelector))&&i(function(e){w.disconnectedMatch=R.call(e,"div"),R.call(e,"[s!='']:x"),O.push("!=",st)}),H=H.length&&new RegExp(H.join("|")),O=O.length&&new RegExp(O.join("|")),t=vt.test(j.compareDocumentPosition),P=t||vt.test(j.contains)?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)for(;t=t.parentNode;)if(t===e)return!0;return!1},X=t?function(e,t){if(e===t)return _=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&r||!w.sortDetached&&t.compareDocumentPosition(e)===r?e===n||e.ownerDocument===W&&P(W,e)?-1:t===n||t.ownerDocument===W&&P(W,t)?1:N?tt.call(N,e)-tt.call(N,t):0:4&r?-1:1)}:function(e,t){if(e===t)return _=!0,0;var r,i=0,o=e.parentNode,s=t.parentNode,l=[e],u=[t];if(!o||!s)return e===n?-1:t===n?1:o?-1:s?1:N?tt.call(N,e)-tt.call(N,t):0;if(o===s)return a(e,t);for(r=e;r=r.parentNode;)l.unshift(r);for(r=t;r=r.parentNode;)u.unshift(r);for(;l[i]===u[i];)i++;return i?a(l[i],u[i]):l[i]===W?-1:u[i]===W?1:0},n):E},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==E&&M(e),n=n.replace(ft,"='$1']"),!(!w.matchesSelector||!I||O&&O.test(n)||H&&H.test(n)))try{var r=R.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,E,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==E&&M(e),P(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==E&&M(e);var n=S.attrHandle[t.toLowerCase()],r=n&&J.call(S.attrHandle,t.toLowerCase())?n(e,t,!I):void 0;return void 0!==r?r:w.attributes||!I?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(_=!w.detectDuplicates,N=!w.sortStable&&e.slice(0),e.sort(X),_){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return N=null,e},C=t.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+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},S=t.selectors={cacheLength:50,createPseudo:r,match:pt,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(wt,St),e[3]=(e[3]||e[4]||e[5]||"").replace(wt,St),"~="===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]||t.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]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return pt.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&dt.test(n)&&(t=D(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(wt,St).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=q[e+" "];return t||(t=new RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&q(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==G&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!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,f,d,h,p,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s;if(m){if(o){for(;g;){for(f=t;f=f[g];)if(s?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;p=g="only"===e&&!p&&"nextSibling"}return!0}if(p=[a?m.firstChild:m.lastChild],a&&y){for(c=m[F]||(m[F]={}),u=c[e]||[],h=u[0]===z&&u[1],d=u[0]===z&&u[2],f=h&&m.childNodes[h];f=++h&&f&&f[g]||(d=h=0)||p.pop();)if(1===f.nodeType&&++d&&f===t){c[e]=[z,h,d];break}}else if(y&&(u=(t[F]||(t[F]={}))[e])&&u[0]===z)d=u[1];else for(;(f=++h&&f&&f[g]||(d=h=0)||p.pop())&&((s?f.nodeName.toLowerCase()!==v:1!==f.nodeType)||!++d||(y&&((f[F]||(f[F]={}))[e]=[z,d]),f!==t)););return d-=i,d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,n){var i,o=S.pseudos[e]||S.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[F]?o(n):o.length>1?(i=[e,e,"",n],S.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=tt.call(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(lt,"$1"));return i[F]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return ht.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(wt,St).toLowerCase(),function(t){var n;do if(n=I?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===j},focus:function(e){return e===E.activeElement&&(!E.hasFocus||E.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.nodeType<6)return!1;return!0},parent:function(e){return!S.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return gt.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"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},S.pseudos.nth=S.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})S.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})S.pseudos[x]=l(x);return f.prototype=S.filters=S.pseudos,S.setFilters=new f,D=t.tokenize=function(e,n){var r,i,o,a,s,l,u,c=U[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=S.preFilter;s;){(!r||(i=ut.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ct.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(lt," ")}),s=s.slice(r.length));for(a in S.filter)!(i=pt[a].exec(s))||u[a]&&!(i=u[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length));if(!r)break}return n?s.length:s?t.error(e):U(e,l).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=V[e+" "];if(!o){for(t||(t=D(e)),n=t.length;n--;)o=y(t[n]),o[F]?r.push(o):i.push(o);o=V(e,b(i,r)),o.selector=e}return o},L=t.select=function(e,t,n,r){var i,o,a,s,l,u="function"==typeof e&&e,f=!r&&D(e=u.selector||e);if(n=n||[],1===f.length){if(o=f[0]=f[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&I&&S.relative[o[1].type]){if(t=(S.find.ID(a.matches[0].replace(wt,St),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=pt.needsContext.test(e)?0:o.length;i--&&(a=o[i],!S.relative[s=a.type]);)if((l=S.find[s])&&(r=l(a.matches[0].replace(wt,St),bt.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&d(o),!e)return Z.apply(n,r),n;break}}return(u||k(e,f))(r,t,!I,n,bt.test(e)&&c(t.parentNode)||t),n},w.sortStable=F.split("").sort(X).join("")===F,w.detectDuplicates=!!_,M(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(E.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(nt,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(t);ot.find=ct,ot.expr=ct.selectors,ot.expr[":"]=ot.expr.pseudos,ot.unique=ct.uniqueSort,ot.text=ct.getText,ot.isXMLDoc=ct.isXML,ot.contains=ct.contains;var ft=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ht=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))},ot.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;i>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;i>t;t++)ot.find(e,r[t],n);return n=this.pushStack(i>1?ot.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(i(this,e||[],!1))},not:function(e){return this.pushStack(i(this,e||[],!0))},is:function(e){return!!i(this,"string"==typeof e&&ft.test(e)?ot(e):e||[],!1).length}});var pt,gt=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,vt=ot.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||pt).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof ot?t[0]:t,ot.merge(this,ot.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:gt,!0)),dt.test(n[1])&&ot.isPlainObject(t))for(n in t)ot.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}if(r=gt.getElementById(n[2]),r&&r.parentNode){if(r.id!==n[2])return pt.find(e);this.length=1,this[0]=r}return this.context=gt,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ot.isFunction(e)?"undefined"!=typeof pt.ready?pt.ready(e):e(ot):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ot.makeArray(e,this))};vt.prototype=ot.fn,pt=ot(gt);var yt=/^(?:parents|prev(?:Until|All))/,bt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!ot(i).is(n));)1===i.nodeType&&r.push(i),i=i[t];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),ot.fn.extend({has:function(e){var t,n=ot(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=ft.test(e)||"string"!=typeof e?ot(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&ot.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,n){return ot.dir(e,"parentNode",n)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,n){return ot.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return ot.dir(e,"previousSibling",n)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(n,r){var i=ot.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=ot.filter(r,i)),this.length>1&&(bt[e]||(i=ot.unique(i)),yt.test(e)&&(i=i.reverse())),this.pushStack(i)}});var xt=/\S+/g,wt={};ot.Callbacks=function(e){e="string"==typeof e?wt[e]||a(e):ot.extend({},e);var t,n,r,i,o,s,l=[],u=!e.once&&[],c=function(a){for(n=e.memory&&a,r=!0,o=s||0,s=0,i=l.length,t=!0;l&&i>o;o++)if(l[o].apply(a[0],a[1])===!1&&e.stopOnFalse){n=!1;break}t=!1,l&&(u?u.length&&c(u.shift()):n?l=[]:f.disable())},f={add:function(){if(l){var r=l.length;!function o(t){ot.each(t,function(t,n){var r=ot.type(n);"function"===r?e.unique&&f.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})}(arguments),t?i=l.length:n&&(s=r,c(n))}return this},remove:function(){return l&&ot.each(arguments,function(e,n){for(var r;(r=ot.inArray(n,l,r))>-1;)l.splice(r,1),t&&(i>=r&&i--,o>=r&&o--)}),this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],i=0,this},disable:function(){return l=u=n=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,n||f.disable(),this},locked:function(){return!u},fireWith:function(e,n){return!l||r&&!u||(n=n||[],n=[e,n.slice?n.slice():n],t?u.push(n):c(n)),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!r}};return f},ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ot.Deferred(function(n){ot.each(t,function(t,o){var a=ot.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},i={};return r.pipe=r.then,ot.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,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&ot.isFunction(e.promise)?a:0,l=1===s?e:ot.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&ot.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--s;return s||l.resolveWith(r,o),l.promise()}});var St;ot.fn.ready=function(e){return ot.ready.promise().done(e),this},ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!gt.body)return setTimeout(ot.ready);ot.isReady=!0,e!==!0&&--ot.readyWait>0||(St.resolveWith(gt,[ot]),ot.fn.triggerHandler&&(ot(gt).triggerHandler("ready"),ot(gt).off("ready")))}}}),ot.ready.promise=function(e){if(!St)if(St=ot.Deferred(),"complete"===gt.readyState)setTimeout(ot.ready);else if(gt.addEventListener)gt.addEventListener("DOMContentLoaded",l,!1),t.addEventListener("load",l,!1);else{gt.attachEvent("onreadystatechange",l),t.attachEvent("onload",l);var n=!1;try{n=null==t.frameElement&&gt.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!ot.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}s(),ot.ready()}}()}return St.promise(e)};var Ct,Tt="undefined";for(Ct in ot(rt))break;rt.ownLast="0"!==Ct,rt.inlineBlockNeedsLayout=!1,ot(function(){var e,t,n,r;n=gt.getElementsByTagName("body")[0],n&&n.style&&(t=gt.createElement("div"),r=gt.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Tt&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",rt.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=gt.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null}(),ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Dt=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,kt=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando],!!e&&!c(e)},data:function(e,t,n){return f(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return f(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),ot.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=ot.data(o),1===o.nodeType&&!ot._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=ot.camelCase(r.slice(5)),u(o,r,i[r])));ot._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}}),ot.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=ot._data(e,t),n&&(!r||ot.isArray(n)?r=ot._data(e,t,ot.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=ot.queue(e,t),r=n.length,i=n.shift(),o=ot._queueHooks(e,t),a=function(){ot.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 ot._data(e,n)||ot._data(e,n,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue"),ot._removeData(e,n)})})}}),ot.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?ot.queue(this[0],e):void 0===t?this:this.each(function(){var n=ot.queue(this,e,t);ot._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=ot.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=ot._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var Lt=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,At=["Top","Right","Bottom","Left"],Nt=function(e,t){return e=t||e,"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},_t=ot.access=function(e,t,n,r,i,o,a){var s=0,l=e.length,u=null==n;if("object"===ot.type(n)){i=!0;for(s in n)ot.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,ot.isFunction(r)||(a=!0),u&&(a?(t.call(e,r),t=null):(u=t,t=function(e,t,n){return u.call(ot(e),n) })),t))for(;l>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:u?t.call(e):l?t(e[0],n):o},Mt=/^(?:checkbox|radio)$/i;!function(){var e=gt.createElement("input"),t=gt.createElement("div"),n=gt.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",rt.leadingWhitespace=3===t.firstChild.nodeType,rt.tbody=!t.getElementsByTagName("tbody").length,rt.htmlSerialize=!!t.getElementsByTagName("link").length,rt.html5Clone="<:nav></:nav>"!==gt.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,n.appendChild(e),rt.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,n.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,rt.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){rt.noCloneEvent=!1}),t.cloneNode(!0).click()),null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}}(),function(){var e,n,r=gt.createElement("div");for(e in{submit:!0,change:!0,focusin:!0})n="on"+e,(rt[e+"Bubbles"]=n in t)||(r.setAttribute(n,"t"),rt[e+"Bubbles"]=r.attributes[n].expando===!1);r=null}();var Et=/^(?:input|select|textarea)$/i,jt=/^key/,It=/^(?:mouse|pointer|contextmenu)|click/,Ht=/^(?:focusinfocus|focusoutblur)$/,Ot=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,n,r,i){var o,a,s,l,u,c,f,d,h,p,g,m=ot._data(e);if(m){for(n.handler&&(l=n,n=l.handler,i=l.selector),n.guid||(n.guid=ot.guid++),(a=m.events)||(a=m.events={}),(c=m.handle)||(c=m.handle=function(e){return typeof ot===Tt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(xt)||[""],s=t.length;s--;)o=Ot.exec(t[s])||[],h=g=o[1],p=(o[2]||"").split(".").sort(),h&&(u=ot.event.special[h]||{},h=(i?u.delegateType:u.bindType)||h,u=ot.event.special[h]||{},f=ot.extend({type:h,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&ot.expr.match.needsContext.test(i),namespace:p.join(".")},l),(d=a[h])||(d=a[h]=[],d.delegateCount=0,u.setup&&u.setup.call(e,r,p,c)!==!1||(e.addEventListener?e.addEventListener(h,c,!1):e.attachEvent&&e.attachEvent("on"+h,c))),u.add&&(u.add.call(e,f),f.handler.guid||(f.handler.guid=n.guid)),i?d.splice(d.delegateCount++,0,f):d.push(f),ot.event.global[h]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,f,d,h,p,g,m=ot.hasData(e)&&ot._data(e);if(m&&(c=m.events)){for(t=(t||"").match(xt)||[""],u=t.length;u--;)if(s=Ot.exec(t[u])||[],h=g=s[1],p=(s[2]||"").split(".").sort(),h){for(f=ot.event.special[h]||{},h=(r?f.delegateType:f.bindType)||h,d=c[h]||[],s=s[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=d.length;o--;)a=d[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(d.splice(o,1),a.selector&&d.delegateCount--,f.remove&&f.remove.call(e,a));l&&!d.length&&(f.teardown&&f.teardown.call(e,p,m.handle)!==!1||ot.removeEvent(e,h,m.handle),delete c[h])}else for(h in c)ot.event.remove(e,h+t[u],n,r,!0);ot.isEmptyObject(c)&&(delete m.handle,ot._removeData(e,"events"))}},trigger:function(e,n,r,i){var o,a,s,l,u,c,f,d=[r||gt],h=nt.call(e,"type")?e.type:e,p=nt.call(e,"namespace")?e.namespace.split("."):[];if(s=c=r=r||gt,3!==r.nodeType&&8!==r.nodeType&&!Ht.test(h+ot.event.triggered)&&(h.indexOf(".")>=0&&(p=h.split("."),h=p.shift(),p.sort()),a=h.indexOf(":")<0&&"on"+h,e=e[ot.expando]?e:new ot.Event(h,"object"==typeof e&&e),e.isTrigger=i?2:3,e.namespace=p.join("."),e.namespace_re=e.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=r),n=null==n?[e]:ot.makeArray(n,[e]),u=ot.event.special[h]||{},i||!u.trigger||u.trigger.apply(r,n)!==!1)){if(!i&&!u.noBubble&&!ot.isWindow(r)){for(l=u.delegateType||h,Ht.test(l+h)||(s=s.parentNode);s;s=s.parentNode)d.push(s),c=s;c===(r.ownerDocument||gt)&&d.push(c.defaultView||c.parentWindow||t)}for(f=0;(s=d[f++])&&!e.isPropagationStopped();)e.type=f>1?l:u.bindType||h,o=(ot._data(s,"events")||{})[e.type]&&ot._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&ot.acceptData(s)&&(e.result=o.apply(s,n),e.result===!1&&e.preventDefault());if(e.type=h,!i&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),n)===!1)&&ot.acceptData(r)&&a&&r[h]&&!ot.isWindow(r)){c=r[a],c&&(r[a]=null),ot.event.triggered=h;try{r[h]()}catch(g){}ot.event.triggered=void 0,c&&(r[a]=c)}return e.result}},dispatch:function(e){e=ot.event.fix(e);var t,n,r,i,o,a=[],s=Y.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(a=ot.event.handlers.call(this,e,l),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,o=0;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,n=((ot.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s),void 0!==n&&(e.result=n)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(i=[],o=0;s>o;o++)r=t[o],n=r.selector+" ",void 0===i[n]&&(i[n]=r.needsContext?ot(n,this).index(l)>=0:ot.find(n,this,null,[l]).length),i[n]&&i.push(r);i.length&&a.push({elem:l,handlers:i})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[ot.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=It.test(i)?this.mouseHooks:jt.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new ot.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||gt),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.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,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||gt,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==g()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===g()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=ot.extend(new ot.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(i,null,t):ot.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},ot.removeEvent=gt.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]===Tt&&(e[r]=null),e.detachEvent(r,n))},ot.Event=function(e,t){return this instanceof ot.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?h:p):this.type=e,t&&ot.extend(this,t),this.timeStamp=e&&e.timeStamp||ot.now(),void(this[ot.expando]=!0)):new ot.Event(e,t)},ot.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=h,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=h,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=h,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!ot.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),rt.submitBubbles||(ot.event.special.submit={setup:function(){return ot.nodeName(this,"form")?!1:void ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;n&&!ot._data(n,"submitBubbles")&&(ot.event.add(n,"submit._submit",function(e){e._submit_bubble=!0}),ot._data(n,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return ot.nodeName(this,"form")?!1:void ot.event.remove(this,"._submit")}}),rt.changeBubbles||(ot.event.special.change={setup:function(){return Et.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),ot.event.simulate("change",this,e,!0)})),!1):void ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;Et.test(t.nodeName)&&!ot._data(t,"changeBubbles")&&(ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)}),ot._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return ot.event.remove(this,"._change"),!Et.test(this.nodeName)}}),rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=ot._data(r,t);i||r.addEventListener(e,n,!0),ot._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=ot._data(r,t)-1;i?ot._data(r,t,i):(r.removeEventListener(e,n,!0),ot._removeData(r,t))}}}),ot.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(a=r,r=function(e){return ot().off(e),a.apply(this,arguments)},r.guid=a.guid||(a.guid=ot.guid++)),this.each(function(){ot.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){ot.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?ot.event.trigger(e,t,n,!0):void 0}});var Rt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Pt=/ jQuery\d+="(?:null|\d+)"/g,Ft=new RegExp("<(?:"+Rt+")[\\s/>]","i"),Wt=/^\s+/,zt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Bt=/<([\w:]+)/,qt=/<tbody/i,Ut=/<|&#?\w+;/,Vt=/<(?:script|style|link)/i,Xt=/checked\s*(?:[^=]|=\s*.checked.)/i,Gt=/^$|\/(?:java|ecma)script/i,$t=/^true\/(.*)/,Jt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Yt={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:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Kt=m(gt),Qt=Kt.appendChild(gt.createElement("div"));Yt.optgroup=Yt.option,Yt.tbody=Yt.tfoot=Yt.colgroup=Yt.caption=Yt.thead,Yt.th=Yt.td,ot.extend({clone:function(e,t,n){var r,i,o,a,s,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ft.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Qt.innerHTML=e.outerHTML,Qt.removeChild(o=Qt.firstChild)),!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e)))for(r=v(o),s=v(e),a=0;null!=(i=s[a]);++a)r[a]&&T(i,r[a]);if(t)if(n)for(s=s||v(e),r=r||v(o),a=0;null!=(i=s[a]);a++)C(i,r[a]);else C(e,o);return r=v(o,"script"),r.length>0&&S(r,!l&&v(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,l,u,c,f=e.length,d=m(t),h=[],p=0;f>p;p++)if(o=e[p],o||0===o)if("object"===ot.type(o))ot.merge(h,o.nodeType?[o]:o);else if(Ut.test(o)){for(s=s||d.appendChild(t.createElement("div")),l=(Bt.exec(o)||["",""])[1].toLowerCase(),c=Yt[l]||Yt._default,s.innerHTML=c[1]+o.replace(zt,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!rt.leadingWhitespace&&Wt.test(o)&&h.push(t.createTextNode(Wt.exec(o)[0])),!rt.tbody)for(o="table"!==l||qt.test(o)?"<table>"!==c[1]||qt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)ot.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(ot.merge(h,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=d.lastChild}else h.push(t.createTextNode(o));for(s&&d.removeChild(s),rt.appendChecked||ot.grep(v(h,"input"),y),p=0;o=h[p++];)if((!r||-1===ot.inArray(o,r))&&(a=ot.contains(o.ownerDocument,o),s=v(d.appendChild(o),"script"),a&&S(s),n))for(i=0;o=s[i++];)Gt.test(o.type||"")&&n.push(o);return s=null,d},cleanData:function(e,t){for(var n,r,i,o,a=0,s=ot.expando,l=ot.cache,u=rt.deleteExpando,c=ot.event.special;null!=(n=e[a]);a++)if((t||ot.acceptData(n))&&(i=n[s],o=i&&l[i])){if(o.events)for(r in o.events)c[r]?ot.event.remove(n,r):ot.removeEvent(n,r,o.handle);l[i]&&(delete l[i],u?delete n[s]:typeof n.removeAttribute!==Tt?n.removeAttribute(s):n[s]=null,J.push(i))}}}),ot.fn.extend({text:function(e){return _t(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||gt).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=b(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=b(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){for(var n,r=e?ot.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||ot.cleanData(v(n)),n.parentNode&&(t&&ot.contains(n.ownerDocument,n)&&S(v(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&ot.cleanData(v(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.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 ot.clone(this,e,t)})},html:function(e){return _t(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Pt,""):void 0;if(!("string"!=typeof e||Vt.test(e)||!rt.htmlSerialize&&Ft.test(e)||!rt.leadingWhitespace&&Wt.test(e)||Yt[(Bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(zt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(ot.cleanData(v(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,ot.cleanData(v(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=K.apply([],e);var n,r,i,o,a,s,l=0,u=this.length,c=this,f=u-1,d=e[0],h=ot.isFunction(d);if(h||u>1&&"string"==typeof d&&!rt.checkClone&&Xt.test(d))return this.each(function(n){var r=c.eq(n);h&&(e[0]=d.call(this,n,r.html())),r.domManip(e,t)});if(u&&(s=ot.buildFragment(e,this[0].ownerDocument,!1,this),n=s.firstChild,1===s.childNodes.length&&(s=n),n)){for(o=ot.map(v(s,"script"),x),i=o.length;u>l;l++)r=s,l!==f&&(r=ot.clone(r,!0,!0),i&&ot.merge(o,v(r,"script"))),t.call(this[l],r,l);if(i)for(a=o[o.length-1].ownerDocument,ot.map(o,w),l=0;i>l;l++)r=o[l],Gt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(a,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Jt,"")));s=n=null}return this}}),ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var n,r=0,i=[],o=ot(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),ot(o[r])[t](n),Q.apply(i,n.get());return this.pushStack(i)}});var Zt,en={};!function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=gt.getElementsByTagName("body")[0],n&&n.style?(t=gt.createElement("div"),r=gt.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Tt&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(gt.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var tn,nn,rn=/^margin/,on=new RegExp("^("+Lt+")(?!px)[a-z%]+$","i"),an=/^(top|right|bottom|left)$/;t.getComputedStyle?(tn=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},nn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||tn(e),a=n?n.getPropertyValue(t)||n[t]:void 0,n&&(""!==a||ot.contains(e.ownerDocument,e)||(a=ot.style(e,t)),on.test(a)&&rn.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0===a?a:a+""}):gt.documentElement.currentStyle&&(tn=function(e){return e.currentStyle},nn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||tn(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),on.test(a)&&!an.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"}),function(){function e(){var e,n,r,i;n=gt.getElementsByTagName("body")[0],n&&n.style&&(e=gt.createElement("div"),r=gt.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(e),e.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=a=!1,l=!0,t.getComputedStyle&&(o="1%"!==(t.getComputedStyle(e,null)||{}).top,a="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width,i=e.appendChild(gt.createElement("div")),i.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",e.style.width="1px",l=!parseFloat((t.getComputedStyle(i,null)||{}).marginRight)),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=e.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",s=0===i[0].offsetHeight,s&&(i[0].style.display="",i[1].style.display="none",s=0===i[0].offsetHeight),n.removeChild(r))}var n,r,i,o,a,s,l;n=gt.createElement("div"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=n.getElementsByTagName("a")[0],r=i&&i.style,r&&(r.cssText="float:left;opacity:.5",rt.opacity="0.5"===r.opacity,rt.cssFloat=!!r.cssFloat,n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",rt.clearCloneStyle="content-box"===n.style.backgroundClip,rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,ot.extend(rt,{reliableHiddenOffsets:function(){return null==s&&e(),s},boxSizingReliable:function(){return null==a&&e(),a},pixelPosition:function(){return null==o&&e(),o},reliableMarginRight:function(){return null==l&&e(),l}}))}(),ot.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};var sn=/alpha\([^)]*\)/i,ln=/opacity\s*=\s*([^)]*)/,un=/^(none|table(?!-c[ea]).+)/,cn=new RegExp("^("+Lt+")(.*)$","i"),fn=new RegExp("^([+-])=("+Lt+")","i"),dn={position:"absolute",visibility:"hidden",display:"block"},hn={letterSpacing:"0",fontWeight:"400"},pn=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=nn(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=ot.camelCase(t),l=e.style;if(t=ot.cssProps[s]||(ot.cssProps[s]=A(l,s)),a=ot.cssHooks[t]||ot.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];if(o=typeof n,"string"===o&&(i=fn.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(ot.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||ot.cssNumber[s]||(n+="px"),rt.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{l[t]=n}catch(u){}}},css:function(e,t,n,r){var i,o,a,s=ot.camelCase(t);return t=ot.cssProps[s]||(ot.cssProps[s]=A(e.style,s)),a=ot.cssHooks[t]||ot.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=nn(e,t,r)),"normal"===o&&t in hn&&(o=hn[t]),""===n||n?(i=parseFloat(o),n===!0||ot.isNumeric(i)?i||0:o):o}}),ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,n,r){return n?un.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,dn,function(){return E(e,t,r)}):E(e,t,r):void 0},set:function(e,n,r){var i=r&&tn(e);return _(e,n,r?M(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,i),i):0)}}}),rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ln.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=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===ot.trim(o.replace(sn,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=sn.test(o)?o.replace(sn,i):o+" "+i)}}),ot.cssHooks.marginRight=L(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},nn,[e,"marginRight"]):void 0}),ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+At[r]+t]=o[r]||o[r-2]||o[0];return i}},rn.test(e)||(ot.cssHooks[e+t].set=_)}),ot.fn.extend({css:function(e,t){return _t(this,function(e,t,n){var r,i,o={},a=0;if(ot.isArray(t)){for(r=tn(e),i=t.length;i>a;a++)o[t[a]]=ot.css(e,t[a],!1,r);return o}return void 0!==n?ot.style(e,t,n):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return N(this,!0)},hide:function(){return N(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Nt(this)?ot(this).show():ot(this).hide()})}}),ot.Tween=j,j.prototype={constructor:j,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||(ot.cssNumber[n]?"":"px")},cur:function(){var e=j.propHooks[this.prop];return e&&e.get?e.get(this):j.propHooks._default.get(this)},run:function(e){var t,n=j.propHooks[this.prop];return this.pos=t=this.options.duration?ot.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):j.propHooks._default.set(this),this}},j.prototype.init.prototype=j.prototype,j.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=ot.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},j.propHooks.scrollTop=j.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},ot.fx=j.prototype.init,ot.fx.step={};var gn,mn,vn=/^(?:toggle|show|hide)$/,yn=new RegExp("^(?:([+-])=|)("+Lt+")([a-z%]*)$","i"),bn=/queueHooks$/,xn=[R],wn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=yn.exec(t),o=i&&i[3]||(ot.cssNumber[e]?"":"px"),a=(ot.cssNumber[e]||"px"!==o&&+r)&&yn.exec(ot.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,ot.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}]};ot.Animation=ot.extend(F,{tweener:function(e,t){ot.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],wn[n]=wn[n]||[],wn[n].unshift(t)},prefilter:function(e,t){t?xn.unshift(e):xn.push(e)}}),ot.speed=function(e,t,n){var r=e&&"object"==typeof e?ot.extend({},e):{complete:n||!n&&t||ot.isFunction(e)&&e,duration:e,easing:n&&t||t&&!ot.isFunction(t)&&t};return r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){ot.isFunction(r.old)&&r.old.call(this),r.queue&&ot.dequeue(this,r.queue)},r},ot.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Nt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=ot.isEmptyObject(e),o=ot.speed(t,n,r),a=function(){var t=F(this,ot.extend({},e),o);(i||ot._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,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=ot.timers,a=ot._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&bn.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&ot.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=ot._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=ot.timers,a=r?r.length:0;for(n.finish=!0,ot.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})}}),ot.each(["toggle","show","hide"],function(e,t){var n=ot.fn[t];ot.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(H(t,!0),e,r,i)}}),ot.each({slideDown:H("show"),slideUp:H("hide"),slideToggle:H("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),ot.timers=[],ot.fx.tick=function(){var e,t=ot.timers,n=0;for(gn=ot.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||ot.fx.stop(),gn=void 0},ot.fx.timer=function(e){ot.timers.push(e),e()?ot.fx.start():ot.timers.pop()},ot.fx.interval=13,ot.fx.start=function(){mn||(mn=setInterval(ot.fx.tick,ot.fx.interval))},ot.fx.stop=function(){clearInterval(mn),mn=null},ot.fx.speeds={slow:600,fast:200,_default:400},ot.fn.delay=function(e,t){return e=ot.fx?ot.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e,t,n,r,i;t=gt.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],n=gt.createElement("select"),i=n.appendChild(gt.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",rt.getSetAttribute="t"!==t.className,rt.style=/top/.test(r.getAttribute("style")),rt.hrefNormalized="/a"===r.getAttribute("href"),rt.checkOn=!!e.value,rt.optSelected=i.selected,rt.enctype=!!gt.createElement("form").enctype,n.disabled=!0,rt.optDisabled=!i.disabled,e=gt.createElement("input"),e.setAttribute("value",""),rt.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),rt.radioValue="t"===e.value}();var Sn=/\r/g;ot.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=ot.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,ot(this).val()):e,null==i?i="":"number"==typeof i?i+="":ot.isArray(i)&&(i=ot.map(i,function(e){return null==e?"":e+""})),t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=ot.valHooks[i.type]||ot.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(Sn,""):null==n?"":n)}}}),ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(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;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(rt.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&ot.nodeName(n.parentNode,"optgroup"))){if(t=ot(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=ot.makeArray(t),a=i.length;a--;)if(r=i[a],ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}},rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Cn,Tn,Dn=ot.expr.attrHandle,kn=/^(?:checked|selected)$/i,Ln=rt.getSetAttribute,An=rt.input;ot.fn.extend({attr:function(e,t){return _t(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e) })}}),ot.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Tt?ot.prop(e,t,n):(1===o&&ot.isXMLDoc(e)||(t=t.toLowerCase(),r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Tn:Cn)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=ot.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void ot.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(xt);if(o&&1===e.nodeType)for(;n=o[i++];)r=ot.propFix[n]||n,ot.expr.match.bool.test(n)?An&&Ln||!kn.test(n)?e[r]=!1:e[ot.camelCase("default-"+n)]=e[r]=!1:ot.attr(e,n,""),e.removeAttribute(Ln?n:r)},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),Tn={set:function(e,t,n){return t===!1?ot.removeAttr(e,n):An&&Ln||!kn.test(n)?e.setAttribute(!Ln&&ot.propFix[n]||n,n):e[ot.camelCase("default-"+n)]=e[n]=!0,n}},ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Dn[t]||ot.find.attr;Dn[t]=An&&Ln||!kn.test(t)?function(e,t,r){var i,o;return r||(o=Dn[t],Dn[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,Dn[t]=o),i}:function(e,t,n){return n?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}}),An&&Ln||(ot.attrHooks.value={set:function(e,t,n){return ot.nodeName(e,"input")?void(e.defaultValue=t):Cn&&Cn.set(e,t,n)}}),Ln||(Cn={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Dn.id=Dn.name=Dn.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},ot.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Cn.set},ot.attrHooks.contenteditable={set:function(e,t,n){Cn.set(e,""===t?!1:t,n)}},ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Nn=/^(?:input|select|textarea|button|object)$/i,_n=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return _t(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){return e=ot.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!ot.isXMLDoc(e),o&&(t=ot.propFix[t]||t,i=ot.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Nn.test(e.nodeName)||_n.test(e.nodeName)&&e.href?0:-1}}}}),rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this}),rt.enctype||(ot.propFix.enctype="encoding");var Mn=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(xt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Mn," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=ot.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(xt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Mn," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?ot.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(n){ot(this).toggleClass(e.call(this,n,this.className,t),t)}:function(){if("string"===n)for(var t,r=0,i=ot(this),o=e.match(xt)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Tt||"boolean"===n)&&(this.className&&ot._data(this,"__className__",this.className),this.className=this.className||e===!1?"":ot._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(Mn," ").indexOf(t)>=0)return!0;return!1}}),ot.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){ot.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),ot.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 En=ot.now(),jn=/\?/,In=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var n,r=null,i=ot.trim(e+"");return i&&!ot.trim(i.replace(In,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():ot.error("Invalid JSON: "+e)},ot.parseXML=function(e){var n,r;if(!e||"string"!=typeof e)return null;try{t.DOMParser?(r=new DOMParser,n=r.parseFromString(e,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(e))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e),n};var Hn,On,Rn=/#.*$/,Pn=/([?&])_=[^&]*/,Fn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Wn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,zn=/^(?:GET|HEAD)$/,Bn=/^\/\//,qn=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Un={},Vn={},Xn="*/".concat("*");try{On=location.href}catch(Gn){On=gt.createElement("a"),On.href="",On=On.href}Hn=qn.exec(On.toLowerCase())||[],ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:On,type:"GET",isLocal:Wn.test(Hn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Xn,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":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?B(B(e,ot.ajaxSettings),t):B(ot.ajaxSettings,e)},ajaxPrefilter:W(Un),ajaxTransport:W(Vn),ajax:function(e,t){function n(e,t,n,r){var i,c,v,y,x,S=t;2!==b&&(b=2,s&&clearTimeout(s),u=void 0,a=r||"",w.readyState=e>0?4:0,i=e>=200&&300>e||304===e,n&&(y=q(f,w,n)),y=U(f,y,w,i),i?(f.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(ot.lastModified[o]=x),x=w.getResponseHeader("etag"),x&&(ot.etag[o]=x)),204===e||"HEAD"===f.type?S="nocontent":304===e?S="notmodified":(S=y.state,c=y.data,v=y.error,i=!v)):(v=S,(e||!S)&&(S="error",0>e&&(e=0))),w.status=e,w.statusText=(t||S)+"",i?p.resolveWith(d,[c,S,w]):p.rejectWith(d,[w,S,v]),w.statusCode(m),m=void 0,l&&h.trigger(i?"ajaxSuccess":"ajaxError",[w,f,i?c:v]),g.fireWith(d,[w,S]),l&&(h.trigger("ajaxComplete",[w,f]),--ot.active||ot.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,l,u,c,f=ot.ajaxSetup({},t),d=f.context||f,h=f.context&&(d.nodeType||d.jquery)?ot(d):ot.event,p=ot.Deferred(),g=ot.Callbacks("once memory"),m=f.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c)for(c={};t=Fn.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=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return b||(f.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||x;return u&&u.abort(t),n(0,t),this}};if(p.promise(w).complete=g.add,w.success=w.done,w.error=w.fail,f.url=((e||f.url||On)+"").replace(Rn,"").replace(Bn,Hn[1]+"//"),f.type=t.method||t.type||f.method||f.type,f.dataTypes=ot.trim(f.dataType||"*").toLowerCase().match(xt)||[""],null==f.crossDomain&&(r=qn.exec(f.url.toLowerCase()),f.crossDomain=!(!r||r[1]===Hn[1]&&r[2]===Hn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(Hn[3]||("http:"===Hn[1]?"80":"443")))),f.data&&f.processData&&"string"!=typeof f.data&&(f.data=ot.param(f.data,f.traditional)),z(Un,f,t,w),2===b)return w;l=f.global,l&&0===ot.active++&&ot.event.trigger("ajaxStart"),f.type=f.type.toUpperCase(),f.hasContent=!zn.test(f.type),o=f.url,f.hasContent||(f.data&&(o=f.url+=(jn.test(o)?"&":"?")+f.data,delete f.data),f.cache===!1&&(f.url=Pn.test(o)?o.replace(Pn,"$1_="+En++):o+(jn.test(o)?"&":"?")+"_="+En++)),f.ifModified&&(ot.lastModified[o]&&w.setRequestHeader("If-Modified-Since",ot.lastModified[o]),ot.etag[o]&&w.setRequestHeader("If-None-Match",ot.etag[o])),(f.data&&f.hasContent&&f.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",f.contentType),w.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Xn+"; q=0.01":""):f.accepts["*"]);for(i in f.headers)w.setRequestHeader(i,f.headers[i]);if(f.beforeSend&&(f.beforeSend.call(d,w,f)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](f[i]);if(u=z(Vn,f,t,w)){w.readyState=1,l&&h.trigger("ajaxSend",[w,f]),f.async&&f.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},f.timeout));try{b=1,u.send(v,n)}catch(S){if(!(2>b))throw S;n(-1,S)}}else n(-1,"No Transport");return w},getJSON:function(e,t,n){return ot.get(e,t,n,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}}),ot.each(["get","post"],function(e,t){ot[t]=function(e,n,r,i){return ot.isFunction(n)&&(i=i||r,r=n,n=void 0),ot.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}}),ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(n){ot(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}}),ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))},ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var $n=/%20/g,Jn=/\[\]$/,Yn=/\r?\n/g,Kn=/^(?:submit|button|image|reset|file)$/i,Qn=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var n,r=[],i=function(e,t){t=ot.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional),ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){i(this.name,this.value)});else for(n in e)V(n,e[n],t,i);return r.join("&").replace($n,"+")},ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qn.test(this.nodeName)&&!Kn.test(e)&&(this.checked||!Mt.test(e))}).map(function(e,t){var n=ot(this).val();return null==n?null:ot.isArray(n)?ot.map(n,function(e){return{name:t.name,value:e.replace(Yn,"\r\n")}}):{name:t.name,value:n.replace(Yn,"\r\n")}}).get()}}),ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||G()}:X;var Zn=0,er={},tr=ot.ajaxSettings.xhr();t.ActiveXObject&&ot(t).on("unload",function(){for(var e in er)er[e](void 0,!0)}),rt.cors=!!tr&&"withCredentials"in tr,tr=rt.ajax=!!tr,tr&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(n,r){var i,o=e.xhr(),a=++Zn;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null),t=function(n,i){var s,l,u;if(t&&(i||4===o.readyState))if(delete er[a],t=void 0,o.onreadystatechange=ot.noop,i)4!==o.readyState&&o.abort();else{u={},s=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(c){l=""}s||!e.isLocal||e.crossDomain?1223===s&&(s=204):s=u.text?200:404}u&&r(s,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=er[a]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return ot.globalEval(e),e}}}),ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=gt.head||ot("head")[0]||gt.documentElement;return{send:function(r,i){t=gt.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var nr=[],rr=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=nr.pop()||ot.expando+"_"+En++;return this[e]=!0,e}}),ot.ajaxPrefilter("json jsonp",function(e,n,r){var i,o,a,s=e.jsonp!==!1&&(rr.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&rr.test(e.data)&&"data");return s||"jsonp"===e.dataTypes[0]?(i=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,s?e[s]=e[s].replace(rr,"$1"+i):e.jsonp!==!1&&(e.url+=(jn.test(e.url)?"&":"?")+e.jsonp+"="+i),e.converters["script json"]=function(){return a||ot.error(i+" was not called"),a[0]},e.dataTypes[0]="json",o=t[i],t[i]=function(){a=arguments},r.always(function(){t[i]=o,e[i]&&(e.jsonpCallback=n.jsonpCallback,nr.push(i)),a&&ot.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),ot.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||gt;var r=dt.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=ot.buildFragment([e],t,i),i&&i.length&&ot(i).remove(),ot.merge([],r.childNodes))};var ir=ot.fn.load;ot.fn.load=function(e,t,n){if("string"!=typeof e&&ir)return ir.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=ot.trim(e.slice(s,e.length)),e=e.slice(0,s)),ot.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),a.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments,a.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var or=t.document.documentElement;ot.offset={setOffset:function(e,t,n){var r,i,o,a,s,l,u,c=ot.css(e,"position"),f=ot(e),d={};"static"===c&&(e.style.position="relative"),s=f.offset(),o=ot.css(e,"top"),l=ot.css(e,"left"),u=("absolute"===c||"fixed"===c)&&ot.inArray("auto",[o,l])>-1,u?(r=f.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(l)||0),ot.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(d.top=t.top-s.top+a),null!=t.left&&(d.left=t.left-s.left+i),"using"in t?t.using.call(e,d):f.css(d)}},ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o)return t=o.documentElement,ot.contains(t,i)?(typeof i.getBoundingClientRect!==Tt&&(r=i.getBoundingClientRect()),n=$(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===ot.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ot.nodeName(e[0],"html")||(n=e.offset()),n.top+=ot.css(e[0],"borderTopWidth",!0),n.left+=ot.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-ot.css(r,"marginTop",!0),left:t.left-n.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||or;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||or})}}),ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);ot.fn[e]=function(r){return _t(this,function(e,r,i){var o=$(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?ot(o).scrollLeft():i,n?i:ot(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),ot.each(["top","left"],function(e,t){ot.cssHooks[t]=L(rt.pixelPosition,function(e,n){return n?(n=nn(e,t),on.test(n)?ot(e).position()[t]+"px":n):void 0})}),ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){ot.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return _t(this,function(t,n,r){var i;return ot.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?ot.css(t,n,a):ot.style(t,n,r,a)},t,o?r:void 0,o,null)}})}),ot.fn.size=function(){return this.length},ot.fn.andSelf=ot.fn.addBack,"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var ar=t.jQuery,sr=t.$;return ot.noConflict=function(e){return t.$===ot&&(t.$=sr),e&&t.jQuery===ot&&(t.jQuery=ar),ot},typeof n===Tt&&(t.jQuery=t.$=ot),ot})},{}],9:[function(t,n){!function(t){function r(){try{return u in t&&t[u]}catch(e){return!1}}function i(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(a),f.appendChild(a),a.addBehavior("#default#userData"),a.load(u);var n=e.apply(s,t);return f.removeChild(a),n}}function o(e){return e.replace(/^d/,"___$&").replace(p,"___")}var a,s={},l=t.document,u="localStorage",c="script";if(s.disabled=!1,s.set=function(){},s.get=function(){},s.remove=function(){},s.clear=function(){},s.transact=function(e,t,n){var r=s.get(e);null==n&&(n=t,t=null),"undefined"==typeof r&&(r=t||{}),n(r),s.set(e,r)},s.getAll=function(){},s.forEach=function(){},s.serialize=function(e){return JSON.stringify(e)},s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}},r())a=t[u],s.set=function(e,t){return void 0===t?s.remove(e):(a.setItem(e,s.serialize(t)),t)},s.get=function(e){return s.deserialize(a.getItem(e))},s.remove=function(e){a.removeItem(e)},s.clear=function(){a.clear()},s.getAll=function(){var e={};return s.forEach(function(t,n){e[t]=n}),e},s.forEach=function(e){for(var t=0;t<a.length;t++){var n=a.key(t);e(n,s.get(n))}};else if(l.documentElement.addBehavior){var f,d;try{d=new ActiveXObject("htmlfile"),d.open(),d.write("<"+c+">document.w=window</"+c+'><iframe src="/favicon.ico"></iframe>'),d.close(),f=d.w.frames[0].document,a=f.createElement("div")}catch(h){a=l.createElement("div"),f=l.body}var p=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=i(function(e,t,n){return t=o(t),void 0===n?s.remove(t):(e.setAttribute(t,s.serialize(n)),e.save(u),n)}),s.get=i(function(e,t){return t=o(t),s.deserialize(e.getAttribute(t))}),s.remove=i(function(e,t){t=o(t),e.removeAttribute(t),e.save(u)}),s.clear=i(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(u);for(var n,r=0;n=t[r];r++)e.removeAttribute(n.name);e.save(u)}),s.getAll=function(){var e={};return s.forEach(function(t,n){e[t]=n}),e},s.forEach=i(function(e,t){for(var n,r=e.XMLDocument.documentElement.attributes,i=0;n=r[i];++i)t(n.name,s.deserialize(e.getAttribute(n.name)))})}try{var g="__storejs__";s.set(g,g),s.get(g)!=g&&(s.disabled=!0),s.remove(g)}catch(h){s.disabled=!0}s.enabled=!s.disabled,"undefined"!=typeof n&&n.exports&&this.module!==n?n.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s}(Function("return this")())},{}],10:[function(e,t){t.exports={name:"yasgui-utils",version:"1.4.1",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:{name:"Laurens Rietveld"},maintainers:[{name:"Laurens Rietveld",email:"[email protected]",url:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"},readme:"A simple utils repo for the YASGUI tools\n",readmeFilename:"README.md",_id:"[email protected]",_from:"yasgui-utils@^1.4.1"}},{}],11:[function(e,t){window.console=window.console||{log:function(){}},t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":10,"./storage.js":12,"./svg.js":13}],12:[function(e,t){{var n=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,i){"string"==typeof i&&(i=r[i]()),t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement)),n.set(e,{val:t,exp:i,time:(new Date).getTime()})},get:function(e){var t=n.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}}}},{store:9}],13:[function(e,t){t.exports={draw:function(e,n,r){if(e){var i=t.exports.getElement(n,r);i&&(e.append?e.append(i):e.appendChild(i))}},getElement:function(e,t){if(e&&0==e.indexOf("<svg")){t.width||(t.width="100%"),t.height||(t.height="100%");var n=new DOMParser,r=n.parseFromString(e,"text/xml"),i=r.documentElement,o=document.createElement("div");return o.style.display="inline-block",o.style.width=t.width,o.style.height=t.height,o.appendChild(i),o}return!1}}},{}],14:[function(e,t){t.exports={name:"yasgui-yasr",description:"Yet Another SPARQL Resultset GUI",version:"2.0.2",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasr.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasr.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.0","gulp-notify":"^1.2.5","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^0.2.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","browserify-shim":"^3.8.0","gulp-sourcemaps":"^1.2.4",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","yasgui-yasqe":"^2.0.1","twitter-bootstrap-3.0.0":"^3.0.0"},bugs:"https://github.com/YASGUI/YASR/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASR.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.2.0","yasgui-utils":"^1.4.1"},"browserify-shim":{jquery:"global:jQuery",codemirror:"global:CodeMirror","../../lib/codemirror":"global:CodeMirror","../lib/DataTables/media/js/jquery.dataTables.js":"global:jQuery"}}},{}],15:[function(e,t){t.exports=function(e){var t='"',n=",",r="\n",i=e.head.vars,o=e.results.bindings,a=function(){for(var e=0;e<i.length;e++)u(i[e]);csvString+=r},s=function(){for(var e=0;e<o.length;e++)l(o[e]),csvString+=r},l=function(e){for(var t=0;t<i.length;t++){var n=i[t];u(e.hasOwnProperty(n)?e[n].value:"")}},u=function(e){e.replace(t,t+t),c(e)&&(e=t+e+t),csvString+=" "+e+" "+n},c=function(e){var r=!1;return e.match("[\\w|"+n+"|"+t+"]")&&(r=!0),r};return csvString="",a(),s(),csvString}},{}],16:[function(e,t){var n=e("jquery"),r=t.exports=function(t){var r=n("<div class='booleanResult'></div>"),i=function(){r.empty().appendTo(t.resultsContainer);var i=t.results.getBoolean(),o=null,a=null;i===!0?(o="check",a="True"):i===!1?(o="cross",a="False"):(r.width("140"),a="Could not find boolean value in response"),o&&e("yasgui-utils").svg.draw(r,e("./imgs.js")[o],{width:25,height:25}),n("<span></span>").text(a).appendTo(r)},o=function(){return t.results.getBoolean()===!0||0==t.results.getBoolean()};return{name:null,draw:i,hideFromSelection:!0,getPriority:10,canHandleResults:o}};r.version={"YASR-boolean":e("../package.json").version,jquery:n.fn.jquery}},{"../package.json":14,"./imgs.js":19,jquery:8,"yasgui-utils":11}],17:[function(e,t){var n=e("jquery");t.exports={output:"table",outputPlugins:["table","error","boolean","rawResponse"],drawOutputSelector:!0,drawDownloadIcon:!0,getUsedPrefixes:null,persistency:{outputSelector:function(e){return"selector_"+n(e.container).closest("[id]").attr("id")},results:{id:function(e){return"results_"+n(e.container).closest("[id]").attr("id")},maxSize:1e5}}}},{jquery:8}],18:[function(e,t){var n=e("jquery"),r=t.exports=function(e){var t=n("<div class='errorResult'></div>"),i=(n.extend(!0,{},r.defaults),function(){t.empty().appendTo(e.resultsContainer),n("<span class='exception'>ERROR</span>").appendTo(t),n("<p></p>").html(e.results.getException()).appendTo(t)}),o=function(e){return e.results.getException()||!1};return{name:null,draw:i,getPriority:20,hideFromSelection:!0,canHandleResults:o}};r.defaults={}},{jquery:8}],19:[function(e,t){t.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>'} },{}],20:[function(e,t){e("jquery"),t.exports=function(t){return e("./dlv.js")(t,",")}},{"./dlv.js":21,jquery:8}],21:[function(e,t){var n=jQuery=e("jquery");e("../../lib/jquery.csv-0.71.js");t.exports=function(e,t){var r={},i=n.csv.toArrays(e,{separator:t}),o=function(e){return 0==e.indexOf("http")?"uri":null},a=function(){return 2!=i.length||1!=i[0].length||1!=i[1].length||"boolean"!=i[0][0]||"1"!=i[1][0]&&"0"!=i[1][0]?!1:(r.boolean="1"==i[1][0]?!0:!1,!0)},s=function(){return i.length>0&&i[0].length>0?(r.head={vars:i[0]},!0):!1},l=function(){if(i.length>1){r.results={bindings:[]};for(var e=1;e<i.length;e++){for(var t={},n=0;n<i[e].length;n++){var a=r.head.vars[n];if(a){var s=i[e][n],l=o(s);t[a]={value:s},l&&(t[a].type=l)}}r.results.bindings.push(t)}return r.head={vars:i[0]},!0}return!1},u=a();if(!u){var c=s();c&&l()}return r}},{"../../lib/jquery.csv-0.71.js":3,jquery:8}],22:[function(e,t){e("jquery"),t.exports=function(e){if("string"==typeof e)try{return JSON.parse(e)}catch(t){return!1}return"object"==typeof e&&e.constructor==={}.constructor?e:!1}},{jquery:8}],23:[function(e,t){e("jquery"),t.exports=function(t){return e("./dlv.js")(t," ")}},{"./dlv.js":21,jquery:8}],24:[function(e,t){e("jquery"),t.exports=function(t){var n,r,i={xml:e("./xml.js"),json:e("./json.js"),tsv:e("./tsv.js"),csv:e("./csv.js")},o=null,a=null,s="object"==typeof t&&t.exception?t.exception:null;n="object"==typeof t&&t.contentType?t.contentType.toLowerCase():null,r="object"==typeof t&&t.response?t.response:t;var l=function(){if(o)return o;if(o===!1||s)return!1;var e=function(){if(n)if(n.indexOf("json")>-1){try{o=i.json(r)}catch(e){s=e}a="json"}else if(n.indexOf("xml")>-1){try{o=i.xml(r)}catch(e){s=e}a="xml"}else if(n.indexOf("csv")>-1){try{o=i.csv(r)}catch(e){s=e}a="csv"}else if(n.indexOf("tab-separated")>-1){try{o=i.tsv(r)}catch(e){s=e}a="tsv"}},t=function(){if(o=i.json(r))a="json";else try{o=i.xml(r),o&&(a="xml")}catch(e){}};return e(),o||t(),o||(o=!1),o},u=function(){var e=l();return e&&"head"in e?e.head.vars:null},c=function(){var e=l();return e&&"results"in e?e.results.bindings:null},f=function(){var e=l();return e&&"boolean"in e?e.boolean:null},d=function(){return r},h=function(){var e="";return"string"==typeof r?e=r:"json"==a?e=JSON.stringify(r,void 0,2):"xml"==a&&(e=(new XMLSerializer).serializeToString(r)),e},p=function(){return s},g=function(){return null==a&&l(),a};return o=l(),{getAsJson:l,getOriginalResponse:d,getOriginalResponseAsString:h,getOriginalContentType:function(){return n},getVariables:u,getBindings:c,getBoolean:f,getType:g,getException:p}}},{"./csv.js":20,"./json.js":22,"./tsv.js":23,"./xml.js":25,jquery:8}],25:[function(e,t){{var n=e("jquery");t.exports=function(e){var t=function(e){a.head={};for(var t=0;t<e.childNodes.length;t++){var n=e.childNodes[t];if("variable"==n.nodeName){a.head.vars||(a.head.vars=[]);var r=n.getAttribute("name");r&&a.head.vars.push(r)}}},r=function(e){a.results={},a.results.bindings=[];for(var t=0;t<e.childNodes.length;t++){for(var n=e.childNodes[t],r=null,i=0;i<n.childNodes.length;i++){var o=n.childNodes[i];if("binding"==o.nodeName){var s=o.getAttribute("name");if(s){r=r||{},r[s]={};for(var l=0;l<o.childNodes.length;l++){var u=o.childNodes[l],c=u.nodeName;if("#text"!=c){r[s].type=c,r[s].value=u.innerHTML;var f=u.getAttribute("datatype");f&&(r[s].datatype=f)}}}}}r&&a.results.bindings.push(r)}},i=function(e){a.boolean="true"==e.innerHTML?!0:!1},o=null;"string"==typeof e?o=n.parseXML(e):n.isXMLDoc(e)&&(o=e);var e=null;if(!(o.childNodes.length>0))return null;e=o.childNodes[0];for(var a={},s=0;s<e.childNodes.length;s++){var l=e.childNodes[s];"head"==l.nodeName&&t(l),"results"==l.nodeName&&r(l),"boolean"==l.nodeName&&i(l)}return a}}},{jquery:8}],26:[function(e,t){var n=e("jquery"),r=e("codemirror");e("codemirror/addon/edit/matchbrackets.js"),e("codemirror/mode/xml/xml.js"),e("codemirror/mode/javascript/javascript.js");var i=t.exports=function(e){var t=n.extend(!0,{},i.defaults),o=function(){var n=t.CodeMirror;n.value=e.results.getOriginalResponseAsString();var i=e.results.getType();i&&("json"==i&&(i={name:"javascript",json:!0}),n.mode=i),r(e.resultsContainer.get()[0],n)},a=function(){if(!e.results)return!1;var t=e.results.getOriginalResponseAsString();return t&&0!=t.length||!e.results.getException()?!0:!1},s=function(){if(!e.results)return null;var t=e.results.getOriginalContentType(),n=e.results.getType();return{getContent:function(){return e.results.getOriginalResponse()},filename:"queryResults"+(n?"."+n:""),contentType:t?t:"text/plain",buttonTitle:"Download raw response"}};return{draw:o,name:"Raw Response",canHandleResults:a,getPriority:2,getDownloadInfo:s}};i.defaults={CodeMirror:{readOnly:!0}},i.version={"YASR-rawResponse":e("../package.json").version,jquery:n.fn.jquery,CodeMirror:r.version}},{"../package.json":14,codemirror:5,"codemirror/addon/edit/matchbrackets.js":4,"codemirror/mode/javascript/javascript.js":6,"codemirror/mode/xml/xml.js":7,jquery:8}],27:[function(e,t){var n=e("jquery"),r=e("yasgui-utils"),i=e("./imgs.js");e("../lib/DataTables/media/js/jquery.dataTables.js");var o=t.exports=function(t){var a=null,l=n.extend(!0,{},o.defaults),u=function(){var e=[];e.push({title:""});for(var n=t.results.getVariables(),r=0;r<n.length;r++)e.push({title:n[r]});return e},c=function(){var e=[],n=t.results.getBindings(),r=t.results.getVariables(),i=null;t.options.getUsedPrefixes&&(i="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);for(var o=0;o<n.length;o++){var a=[];a.push("");for(var s=n[o],u=0;u<r.length;u++){var c=r[u];a.push(c in s?l.drawCellContent?l.drawCellContent(o,u,s[c],i):"":"")}e.push(a)}return e},f=function(){a.on("order.dt",function(){h()}),n.extend(!0,l.callbacks,l.handlers),a.delegate("td","click",function(e){if(l.callbacks&&l.callbacks.onCellClick){var t=l.callbacks.onCellClick(this,e);if(t===!1)return!1}}).delegate("td","mouseenter",function(e){l.callbacks&&l.callbacks.onCellMouseEnter&&l.callbacks.onCellMouseEnter(this,e);var t=n(this);l.fetchTitlesFromPreflabel&&void 0===t.attr("title")&&0==t.text().trim().indexOf("http")&&s(t)}).delegate("td","mouseleave",function(e){l.callbacks&&l.callbacks.onCellMouseLeave&&l.callbacks.onCellMouseLeave(this,e)})},d=function(){a=n('<table cellpadding="0" cellspacing="0" border="0" class="resultsTable"></table>'),n(t.resultsContainer).html(a);var e=l.datatable;e.data=c(),e.columns=u(),a.DataTable(n.extend(!0,{},e)),h(),f();var r=t.header.outerHeight()-5;r>0&&t.resultsContainer.find(".dataTables_wrapper").css("position","relative").css("top","-"+r+"px").css("margin-bottom","-"+r+"px")},h=function(){var e={sorting:"unsorted",sorting_asc:"sortAsc",sorting_desc:"sortDesc"};a.find(".sortIcons").remove();var t=8,o=13;for(var s in e){var l=n("<div class='sortIcons'></div>").css("float","right").css("margin-right","-12px").width(t).height(o);r.svg.draw(l,i[e[s]],{width:t+2,height:o+1}),a.find("th."+s).append(l)}},p=function(){return t.results&&t.results.getVariables()&&t.results.getVariables().length>0},g=function(){return t.results?{getContent:function(){return e("./bindingsToCsv.js")(t.results.getAsJson())},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:null};return{name:"Table",draw:d,getPriority:10,getDownloadInfo:g,canHandleResults:p}},a=function(e,t,n,r){var i=null;if("uri"==n.type){var o=visibleString=n.value;if(r)for(var a in r)if(0==visibleString.indexOf(r[a])){visibleString=a+o.substring(r[a].length);break}i="<a class='uri' target='_blank' href='"+o+"'>"+visibleString+"</a>"}else{var s=n.value;if(n["xml:lang"])s='"'+n.value+'"@'+n["xml:lang"];else if(n.datatype){var l="http://www.w3.org/2001/XMLSchema#",u=n.datatype;u=0==u.indexOf(l)?"xsd:"+u.substring(l.length):"<"+u+">",s='"'+s+'"^^'+u}i="<span class='nonUri'>"+s+"</span>"}return i},s=function(e){var t=function(){e.attr("title","")};n.get("http://preflabel.org/api/v1/label/"+encodeURIComponent(e.text())+"?silent=true").success(function(n){"object"==typeof n&&n.label?e.attr("title",n.label):"string"==typeof n&&n.length>0?e.attr("title",n):t()}).fail(t)};o.defaults={drawCellContent:a,fetchTitlesFromPreflabel:!0,callbacks:{onCellMouseEnter:null,onCellMouseLeave:null,onCellClick:null},datatable:{order:[],pageLength:50,lengthMenu:[[10,50,100,1e3,-1],[10,50,100,1e3,"All"]],lengthChange:!0,pagingType:"full_numbers",drawCallback:function(e){for(var t=0;t<e.aiDisplay.length;t++)n("td:eq(0)",e.aoData[e.aiDisplay[t]].nTr).html(t+1);var r=!1;n(e.nTableWrapper).find(".paginate_button").each(function(){-1==n(this).attr("class").indexOf("current")&&-1==n(this).attr("class").indexOf("disabled")&&(r=!0)}),r?n(e.nTableWrapper).find(".dataTables_paginate").show():n(e.nTableWrapper).find(".dataTables_paginate").hide()},columnDefs:[{width:"12px",orderable:!1,targets:0}]}},o.version={"YASR-table":e("../package.json").version,jquery:n.fn.jquery,"jquery-datatables":n.fn.DataTable.version}},{"../lib/DataTables/media/js/jquery.dataTables.js":2,"../package.json":14,"./bindingsToCsv.js":15,"./imgs.js":19,jquery:8,"yasgui-utils":11}]},{},[1])(1)}); //# sourceMappingURL=yasr.bundled.min.js.map
ajax/libs/rxjs/2.4.9/rx.all.compat.js
bsquochoaidownloadfolders/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); } recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle) }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { return thrower(result.e); } } } } var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; 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); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** @deprecated use return or just */ Observable.returnValue = function () { //deprecate('returnValue', 'return or just'); return observableReturn.apply(null, arguments); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }, source); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { o.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { o.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, function (e) { o.onError(e); }, function () { o.onNext(list); o.onCompleted(); }); }, source); } function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @deprecated Use #reduce instead * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var hasSeed = false, accumulator, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var hasSeed = false, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, function (e) { observer.onError(e); }, function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { o.onNext(true); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onNext(false); o.onCompleted(); }); }, this); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { o.onNext(i); o.onCompleted(); } i++; }, function (e) { o.onError(e); }, function () { o.onNext(-1); o.onCompleted(); }); }, source); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).average() : this.reduce(function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }, {sum: 0, count: 0 }).map(function (s) { if (s.count === 0) { throw new EmptyError(); } return s.sum / s.count; }); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (o) { var i = index; return source.subscribe(function (x) { if (i-- === 0) { o.onNext(x); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new ArgumentOutOfRangeError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { return source.subscribe(function (x) { o.onNext(x); o.onCompleted(); }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new EmptyError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = callback(x, i, source); } catch (e) { o.onError(e); return; } if (shouldRun) { o.onNext(yieldIndex ? i : x); o.onCompleted(); } else { i++; } }, function (e) { o.onError(e); }, function () { o.onNext(yieldIndex ? -1 : undefined); o.onCompleted(); }); }, source); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var s = new root.Set(); return source.subscribe( function (x) { s.add(x); }, function (e) { o.onError(e); }, function () { o.onNext(s); o.onCompleted(); }); }, source); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { o.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { o.onError(e); return; } } m.set(key, element); }, function (e) { o.onError(e); }, function () { o.onNext(m); o.onCompleted(); }); }, source); }; var fnString = 'function', throwString = 'throw', isObject = Rx.internals.isObject; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res) { if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThunk(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn) { promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && typeof obj.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fn; if (isGenFun) { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : handleError; gen = fn.apply(this, args); } else { done = done || handleError; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) { for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } } if (err) { try { ret = gen[throwString](err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function() { if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; function handleError(err) { if (!err) { return; } timeoutScheduler.schedule(function() { throw err; }); } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return new AnonymousObservable(function (observer) { function handler() { var results = arguments; if (selector) { try { results = selector(results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (selector) { try { results = selector(results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation) { event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch (event.type) { case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { o.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { o.onError(ex); return; } o.onNext(res); } if (isDone && values[1]) { o.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { o.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { o.onNext(q.shift()); } o.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue) { enableQueue == null && (enableQueue = true); __super__.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) this.subject.onCompleted(); else this.queue.push(Rx.Notification.createOnCompleted()); }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) this.subject.onError(error); else this.queue.push(Rx.Notification.createOnError(error)); }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value)); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while ((this.queue.length >= numberOfItems && numberOfItems > 0) || (this.queue.length > 0 && this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') numberOfItems--; else { this.disposeCurrentRequest(); this.queue = []; } } return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } //TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function //if (this.hasFailed) { // this.subject.onError(this.error); //} else if (this.hasCompleted) { // this.subject.onCompleted(); //} return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); var number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable; } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var StopAndWaitObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(1); }); return this.subscription; } inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this, subscribe, source); this.source = source; } var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; } var stopAndWaitObserverProto = StopAndWaitObserver.prototype; stopAndWaitObserverProto.completed = function () { this.observer.onCompleted(); this.dispose(); }; stopAndWaitObserverProto.error = function (error) { this.observer.onError(error); this.dispose(); } stopAndWaitObserverProto.next = function (value) { this.observer.onNext(value); var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(1); }); }; stopAndWaitObserverProto.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(self.windowSize); }); return this.subscription; } inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this, subscribe, source); this.source = source; this.windowSize = windowSize; } var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; } var windowedObserverPrototype = WindowedObserver.prototype; windowedObserverPrototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; windowedObserverPrototype.error = function (error) { this.observer.onError(error); this.dispose(); }; windowedObserverPrototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; if (this.received === 0) { var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(self.observable.windowSize); }); } }; windowedObserverPrototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if ((candidate & 1) === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash << 5) - hash) + character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof valueOf === 'string') { return stringHashFn(valueOf); } } if (obj.hashCode) { return obj.hashCode(); } var id = 17 * uniqueIdCounter++; obj.hashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new ArgumentOutOfRangeError(); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }, left); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }, left); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }, this); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }, first); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }, source); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeAll().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwError(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.exception); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, observer.onError.bind(observer), start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ observableProto.debounceWithSelector = function (durationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = durationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && observer.onNext(value); observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, source); }; /** * @deprecated use #debounceWithSelector instead. */ observableProto.throttleWithSelector = function (durationSelector) { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector(durationSelector); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } o.onCompleted(); }); }, source); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { o.onNext(next.value); } } o.onCompleted(); }); }, source); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }, source); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); })); }, source); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }, this); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this, selectorFunc = bindCallback(selector, thisArg, 3); return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selectorFunc(x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (e) { observer.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, function (e) { observer.onError(e); }, function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }, this); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
ajax/libs/analytics.js/1.3.7/analytics.js
nesk/cdnjs
;(function(){ /** * Require the given path. * * @param {String} path * @return {Object} exports * @api public */ function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module._resolving && !module.exports) { var mod = {}; mod.exports = {}; mod.client = mod.component = true; module._resolving = true; module.call(this, mod.exports, require.relative(resolved), mod); delete module._resolving; module.exports = mod.exports; } return module.exports; } /** * Registered modules. */ require.modules = {}; /** * Registered aliases. */ require.aliases = {}; /** * Resolve `path`. * * Lookup: * * - PATH/index.js * - PATH.js * - PATH * * @param {String} path * @return {String} path or null * @api private */ require.resolve = function(path) { if (path.charAt(0) === '/') path = path.slice(1); var paths = [ path, path + '.js', path + '.json', path + '/index.js', path + '/index.json' ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; } }; /** * Normalize `path` relative to the current path. * * @param {String} curr * @param {String} path * @return {String} * @api private */ require.normalize = function(curr, path) { var segs = []; if ('.' != path.charAt(0)) return path; curr = curr.split('/'); path = path.split('/'); for (var i = 0; i < path.length; ++i) { if ('..' == path[i]) { curr.pop(); } else if ('.' != path[i] && '' != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join('/'); }; /** * Register module at `path` with callback `definition`. * * @param {String} path * @param {Function} definition * @api private */ require.register = function(path, definition) { require.modules[path] = definition; }; /** * Alias a module definition. * * @param {String} from * @param {String} to * @api private */ require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; /** * Return a require function relative to the `parent` path. * * @param {String} parent * @return {Function} * @api private */ require.relative = function(parent) { var p = require.normalize(parent, '..'); /** * lastIndexOf helper. */ function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * The relative require() itself. */ function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } /** * Resolve relative to the parent. */ localRequire.resolve = function(path) { var c = path.charAt(0); if ('/' == c) return path.slice(1); if ('.' == c) return require.normalize(p, path); // resolve deps by returning // the dep in the nearest "deps" // directory var segs = parent.split('/'); var i = lastIndexOf(segs, 'deps') + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join('/') + '/deps/' + path; return path; }; /** * Check if module is defined at `path`. */ localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("avetisk-defaults/index.js", function(exports, require, module){ 'use strict'; /** * Merge default values. * * @param {Object} dest * @param {Object} defaults * @return {Object} * @api public */ var defaults = function (dest, src, recursive) { for (var prop in src) { if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) { dest[prop] = defaults(dest[prop], src[prop], true); } else if (! (prop in dest)) { dest[prop] = src[prop]; } } return dest; }; /** * Expose `defaults`. */ module.exports = defaults; }); require.register("component-type/index.js", function(exports, require, module){ /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Function]': return 'function'; case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object String]': return 'string'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val && val.nodeType === 1) return 'element'; if (val === Object(val)) return 'object'; return typeof val; }; }); require.register("component-clone/index.js", function(exports, require, module){ /** * Module dependencies. */ var type; try { type = require('type'); } catch(e){ type = require('type-component'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }); require.register("component-cookie/index.js", function(exports, require, module){ /** * Encode. */ var encode = encodeURIComponent; /** * Decode. */ var decode = decodeURIComponent; /** * Set or get cookie `name` with `value` and `options` object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Mixed} * @api public */ module.exports = function(name, value, options){ switch (arguments.length) { case 3: case 2: return set(name, value, options); case 1: return get(name); default: return all(); } }; /** * Set cookie `name` to `value`. * * @param {String} name * @param {String} value * @param {Object} options * @api private */ function set(name, value, options) { options = options || {}; var str = encode(name) + '=' + encode(value); if (null == value) options.maxage = -1; if (options.maxage) { options.expires = new Date(+new Date + options.maxage); } if (options.path) str += '; path=' + options.path; if (options.domain) str += '; domain=' + options.domain; if (options.expires) str += '; expires=' + options.expires.toGMTString(); if (options.secure) str += '; secure'; document.cookie = str; } /** * Return all cookies. * * @return {Object} * @api private */ function all() { return parse(document.cookie); } /** * Get cookie `name`. * * @param {String} name * @return {String} * @api private */ function get(name) { return all()[name]; } /** * Parse cookie `str`. * * @param {String} str * @return {Object} * @api private */ function parse(str) { var obj = {}; var pairs = str.split(/ *; */); var pair; if ('' == pairs[0]) return obj; for (var i = 0; i < pairs.length; ++i) { pair = pairs[i].split('='); obj[decode(pair[0])] = decode(pair[1]); } return obj; } }); require.register("component-each/index.js", function(exports, require, module){ /** * Module dependencies. */ var type = require('type'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)`. * * @param {String|Array|Object} obj * @param {Function} fn * @api public */ module.exports = function(obj, fn){ switch (type(obj)) { case 'array': return array(obj, fn); case 'object': if ('number' == typeof obj.length) return array(obj, fn); return object(obj, fn); case 'string': return string(obj, fn); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @api private */ function string(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @api private */ function object(obj, fn) { for (var key in obj) { if (has.call(obj, key)) { fn(key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @api private */ function array(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj[i], i); } } }); require.register("component-indexof/index.js", function(exports, require, module){ module.exports = function(arr, obj){ if (arr.indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; }); require.register("component-emitter/index.js", function(exports, require, module){ /** * Module dependencies. */ var index = require('indexof'); /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = index(callbacks, fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }); require.register("component-event/index.js", function(exports, require, module){ /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ if (el.addEventListener) { el.addEventListener(type, fn, capture || false); } else { el.attachEvent('on' + type, fn); } return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ if (el.removeEventListener) { el.removeEventListener(type, fn, capture || false); } else { el.detachEvent('on' + type, fn); } return fn; }; }); require.register("component-inherit/index.js", function(exports, require, module){ module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }); require.register("component-object/index.js", function(exports, require, module){ /** * HOP ref. */ var has = Object.prototype.hasOwnProperty; /** * Return own keys in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.keys = Object.keys || function(obj){ var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Return own values in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.values = function(obj){ var vals = []; for (var key in obj) { if (has.call(obj, key)) { vals.push(obj[key]); } } return vals; }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} a * @api public */ exports.merge = function(a, b){ for (var key in b) { if (has.call(b, key)) { a[key] = b[key]; } } return a; }; /** * Return length of `obj`. * * @param {Object} obj * @return {Number} * @api public */ exports.length = function(obj){ return exports.keys(obj).length; }; /** * Check if `obj` is empty. * * @param {Object} obj * @return {Boolean} * @api public */ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; }); require.register("component-trim/index.js", function(exports, require, module){ exports = module.exports = trim; function trim(str){ if (str.trim) return str.trim(); return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ if (str.trimLeft) return str.trimLeft(); return str.replace(/^\s*/, ''); }; exports.right = function(str){ if (str.trimRight) return str.trimRight(); return str.replace(/\s*$/, ''); }; }); require.register("component-querystring/index.js", function(exports, require, module){ /** * Module dependencies. */ var trim = require('trim'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); obj[parts[0]] = null == parts[1] ? '' : decodeURIComponent(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } return pairs.join('&'); }; }); require.register("component-url/index.js", function(exports, require, module){ /** * Parse the given `url`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(url){ var a = document.createElement('a'); a.href = url; return { href: a.href, host: a.host || location.host, port: ('0' === a.port || '' === a.port) ? port(a.protocol) : a.port, hash: a.hash, hostname: a.hostname || location.hostname, pathname: a.pathname.charAt(0) != '/' ? '/' + a.pathname : a.pathname, protocol: !a.protocol || ':' == a.protocol ? location.protocol : a.protocol, search: a.search, query: a.search.slice(1) }; }; /** * Check if `url` is absolute. * * @param {String} url * @return {Boolean} * @api public */ exports.isAbsolute = function(url){ return 0 == url.indexOf('//') || !!~url.indexOf('://'); }; /** * Check if `url` is relative. * * @param {String} url * @return {Boolean} * @api public */ exports.isRelative = function(url){ return !exports.isAbsolute(url); }; /** * Check if `url` is cross domain. * * @param {String} url * @return {Boolean} * @api public */ exports.isCrossDomain = function(url){ url = exports.parse(url); return url.hostname !== location.hostname || url.port !== location.port || url.protocol !== location.protocol; }; /** * Return default port for `protocol`. * * @param {String} protocol * @return {String} * @api private */ function port (protocol){ switch (protocol) { case 'http:': return 80; case 'https:': return 443; default: return location.port; } } }); require.register("component-bind/index.js", function(exports, require, module){ /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; }); require.register("segmentio-bind-all/index.js", function(exports, require, module){ try { var bind = require('bind'); var type = require('type'); } catch (e) { var bind = require('bind-component'); var type = require('type-component'); } module.exports = function (obj) { for (var key in obj) { var val = obj[key]; if (type(val) === 'function') obj[key] = bind(obj, obj[key]); } return obj; }; }); require.register("ianstormtaylor-bind/index.js", function(exports, require, module){ try { var bind = require('bind'); } catch (e) { var bind = require('bind-component'); } var bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; } }); require.register("timoxley-next-tick/index.js", function(exports, require, module){ "use strict" if (typeof setImmediate == 'function') { module.exports = function(f){ setImmediate(f) } } // legacy node.js else if (typeof process != 'undefined' && typeof process.nextTick == 'function') { module.exports = process.nextTick } // fallback for other environments / postMessage behaves badly on IE8 else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) { module.exports = function(f){ setTimeout(f) }; } else { var q = []; window.addEventListener('message', function(){ var i = 0; while (i < q.length) { try { q[i++](); } catch (e) { q = q.slice(i); window.postMessage('tic!', '*'); throw e; } } q.length = 0; }, true); module.exports = function(fn){ if (!q.length) window.postMessage('tic!', '*'); q.push(fn); } } }); require.register("ianstormtaylor-callback/index.js", function(exports, require, module){ var next = require('next-tick'); /** * Expose `callback`. */ module.exports = callback; /** * Call an `fn` back synchronously if it exists. * * @param {Function} fn */ function callback (fn) { if ('function' === typeof fn) fn(); } /** * Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the * `fn` will be called on next tick. * * @param {Function} fn * @param {Number} wait (optional) */ callback.async = function (fn, wait) { if ('function' !== typeof fn) return; if (!wait) return next(fn); setTimeout(fn, wait); }; /** * Symmetry. */ callback.sync = callback; }); require.register("ianstormtaylor-is-empty/index.js", function(exports, require, module){ /** * Expose `isEmpty`. */ module.exports = isEmpty; /** * Has. */ var has = Object.prototype.hasOwnProperty; /** * Test whether a value is "empty". * * @param {Mixed} val * @return {Boolean} */ function isEmpty (val) { if (null == val) return true; if ('number' == typeof val) return 0 === val; if (undefined !== val.length) return 0 === val.length; for (var key in val) if (has.call(val, key)) return false; return true; } }); require.register("ianstormtaylor-is/index.js", function(exports, require, module){ var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }); require.register("segmentio-after/index.js", function(exports, require, module){ module.exports = function after (times, func) { // After 0, really? if (times <= 0) return func(); // That's more like it. return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; }); require.register("yields-slug/index.js", function(exports, require, module){ /** * Generate a slug from the given `str`. * * example: * * generate('foo bar'); * // > foo-bar * * @param {String} str * @param {Object} options * @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g` * @config {String} [separator] separator to insert, defaulted to `-` * @return {String} */ module.exports = function (str, options) { options || (options = {}); return str.toLowerCase() .replace(options.replace || /[^a-z0-9]/g, ' ') .replace(/^ +| +$/g, '') .replace(/ +/g, options.separator || '-') }; }); require.register("segmentio-analytics.js-integration/lib/index.js", function(exports, require, module){ var bind = require('bind'); var callback = require('callback'); var clone = require('clone'); var debug = require('debug'); var defaults = require('defaults'); var protos = require('./protos'); var slug = require('slug'); var statics = require('./statics'); /** * Expose `createIntegration`. */ module.exports = createIntegration; /** * Create a new Integration constructor. * * @param {String} name */ function createIntegration (name) { /** * Initialize a new `Integration`. * * @param {Object} options */ function Integration (options) { this.debug = debug('analytics:integration:' + slug(name)); this.options = defaults(clone(options) || {}, this.defaults); this._queue = []; this.once('ready', bind(this, this.flush)); Integration.emit('construct', this); this._wrapInitialize(); this._wrapLoad(); this._wrapPage(); this._wrapTrack(); } Integration.prototype.defaults = {}; Integration.prototype.globals = []; Integration.prototype.name = name; for (var key in statics) Integration[key] = statics[key]; for (var key in protos) Integration.prototype[key] = protos[key]; return Integration; } }); require.register("segmentio-analytics.js-integration/lib/protos.js", function(exports, require, module){ var after = require('after'); var callback = require('callback'); var Emitter = require('emitter'); var tick = require('next-tick'); var events = require('./events'); /** * Mixin emitter. */ Emitter(exports); /** * Initialize. */ exports.initialize = function () { this.load(); }; /** * Loaded? * * @return {Boolean} * @api private */ exports.loaded = function () { return false; }; /** * Load. * * @param {Function} cb */ exports.load = function (cb) { callback.async(cb); }; /** * Page. * * @param {Page} page */ exports.page = function(page){}; /** * Track. * * @param {Track} track */ exports.track = function(track){}; /** * Invoke a `method` that may or may not exist on the prototype with `args`, * queueing or not depending on whether the integration is "ready". Don't * trust the method call, since it contains integration party code. * * @param {String} method * @param {Mixed} args... * @api private */ exports.invoke = function (method) { if (!this[method]) return; var args = [].slice.call(arguments, 1); if (!this._ready) return this.queue(method, args); try { this.debug('%s with %o', method, args); this[method].apply(this, args); } catch (e) { this.debug('error %o calling %s with %o', e, method, args); } }; /** * Queue a `method` with `args`. If the integration assumes an initial * pageview, then let the first call to `page` pass through. * * @param {String} method * @param {Array} args * @api private */ exports.queue = function (method, args) { if ('page' == method && this._assumesPageview && !this._initialized) { return this.page.apply(this, args); } this._queue.push({ method: method, args: args }); }; /** * Flush the internal queue. * * @api private */ exports.flush = function () { this._ready = true; var call; while (call = this._queue.shift()) this[call.method].apply(this, call.args); }; /** * Reset the integration, removing its global variables. * * @api private */ exports.reset = function () { for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined; }; /** * Wrap the initialize method in an exists check, so we don't have to do it for * every single integration. * * @api private */ exports._wrapInitialize = function () { var initialize = this.initialize; this.initialize = function () { this.debug('initialize'); this._initialized = true; initialize.apply(this, arguments); this.emit('initialize'); var self = this; if (this._readyOnInitialize) { tick(function () { self.emit('ready'); }); } }; if (this._assumesPageview) this.initialize = after(2, this.initialize); }; /** * Wrap the load method in `debug` calls, so every integration gets them * automatically. * * @api private */ exports._wrapLoad = function () { var load = this.load; this.load = function (callback) { var self = this; this.debug('loading'); if (this.loaded()) { this.debug('already loaded'); tick(function () { if (self._readyOnLoad) self.emit('ready'); callback && callback(); }); return; } load.call(this, function (err, e) { self.debug('loaded'); self.emit('load'); if (self._readyOnLoad) self.emit('ready'); callback && callback(err, e); }); }; }; /** * Wrap the page method to call `initialize` instead if the integration assumes * a pageview. * * @api private */ exports._wrapPage = function () { var page = this.page; this.page = function () { if (this._assumesPageview && !this._initialized) { return this.initialize({ category: arguments[0], name: arguments[1], properties: arguments[2], options: arguments[3] }); } page.apply(this, arguments); }; }; /** * Wrap the track method to call other ecommerce methods if * available depending on the `track.event()`. * * @api private */ exports._wrapTrack = function(){ var t = this.track; this.track = function(track){ var event = track.event(); var called; for (var method in events) { var regexp = events[method]; if (!this[method]) continue; if (!regexp.test(event)) continue; this[method].apply(this, arguments); called = true; break; } if (!called) t.apply(this, arguments); }; }; }); require.register("segmentio-analytics.js-integration/lib/events.js", function(exports, require, module){ /** * Expose `events` */ module.exports = { removedProduct: /removed product/i, viewedProduct: /viewed product/i, addedProduct: /added product/i, completedOrder: /completed order/i }; }); require.register("segmentio-analytics.js-integration/lib/statics.js", function(exports, require, module){ var after = require('after'); var Emitter = require('emitter'); /** * Mixin emitter. */ Emitter(exports); /** * Add a new option to the integration by `key` with default `value`. * * @param {String} key * @param {Mixed} value * @return {Integration} */ exports.option = function (key, value) { this.prototype.defaults[key] = value; return this; }; /** * Register a new global variable `key` owned by the integration, which will be * used to test whether the integration is already on the page. * * @param {String} global * @return {Integration} */ exports.global = function (key) { this.prototype.globals.push(key); return this; }; /** * Mark the integration as assuming an initial pageview, so to defer loading * the script until the first `page` call, noop the first `initialize`. * * @return {Integration} */ exports.assumesPageview = function () { this.prototype._assumesPageview = true; return this; }; /** * Mark the integration as being "ready" once `load` is called. * * @return {Integration} */ exports.readyOnLoad = function () { this.prototype._readyOnLoad = true; return this; }; /** * Mark the integration as being "ready" once `load` is called. * * @return {Integration} */ exports.readyOnInitialize = function () { this.prototype._readyOnInitialize = true; return this; }; }); require.register("component-domify/index.js", function(exports, require, module){ /** * Expose `parse`. */ module.exports = parse; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], _default: [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return the children. * * @param {String} html * @return {Array} * @api private */ function parse(html) { if ('string' != typeof html) throw new TypeError('String expected'); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace // tag name var m = /<([\w:]+)/.exec(html); if (!m) return document.createTextNode(html); var tag = m[1]; // body support if (tag == 'body') { var el = document.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = document.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = document.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } }); require.register("component-once/index.js", function(exports, require, module){ /** * Identifier. */ var n = 0; /** * Global. */ var global = (function(){ return this })(); /** * Make `fn` callable only once. * * @param {Function} fn * @return {Function} * @api public */ module.exports = function(fn) { var id = n++; function once(){ // no receiver if (this == global) { if (once.called) return; once.called = true; return fn.apply(this, arguments); } // receiver var key = '__called_' + id + '__'; if (this[key]) return; this[key] = true; return fn.apply(this, arguments); } return once; }; }); require.register("segmentio-alias/index.js", function(exports, require, module){ var type = require('type'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `alias`. */ module.exports = alias; /** * Alias an `object`. * * @param {Object} obj * @param {Mixed} method */ function alias (obj, method) { switch (type(method)) { case 'object': return aliasByDictionary(clone(obj), method); case 'function': return aliasByFunction(clone(obj), method); } } /** * Convert the keys in an `obj` using a dictionary of `aliases`. * * @param {Object} obj * @param {Object} aliases */ function aliasByDictionary (obj, aliases) { for (var key in aliases) { if (undefined === obj[key]) continue; obj[aliases[key]] = obj[key]; delete obj[key]; } return obj; } /** * Convert the keys in an `obj` using a `convert` function. * * @param {Object} obj * @param {Function} convert */ function aliasByFunction (obj, convert) { // have to create another object so that ie8 won't infinite loop on keys var output = {}; for (var key in obj) output[convert(key)] = obj[key]; return output; } }); require.register("segmentio-convert-dates/index.js", function(exports, require, module){ var is = require('is'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `convertDates`. */ module.exports = convertDates; /** * Recursively convert an `obj`'s dates to new values. * * @param {Object} obj * @param {Function} convert * @return {Object} */ function convertDates (obj, convert) { obj = clone(obj); for (var key in obj) { var val = obj[key]; if (is.date(val)) obj[key] = convert(val); if (is.object(val)) obj[key] = convertDates(val, convert); } return obj; } }); require.register("segmentio-global-queue/index.js", function(exports, require, module){ /** * Expose `generate`. */ module.exports = generate; /** * Generate a global queue pushing method with `name`. * * @param {String} name * @param {Object} options * @property {Boolean} wrap * @return {Function} */ function generate (name, options) { options = options || {}; return function (args) { args = [].slice.call(arguments); window[name] || (window[name] = []); options.wrap === false ? window[name].push.apply(window[name], args) : window[name].push(args); }; } }); require.register("segmentio-load-date/index.js", function(exports, require, module){ /* * Load date. * * For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/ */ var time = new Date() , perf = window.performance; if (perf && perf.timing && perf.timing.responseEnd) { time = new Date(perf.timing.responseEnd); } module.exports = time; }); require.register("segmentio-load-script/index.js", function(exports, require, module){ var type = require('type'); module.exports = function loadScript (options, callback) { if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if (type(options) === 'string') options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); // If we have a callback, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if (callback && type(callback) === 'function') { if (script.addEventListener) { script.addEventListener('load', function (event) { callback(null, event); }, false); script.addEventListener('error', function (event) { callback(new Error('Failed to load the script.'), event); }, false); } else if (script.attachEvent) { script.attachEvent('onreadystatechange', function (event) { if (/complete|loaded/.test(script.readyState)) { callback(null, event); } }); } } // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }); require.register("segmentio-on-body/index.js", function(exports, require, module){ var each = require('each'); /** * Cache whether `<body>` exists. */ var body = false; /** * Callbacks to call when the body exists. */ var callbacks = []; /** * Export a way to add handlers to be invoked once the body exists. * * @param {Function} callback A function to call when the body exists. */ module.exports = function onBody (callback) { if (body) { call(callback); } else { callbacks.push(callback); } }; /** * Set an interval to check for `document.body`. */ var interval = setInterval(function () { if (!document.body) return; body = true; each(callbacks, call); clearInterval(interval); }, 5); /** * Call a callback, passing it the body. * * @param {Function} callback The callback to call. */ function call (callback) { callback(document.body); } }); require.register("segmentio-on-error/index.js", function(exports, require, module){ /** * Expose `onError`. */ module.exports = onError; /** * Callbacks. */ var callbacks = []; /** * Preserve existing handler. */ if ('function' == typeof window.onerror) callbacks.push(window.onerror); /** * Bind to `window.onerror`. */ window.onerror = handler; /** * Error handler. */ function handler () { for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments); } /** * Call a `fn` on `window.onerror`. * * @param {Function} fn */ function onError (fn) { callbacks.push(fn); if (window.onerror != handler) { callbacks.push(window.onerror); window.onerror = handler; } } }); require.register("segmentio-to-iso-string/index.js", function(exports, require, module){ /** * Expose `toIsoString`. */ module.exports = toIsoString; /** * Turn a `date` into an ISO string. * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString * * @param {Date} date * @return {String} */ function toIsoString (date) { return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + 'Z'; } /** * Pad a `number` with a ten's place zero. * * @param {Number} number * @return {String} */ function pad (number) { var n = number.toString(); return n.length === 1 ? '0' + n : n; } }); require.register("segmentio-to-unix-timestamp/index.js", function(exports, require, module){ /** * Expose `toUnixTimestamp`. */ module.exports = toUnixTimestamp; /** * Convert a `date` into a Unix timestamp. * * @param {Date} * @return {Number} */ function toUnixTimestamp (date) { return Math.floor(date.getTime() / 1000); } }); require.register("segmentio-use-https/index.js", function(exports, require, module){ /** * Protocol. */ module.exports = function (url) { switch (arguments.length) { case 0: return check(); case 1: return transform(url); } }; /** * Transform a protocol-relative `url` to the use the proper protocol. * * @param {String} url * @return {String} */ function transform (url) { return check() ? 'https:' + url : 'http:' + url; } /** * Check whether `https:` be used for loading scripts. * * @return {Boolean} */ function check () { return ( location.protocol == 'https:' || location.protocol == 'chrome-extension:' ); } }); require.register("visionmedia-batch/index.js", function(exports, require, module){ /** * Module dependencies. */ try { var EventEmitter = require('events').EventEmitter; } catch (err) { var Emitter = require('emitter'); } /** * Noop. */ function noop(){} /** * Expose `Batch`. */ module.exports = Batch; /** * Create a new Batch. */ function Batch() { if (!(this instanceof Batch)) return new Batch; this.fns = []; this.concurrency(Infinity); this.throws(true); for (var i = 0, len = arguments.length; i < len; ++i) { this.push(arguments[i]); } } /** * Inherit from `EventEmitter.prototype`. */ if (EventEmitter) { Batch.prototype.__proto__ = EventEmitter.prototype; } else { Emitter(Batch.prototype); } /** * Set concurrency to `n`. * * @param {Number} n * @return {Batch} * @api public */ Batch.prototype.concurrency = function(n){ this.n = n; return this; }; /** * Queue a function. * * @param {Function} fn * @return {Batch} * @api public */ Batch.prototype.push = function(fn){ this.fns.push(fn); return this; }; /** * Set wether Batch will or will not throw up. * * @param {Boolean} throws * @return {Batch} * @api public */ Batch.prototype.throws = function(throws) { this.e = !!throws; return this; }; /** * Execute all queued functions in parallel, * executing `cb(err, results)`. * * @param {Function} cb * @return {Batch} * @api public */ Batch.prototype.end = function(cb){ var self = this , total = this.fns.length , pending = total , results = [] , errors = [] , cb = cb || noop , fns = this.fns , max = this.n , throws = this.e , index = 0 , done; // empty if (!fns.length) return cb(null, results); // process function next() { var i = index++; var fn = fns[i]; if (!fn) return; var start = new Date; try { fn(callback); } catch (err) { callback(err); } function callback(err, res){ if (done) return; if (err && throws) return done = true, cb(err); var complete = total - pending + 1; var end = new Date; results[i] = res; errors[i] = err; self.emit('progress', { index: i, value: res, error: err, pending: pending, total: total, complete: complete, percent: complete / total * 100 | 0, start: start, end: end, duration: end - start }); if (--pending) next() else if(!throws) cb(errors, results); else cb(null, results); } } // concurrency for (var i = 0; i < fns.length; i++) { if (i == max) break; next(); } return this; }; }); require.register("segmentio-substitute/index.js", function(exports, require, module){ /** * Expose `substitute` */ module.exports = substitute; /** * Substitute `:prop` with the given `obj` in `str` * * @param {String} str * @param {Object} obj * @param {RegExp} expr * @return {String} * @api public */ function substitute(str, obj, expr){ if (!obj) throw new TypeError('expected an object'); expr = expr || /:(\w+)/g; return str.replace(expr, function(_, prop){ return null != obj[prop] ? obj[prop] : _; }); } }); require.register("segmentio-load-pixel/index.js", function(exports, require, module){ /** * Module dependencies. */ var stringify = require('querystring').stringify; var sub = require('substitute'); /** * Factory function to create a pixel loader. * * @param {String} path * @return {Function} * @api public */ module.exports = function(path){ return function(query, obj, fn){ if ('function' == typeof obj) fn = obj, obj = {}; obj = obj || {}; fn = fn || function(){}; var url = sub(path, obj); var img = new Image; img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; query = stringify(query); if (query) query = '?' + query; img.src = url + query; img.width = 1; img.height = 1; return img; }; }; /** * Create an error handler. * * @param {Fucntion} fn * @param {String} message * @param {Image} img * @return {Function} * @api private */ function error(fn, message, img){ return function(e){ e = e || window.event; var err = new Error(message); err.event = e; err.source = img; fn(err); }; } }); require.register("segmentio-analytics.js-integrations/index.js", function(exports, require, module){ var integrations = require('./lib/slugs'); var each = require('each'); /** * Expose the integrations, using their own `name` from their `prototype`. */ each(integrations, function (slug) { var plugin = require('./lib/' + slug); var name = plugin.Integration.prototype.name; exports[name] = plugin; }); }); require.register("segmentio-analytics.js-integrations/lib/adroll.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(AdRoll); user = analytics.user(); // store for later }; /** * Expose `AdRoll` integration. */ var AdRoll = exports.Integration = integration('AdRoll') .assumesPageview() .readyOnLoad() .global('__adroll_loaded') .global('adroll_adv_id') .global('adroll_pix_id') .global('adroll_custom_data') .option('advId', '') .option('pixId', ''); /** * Initialize. * * http://support.adroll.com/getting-started-in-4-easy-steps/#step-one * http://support.adroll.com/enhanced-conversion-tracking/ * * @param {Object} page */ AdRoll.prototype.initialize = function (page) { window.adroll_adv_id = this.options.advId; window.adroll_pix_id = this.options.pixId; if (user.id()) window.adroll_custom_data = { USER_ID: user.id() }; window.__adroll_loaded = true; this.load(); }; /** * Loaded? * * @return {Boolean} */ AdRoll.prototype.loaded = function () { return window.__adroll; }; /** * Load the AdRoll library. * * @param {Function} callback */ AdRoll.prototype.load = function (callback) { load({ http: 'http://a.adroll.com/j/roundtrip.js', https: 'https://s.adroll.com/j/roundtrip.js' }, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/adwords.js", function(exports, require, module){ var load = require('load-pixel')('//www.googleadservices.com/pagead/conversion/:id'); var integration = require('integration'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(AdWords); }; /** * Expose `load`. */ exports.load = load; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdWords` */ var AdWords = exports.Integration = integration('AdWords') .readyOnInitialize() .option('conversionId', '') .option('events', {}); /** * Track. * * @param {Track} */ AdWords.prototype.track = function(track){ var id = this.options.conversionId; var events = this.options.events; var event = track.event(); if (!has.call(events, event)) return; return exports.load({ value: track.revenue() || 0, label: events[event], script: 0 }, { id: id }); }; }); require.register("segmentio-analytics.js-integrations/lib/amplitude.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Amplitude); }; /** * Expose `Amplitude` integration. */ var Amplitude = exports.Integration = integration('Amplitude') .assumesPageview() .readyOnInitialize() .global('amplitude') .option('apiKey', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * https://github.com/amplitude/Amplitude-Javascript * * @param {Object} page */ Amplitude.prototype.initialize = function (page) { (function(e,t){var r=e.amplitude||{}; r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));};} var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName"]; for(var c=0;c<s.length;c++){i(s[c]);}e.amplitude=r;})(window,document); window.amplitude.init(this.options.apiKey); this.load(); }; /** * Loaded? * * @return {Boolean} */ Amplitude.prototype.loaded = function () { return !! (window.amplitude && window.amplitude.options); }; /** * Load the Amplitude library. * * @param {Function} callback */ Amplitude.prototype.load = function (callback) { load('https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.0-min.js', callback); }; /** * Page. * * @param {Page} page */ Amplitude.prototype.page = function (page) { var properties = page.properties(); var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Identify. * * @param {Facade} identify */ Amplitude.prototype.identify = function (identify) { var id = identify.userId(); var traits = identify.traits(); if (id) window.amplitude.setUserId(id); if (traits) window.amplitude.setGlobalUserProperties(traits); }; /** * Track. * * @param {Track} event */ Amplitude.prototype.track = function (track) { var props = track.properties(); var event = track.event(); window.amplitude.logEvent(event, props); }; }); require.register("segmentio-analytics.js-integrations/lib/awesm.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Awesm); user = analytics.user(); // store for later }; /** * Expose `Awesm` integration. */ var Awesm = exports.Integration = integration('awe.sm') .assumesPageview() .readyOnLoad() .global('AWESM') .option('apiKey', '') .option('events', {}); /** * Initialize. * * http://developers.awe.sm/guides/javascript/ * * @param {Object} page */ Awesm.prototype.initialize = function (page) { window.AWESM = { api_key: this.options.apiKey }; this.load(); }; /** * Loaded? * * @return {Boolean} */ Awesm.prototype.loaded = function () { return !! window.AWESM._exists; }; /** * Load. * * @param {Function} callback */ Awesm.prototype.load = function (callback) { var key = this.options.apiKey; load('//widgets.awe.sm/v3/widgets.js?key=' + key + '&async=true', callback); }; /** * Track. * * @param {Track} track */ Awesm.prototype.track = function (track) { var event = track.event(); var goal = this.options.events[event]; if (!goal) return; window.AWESM.convert(goal, track.cents(), null, user.id()); }; }); require.register("segmentio-analytics.js-integrations/lib/awesomatic.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); var noop = function(){}; var onBody = require('on-body'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Awesomatic); user = analytics.user(); // store for later }; /** * Expose `Awesomatic` integration. */ var Awesomatic = exports.Integration = integration('Awesomatic') .assumesPageview() .global('Awesomatic') .global('AwesomaticSettings') .global('AwsmSetup') .global('AwsmTmp') .option('appId', ''); /** * Initialize. * * @param {Object} page */ Awesomatic.prototype.initialize = function (page) { var self = this; var id = user.id(); var options = user.traits(); options.appId = this.options.appId; if (id) options.user_id = id; this.load(function () { window.Awesomatic.initialize(options, function () { self.emit('ready'); // need to wait for initialize to callback }); }); }; /** * Loaded? * * @return {Boolean} */ Awesomatic.prototype.loaded = function () { return is.object(window.Awesomatic); }; /** * Load the Awesomatic library. * * @param {Function} callback */ Awesomatic.prototype.load = function (callback) { var url = 'https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js'; load(url, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/bing-ads.js", function(exports, require, module){ var integration = require('integration'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(Bing); }; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `Bing` */ var Bing = exports.Integration = integration('Bing Ads') .readyOnInitialize() .option('siteId', '') .option('domainId', '') .option('goals', {}); /** * Track. * * @param {Track} track */ Bing.prototype.track = function(track){ var goals = this.options.goals; var traits = track.traits(); var event = track.event(); if (!has.call(goals, event)) return; var goal = goals[event]; return exports.load(goal, track.revenue(), this.options); }; /** * Load conversion. * * @param {Mixed} goal * @param {Number} revenue * @param {String} currency * @return {IFrame} * @api private */ exports.load = function(goal, revenue, options){ var iframe = document.createElement('iframe'); iframe.src = '//flex.msn.com/mstag/tag/' + options.siteId + '/analytics.html' + '?domainId=' + options.domainId + '&revenue=' + revenue || 0 + '&actionid=' + goal; + '&dedup=1' + '&type=1' iframe.width = 1; iframe.height = 1; return iframe; }; }); require.register("segmentio-analytics.js-integrations/lib/bronto.js", function(exports, require, module){ /** * Module dependencies. */ var integration = require('integration'); var Track = require('facade').Track; var load = require('load-script'); var each = require('each'); /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(Bronto); }; /** * Expose `Bronto` integration. */ var Bronto = exports.Integration = integration('Bronto') .readyOnLoad() .global('__bta') .option('siteId', '') .option('host', ''); /** * Initialize. * * http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB * http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB * * @param {Object} page */ Bronto.prototype.initialize = function(page){ this.load(); }; /** * Loaded? * * @return {Boolean} */ Bronto.prototype.loaded = function(){ return this.bta; }; /** * Load the Bronto library. * * @param {Function} fn */ Bronto.prototype.load = function(fn){ var self = this; load('//p.bm23.com/bta.js', function(err){ if (err) return fn(err); var opts = self.options; self.bta = new window.__bta(opts.siteId); if (opts.host) self.bta.setHost(opts.host); fn(); }); }; /** * Track. * * @param {Track} event */ Bronto.prototype.track = function(track){ var revenue = track.revenue(); var event = track.event(); var type = 'number' == typeof revenue ? '$' : 't'; this.bta.addConversionLegacy(type, event, revenue); }; /** * Completed order. * * @param {Track} track * @api private */ Bronto.prototype.completedOrder = function(track){ var products = track.products(); var props = track.properties(); var items = []; // items each(products, function(product){ var track = new Track({ properties: product }); items.push({ item_id: track.id() || track.sku(), desc: product.description || track.name(), quantity: track.quantity(), amount: track.price(), }); }); // add conversion this.bta.addConversion({ order_id: track.orderId(), date: props.date || new Date, items: items }); }; }); require.register("segmentio-analytics.js-integrations/lib/bugherd.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(BugHerd); }; /** * Expose `BugHerd` integration. */ var BugHerd = exports.Integration = integration('BugHerd') .assumesPageview() .readyOnLoad() .global('BugHerdConfig') .global('_bugHerd') .option('apiKey', '') .option('showFeedbackTab', true); /** * Initialize. * * http://support.bugherd.com/home * * @param {Object} page */ BugHerd.prototype.initialize = function (page) { window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }}; this.load(); }; /** * Loaded? * * @return {Boolean} */ BugHerd.prototype.loaded = function () { return !! window._bugHerd; }; /** * Load the BugHerd library. * * @param {Function} callback */ BugHerd.prototype.load = function (callback) { load('//www.bugherd.com/sidebarv2.js?apikey=' + this.options.apiKey, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/bugsnag.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var extend = require('extend'); var load = require('load-script'); var onError = require('on-error'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Bugsnag); }; /** * Expose `Bugsnag` integration. */ var Bugsnag = exports.Integration = integration('Bugsnag') .readyOnLoad() .global('Bugsnag') .option('apiKey', ''); /** * Initialize. * * https://bugsnag.com/docs/notifiers/js * * @param {Object} page */ Bugsnag.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ Bugsnag.prototype.loaded = function () { return is.object(window.Bugsnag); }; /** * Load. * * @param {Function} callback (optional) */ Bugsnag.prototype.load = function (callback) { var apiKey = this.options.apiKey; load('//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js', function(err){ if (err) return callback(err); window.Bugsnag.apiKey = apiKey; callback(); }); }; /** * Identify. * * @param {Identify} identify */ Bugsnag.prototype.identify = function (identify) { window.Bugsnag.metaData = window.Bugsnag.metaData || {}; extend(window.Bugsnag.metaData, identify.traits()); }; }); require.register("segmentio-analytics.js-integrations/lib/chartbeat.js", function(exports, require, module){ var integration = require('integration'); var onBody = require('on-body'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Chartbeat); }; /** * Expose `Chartbeat` integration. */ var Chartbeat = exports.Integration = integration('Chartbeat') .assumesPageview() .readyOnLoad() .global('_sf_async_config') .global('_sf_endpt') .global('pSUPERFLY') .option('domain', '') .option('uid', null); /** * Initialize. * * http://chartbeat.com/docs/configuration_variables/ * * @param {Object} page */ Chartbeat.prototype.initialize = function (page) { window._sf_async_config = this.options; onBody(function () { window._sf_endpt = new Date().getTime(); }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Chartbeat.prototype.loaded = function () { return !! window.pSUPERFLY; }; /** * Load the Chartbeat library. * * http://chartbeat.com/docs/adding_the_code/ * * @param {Function} callback */ Chartbeat.prototype.load = function (callback) { load({ https: 'https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js', http: 'http://static.chartbeat.com/js/chartbeat.js' }, callback); }; /** * Page. * * http://chartbeat.com/docs/handling_virtual_page_changes/ * * @param {Page} page */ Chartbeat.prototype.page = function (page) { var props = page.properties(); var name = page.fullName(); window.pSUPERFLY.virtualPage(props.path, name || props.title); }; }); require.register("segmentio-analytics.js-integrations/lib/churnbee.js", function(exports, require, module){ /** * Module dependencies. */ var push = require('global-queue')('_cbq'); var integration = require('integration'); var load = require('load-script'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Supported events */ var supported = { activation: true, changePlan: true, register: true, refund: true, charge: true, cancel: true, login: true, }; /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(ChurnBee); }; /** * Expose `ChurnBee` integration. */ var ChurnBee = exports.Integration = integration('ChurnBee') .readyOnInitialize() .global('_cbq') .global('ChurnBee') .option('events', {}) .option('apiKey', ''); /** * Initialize. * * https://churnbee.com/docs * * @param {Object} page */ ChurnBee.prototype.initialize = function(page){ push('_setApiKey', this.options.apiKey); this.load(); }; /** * Loaded? * * @return {Boolean} */ ChurnBee.prototype.loaded = function(){ return !! window.ChurnBee; }; /** * Load the ChurnBee library. * * @param {Function} fn */ ChurnBee.prototype.load = function(fn){ load('//api.churnbee.com/cb.js', fn); }; /** * Track. * * @param {Track} event */ ChurnBee.prototype.track = function(track){ var events = this.options.events; var event = track.event(); if (has.call(events, event)) event = events[event]; if (true != supported[event]) return; push(event, track.properties({ revenue: 'amount' })); }; }); require.register("segmentio-analytics.js-integrations/lib/clicktale.js", function(exports, require, module){ var date = require('load-date'); var domify = require('domify'); var each = require('each'); var integration = require('integration'); var is = require('is'); var useHttps = require('use-https'); var load = require('load-script'); var onBody = require('on-body'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(ClickTale); }; /** * Expose `ClickTale` integration. */ var ClickTale = exports.Integration = integration('ClickTale') .assumesPageview() .readyOnLoad() .global('WRInitTime') .global('ClickTale') .global('ClickTaleSetUID') .global('ClickTaleField') .global('ClickTaleEvent') .option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js') .option('httpsCdnUrl', '') .option('projectId', '') .option('recordingRatio', 0.01) .option('partitionId', ''); /** * Initialize. * * http://wiki.clicktale.com/Article/JavaScript_API * * @param {Object} page */ ClickTale.prototype.initialize = function (page) { var options = this.options; window.WRInitTime = date.getTime(); onBody(function (body) { body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">')); }); this.load(function () { window.ClickTale(options.projectId, options.recordingRatio, options.partitionId); }); }; /** * Loaded? * * @return {Boolean} */ ClickTale.prototype.loaded = function () { return is.fn(window.ClickTale); }; /** * Load the ClickTale library. * * @param {Function} callback */ ClickTale.prototype.load = function (callback) { var http = this.options.httpCdnUrl; var https = this.options.httpsCdnUrl; if (useHttps() && !https) return this.debug('https option required'); load({ http: http, https: https }, callback); }; /** * Identify. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField * * @param {Identify} identify */ ClickTale.prototype.identify = function (identify) { var id = identify.userId(); window.ClickTaleSetUID(id); each(identify.traits(), function (key, value) { window.ClickTaleField(key, value); }); }; /** * Track. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent * * @param {Track} track */ ClickTale.prototype.track = function (track) { window.ClickTaleEvent(track.event()); }; }); require.register("segmentio-analytics.js-integrations/lib/clicky.js", function(exports, require, module){ var Identify = require('facade').Identify; var extend = require('extend'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Clicky); user = analytics.user(); // store for later }; /** * Expose `Clicky` integration. */ var Clicky = exports.Integration = integration('Clicky') .assumesPageview() .readyOnLoad() .global('clicky') .global('clicky_site_ids') .global('clicky_custom') .option('siteId', null); /** * Initialize. * * http://clicky.com/help/customization * * @param {Object} page */ Clicky.prototype.initialize = function (page) { window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId]; this.identify(new Identify({ userId: user.id(), traits: user.traits() })); this.load(); }; /** * Loaded? * * @return {Boolean} */ Clicky.prototype.loaded = function () { return is.object(window.clicky); }; /** * Load the Clicky library. * * @param {Function} callback */ Clicky.prototype.load = function (callback) { load('//static.getclicky.com/js', callback); }; /** * Page. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Page} page */ Clicky.prototype.page = function (page) { var properties = page.properties(); var category = page.category(); var name = page.fullName(); window.clicky.log(properties.path, name || properties.title); }; /** * Identify. * * @param {Identify} id (optional) */ Clicky.prototype.identify = function (identify) { window.clicky_custom = window.clicky_custom || {}; window.clicky_custom.session = window.clicky_custom.session || {}; extend(window.clicky_custom.session, identify.traits()); }; /** * Track. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Track} event */ Clicky.prototype.track = function (track) { window.clicky.goal(track.event(), track.revenue()); }; }); require.register("segmentio-analytics.js-integrations/lib/comscore.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Comscore); }; /** * Expose `Comscore` integration. */ var Comscore = exports.Integration = integration('comScore') .assumesPageview() .readyOnLoad() .global('_comscore') .global('COMSCORE') .option('c1', '2') .option('c2', ''); /** * Initialize. * * @param {Object} page */ Comscore.prototype.initialize = function (page) { window._comscore = window._comscore || [this.options]; this.load(); }; /** * Loaded? * * @return {Boolean} */ Comscore.prototype.loaded = function () { return !! window.COMSCORE; }; /** * Load. * * @param {Function} callback */ Comscore.prototype.load = function (callback) { load({ http: 'http://b.scorecardresearch.com/beacon.js', https: 'https://sb.scorecardresearch.com/beacon.js' }, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/crazy-egg.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(CrazyEgg); }; /** * Expose `CrazyEgg` integration. */ var CrazyEgg = exports.Integration = integration('Crazy Egg') .assumesPageview() .readyOnLoad() .global('CE2') .option('accountNumber', ''); /** * Initialize. * * @param {Object} page */ CrazyEgg.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ CrazyEgg.prototype.loaded = function () { return !! window.CE2; }; /** * Load the Crazy Egg library. * * @param {Function} callback */ CrazyEgg.prototype.load = function (callback) { var number = this.options.accountNumber; var path = number.slice(0,4) + '/' + number.slice(4); var cache = Math.floor(new Date().getTime()/3600000); var url = '//dnn506yrbagrg.cloudfront.net/pages/scripts/' + path + '.js?' + cache; load(url, callback); }; }); require.register("segmentio-analytics.js-integrations/lib/curebit.js", function(exports, require, module){ var push = require('global-queue')('_curebitq'); var Identify = require('facade').Identify; var integration = require('integration'); var Track = require('facade').Track; var iso = require('to-iso-string'); var load = require('load-script'); var extend = require('extend'); var clone = require('clone'); var each = require('each'); /** * User reference */ var user; /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(Curebit); user = analytics.user(); }; /** * Expose `Curebit` integration */ var Curebit = exports.Integration = integration('Curebit') .readyOnInitialize() .global('_curebitq') .global('curebit') .option('siteId', '') .option('iframeWidth', 0) .option('iframeHeight', 0) .option('iframeBorder', 0) .option('iframeId', '') .option('responsive', true) .option('device', '') .option('server', 'https://www.curebit.com'); /** * Initialize * * @param {Object} page */ Curebit.prototype.initialize = function(){ push('init', { site_id: this.options.siteId, server: this.options.server }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Curebit.prototype.loaded = function(){ return !! window.curebit; }; /** * Load * * @param {Function} fn * @api private */ Curebit.prototype.load = function(fn){ load('//d2jjzw81hqbuqv.cloudfront.net/assets/api/all-0.6.js', fn); }; /** * Identify. * * http://www.curebit.com/docs/affiliate/registration * * @param {Identify} identify * @api public */ Curebit.prototype.identify = function(identify){ push('register_affiliate', { responsive: this.options.responsive, device: this.options.device, iframe: { width: this.options.iframeWidth, height: this.options.iframeHeight, id: this.options.iframeId, frameborder: this.options.iframeBorder }, affiliate_member: { email: identify.email(), first_name: identify.firstName(), last_name: identify.lastName(), customer_id: identify.userId() }, }); }; /** * Completed order * * https://www.curebit.com/docs/ecommerce/custom * * @param {Track} track * @api private */ Curebit.prototype.completedOrder = function(track){ var orderId = track.orderId(); var products = track.products(); var props = track.properties(); var items = []; // identify var identify = new Identify({ traits: user.traits(), userId: user.id() }); // items each(products, function(product){ var track = new Track({ properties: product }); items.push({ product_id: track.id() || track.sku(), quantity: track.quantity(), image_url: product.image, price: track.price(), title: track.name(), url: product.url, }); }); // transaction push('register_purchase', { order_date: iso(props.date || new Date), order_number: orderId, coupon_code: track.coupon(), subtotal: track.total(), customer_id: identify.userId(), first_name: identify.firstName(), last_name: identify.lastName(), email: identify.email(), items: items }); }; }); require.register("segmentio-analytics.js-integrations/lib/customerio.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var convertDates = require('convert-dates'); var Identify = require('facade').Identify; var integration = require('integration'); var load = require('load-script'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Customerio); user = analytics.user(); // store for later }; /** * Expose `Customerio` integration. */ var Customerio = exports.Integration = integration('Customer.io') .assumesPageview() .readyOnInitialize() .global('_cio') .option('siteId', ''); /** * Initialize. * * http://customer.io/docs/api/javascript.html * * @param {Object} page */ Customerio.prototype.initialize = function (page) { window._cio = window._cio || []; (function() {var a,b,c; a = function (f) {return function () {window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })(); this.load(); }; /** * Loaded? * * @return {Boolean} */ Customerio.prototype.loaded = function () { return !! (window._cio && window._cio.pageHasLoaded); }; /** * Load. * * @param {Function} callback */ Customerio.prototype.load = function (callback) { var script = load('https://assets.customer.io/assets/track.js', callback); script.id = 'cio-tracker'; script.setAttribute('data-site-id', this.options.siteId); }; /** * Identify. * * http://customer.io/docs/api/javascript.html#section-Identify_customers * * @param {Identify} identify */ Customerio.prototype.identify = function (identify) { if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); window._cio.identify(traits); }; /** * Group. * * @param {Group} group */ Customerio.prototype.group = function (group) { var traits = group.traits(); traits = alias(traits, function (trait) { return 'Group ' + trait; }); this.identify(new Identify({ userId: user.id(), traits: traits })); }; /** * Track. * * http://customer.io/docs/api/javascript.html#section-Track_a_custom_event * * @param {Track} track */ Customerio.prototype.track = function (track) { var properties = track.properties(); properties = convertDates(properties, convertDate); window._cio.track(track.event(), properties); }; /** * Convert a date to the format Customer.io supports. * * @param {Date} date * @return {Number} */ function convertDate (date) { return Math.floor(date.getTime() / 1000); } }); require.register("segmentio-analytics.js-integrations/lib/drip.js", function(exports, require, module){ var alias = require('alias'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_dcq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Drip); }; /** * Expose `Drip` integration. */ var Drip = exports.Integration = integration('Drip') .assumesPageview() .readyOnLoad() .global('dc') .global('_dcq') .global('_dcs') .option('account', ''); /** * Initialize. * * @param {Object} page */ Drip.prototype.initialize = function (page) { window._dcq = window._dcq || []; window._dcs = window._dcs || {}; window._dcs.account = this.options.account; this.load(); }; /** * Loaded? * * @return {Boolean} */ Drip.prototype.loaded = function () { return is.object(window.dc); }; /** * Load. * * @param {Function} callback */ Drip.prototype.load = function (callback) { load('//tag.getdrip.com/' + this.options.account + '.js', callback); }; /** * Track. * * @param {Track} track */ Drip.prototype.track = function (track) { var props = track.properties(); var cents = Math.round(track.cents()); props.action = track.event(); if (cents) props.value = cents; delete props.revenue; push('track', props); }; }); require.register("segmentio-analytics.js-integrations/lib/errorception.js", function(exports, require, module){ var callback = require('callback'); var extend = require('extend'); var integration = require('integration'); var load = require('load-script'); var onError = require('on-error'); var push = require('global-queue')('_errs'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Errorception); }; /** * Expose `Errorception` integration. */ var Errorception = exports.Integration = integration('Errorception') .assumesPageview() .readyOnInitialize() .global('_errs') .option('projectId', '') .option('meta', true); /** * Initialize. * * https://github.com/amplitude/Errorception-Javascript * * @param {Object} page */ Errorception.prototype.initialize = function (page) { window._errs = window._errs || [this.options.projectId]; onError(push); this.load(); }; /** * Loaded? * * @return {Boolean} */ Errorception.prototype.loaded = function () { return !! (window._errs && window._errs.push !== Array.prototype.push); }; /** * Load the Errorception library. * * @param {Function} callback */ Errorception.prototype.load = function (callback) { load('//beacon.errorception.com/' + this.options.projectId + '.js', callback); }; /** * Identify. * * http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html * * @param {Object} identify */ Errorception.prototype.identify = function (identify) { if (!this.options.meta) return; var traits = identify.traits(); window._errs = window._errs || []; window._errs.meta = window._errs.meta || {}; extend(window._errs.meta, traits); }; }); require.register("segmentio-analytics.js-integrations/lib/evergage.js", function(exports, require, module){ var each = require('each'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_aaq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Evergage); }; /** * Expose `Evergage` integration.integration. */ var Evergage = exports.Integration = integration('Evergage') .assumesPageview() .readyOnInitialize() .global('_aaq') .option('account', '') .option('dataset', ''); /** * Initialize. * * @param {Object} page */ Evergage.prototype.initialize = function (page) { var account = this.options.account; var dataset = this.options.dataset; window._aaq = window._aaq || []; push('setEvergageAccount', account); push('setDataset', dataset); push('setUseSiteConfig', true); this.load(); }; /** * Loaded? * * @return {Boolean} */ Evergage.prototype.loaded = function () { return !! (window._aaq && window._aaq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Evergage.prototype.load = function (callback) { var account = this.options.account; var dataset = this.options.dataset; var url = '//cdn.evergage.com/beacon/' + account + '/' + dataset + '/scripts/evergage.min.js'; load(url, callback); }; /** * Page. * * @param {Page} page */ Evergage.prototype.page = function (page) { var props = page.properties(); var name = page.name(); if (name) push('namePage', name); each(props, function(key, value) { push('setCustomField', key, value, 'page'); }); window.Evergage.init(true); }; /** * Identify. * * @param {Identify} identify */ Evergage.prototype.identify = function (identify) { var id = identify.userId(); if (!id) return; push('setUser', id); var traits = identify.traits({ email: 'userEmail', name: 'userName' });; each(traits, function (key, value) { push('setUserField', key, value, 'page'); }); }; /** * Group. * * @param {Group} group */ Evergage.prototype.group = function (group) { var props = group.traits(); var id = group.groupId(); if (!id) return; push('setCompany', id); each(props, function(key, value) { push('setAccountField', key, value, 'page'); }); }; /** * Track. * * @param {Track} track */ Evergage.prototype.track = function (track) { push('trackAction', track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/facebook-ads.js", function(exports, require, module){ var load = require('load-pixel')('//www.facebook.com/offsite_event.php'); var integration = require('integration'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(Facebook); }; /** * Expose `load`. */ exports.load = load; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `Facebook` */ var Facebook = exports.Integration = integration('Facebook Ads') .readyOnInitialize() .option('currency', 'USD') .option('events', {}); /** * Track. * * @param {Track} track */ Facebook.prototype.track = function(track){ var events = this.options.events; var traits = track.traits(); var event = track.event(); if (!has.call(events, event)) return; return exports.load({ currency: this.options.currency, value: track.revenue() || 0, id: events[event] }); }; }); require.register("segmentio-analytics.js-integrations/lib/foxmetrics.js", function(exports, require, module){ var push = require('global-queue')('_fxm'); var integration = require('integration'); var Track = require('facade').Track; var callback = require('callback'); var load = require('load-script'); var each = require('each'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(FoxMetrics); }; /** * Expose `FoxMetrics` integration. */ var FoxMetrics = exports.Integration = integration('FoxMetrics') .assumesPageview() .readyOnInitialize() .global('_fxm') .option('appId', ''); /** * Initialize. * * http://foxmetrics.com/documentation/apijavascript * * @param {Object} page */ FoxMetrics.prototype.initialize = function(page){ window._fxm = window._fxm || []; this.load(); }; /** * Loaded? * * @return {Boolean} */ FoxMetrics.prototype.loaded = function(){ return !! (window._fxm && window._fxm.appId); }; /** * Load the FoxMetrics library. * * @param {Function} callback */ FoxMetrics.prototype.load = function(callback){ var id = this.options.appId; load('//d35tca7vmefkrc.cloudfront.net/scripts/' + id + '.js', callback); }; /** * Page. * * @param {Page} page */ FoxMetrics.prototype.page = function(page){ var properties = page.proxy('properties'); var category = page.category(); var name = page.name(); this._category = category; // store for later push( '_fxm.pages.view', properties.title, // title name, // name category, // category properties.url, // url properties.referrer // referrer ); }; /** * Identify. * * @param {Identify} identify */ FoxMetrics.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push( '_fxm.visitor.profile', id, // user id identify.firstName(), // first name identify.lastName(), // last name identify.email(), // email identify.address(), // address undefined, // social undefined, // partners identify.traits() // attributes ); }; /** * Track. * * @param {Track} track */ FoxMetrics.prototype.track = function(track){ var props = track.properties(); var category = this._category || props.category; push(track.event(), category, props); }; /** * Viewed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.viewedProduct = function(track){ ecommerce('productview', track); }; /** * Removed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.removedProduct = function(track){ ecommerce('removecartitem', track); }; /** * Added product. * * @param {Track} track * @api private */ FoxMetrics.prototype.addedProduct = function(track){ ecommerce('cartitem', track); }; /** * Completed Order. * * @param {Track} track * @api private */ FoxMetrics.prototype.completedOrder = function(track){ var orderId = track.orderId(); // transaction push('_fxm.ecommerce.order' , orderId , track.subtotal() , track.shipping() , track.tax() , track.city() , track.state() , track.zip() , track.quantity()); // items each(track.products(), function(product){ var track = new Track({ properties: product }); ecommerce('purchaseitem', track, [ track.quantity(), track.price(), orderId ]); }); }; /** * Track ecommerce `event` with `track` * with optional `arr` to append. * * @param {String} event * @param {Track} track * @param {Array} arr * @api private */ function ecommerce(event, track, arr){ push.apply(null, [ '_fxm.ecommerce.' + event, track.id() || track.sku(), track.name(), track.category() ].concat(arr || [])); }; }); require.register("segmentio-analytics.js-integrations/lib/gauges.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_gauges'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Gauges); }; /** * Expose `Gauges` integration. */ var Gauges = exports.Integration = integration('Gauges') .assumesPageview() .readyOnInitialize() .global('_gauges') .option('siteId', ''); /** * Initialize Gauges. * * http://get.gaug.es/documentation/tracking/ * * @param {Object} page */ Gauges.prototype.initialize = function (page) { window._gauges = window._gauges || []; this.load(); }; /** * Loaded? * * @return {Boolean} */ Gauges.prototype.loaded = function () { return !! (window._gauges && window._gauges.push !== Array.prototype.push); }; /** * Load the Gauges library. * * @param {Function} callback */ Gauges.prototype.load = function (callback) { var id = this.options.siteId; var script = load('//secure.gaug.es/track.js', callback); script.id = 'gauges-tracker'; script.setAttribute('data-site-id', id); }; /** * Page. * * @param {Page} page */ Gauges.prototype.page = function (page) { push('track'); }; }); require.register("segmentio-analytics.js-integrations/lib/get-satisfaction.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); var onBody = require('on-body'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(GetSatisfaction); }; /** * Expose `GetSatisfaction` integration. */ var GetSatisfaction = exports.Integration = integration('Get Satisfaction') .assumesPageview() .readyOnLoad() .global('GSFN') .option('widgetId', ''); /** * Initialize. * * https://console.getsatisfaction.com/start/101022?signup=true#engage * * @param {Object} page */ GetSatisfaction.prototype.initialize = function (page) { var widget = this.options.widgetId; var div = document.createElement('div'); var id = div.id = 'getsat-widget-' + widget; onBody(function (body) { body.appendChild(div); }); // usually the snippet is sync, so wait for it before initializing the tab this.load(function () { window.GSFN.loadWidget(widget, { containerId: id }); }); }; /** * Loaded? * * @return {Boolean} */ GetSatisfaction.prototype.loaded = function () { return !! window.GSFN; }; /** * Load the Get Satisfaction library. * * @param {Function} callback */ GetSatisfaction.prototype.load = function (callback) { load('https://loader.engage.gsfn.us/loader.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/google-analytics.js", function(exports, require, module){ var callback = require('callback'); var canonical = require('canonical'); var each = require('each'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_gaq'); var Track = require('facade').Track; var type = require('type'); var url = require('url'); var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(GA); user = analytics.user(); }; /** * Expose `GA` integration. * * http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867 * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate */ var GA = exports.Integration = integration('Google Analytics') .readyOnLoad() .global('ga') .global('gaplugins') .global('_gaq') .global('GoogleAnalyticsObject') .option('anonymizeIp', false) .option('classic', false) .option('domain', 'none') .option('doubleClick', false) .option('enhancedLinkAttribution', false) .option('ignoreReferrer', null) .option('includeSearch', false) .option('siteSpeedSampleRate', null) .option('trackingId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('sendUserId', false); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ GA.on('construct', function (integration) { if (!integration.options.classic) return; integration.initialize = integration.initializeClassic; integration.load = integration.loadClassic; integration.loaded = integration.loadedClassic; integration.page = integration.pageClassic; integration.track = integration.trackClassic; integration.completedOrder = integration.completedOrderClassic; }); /** * Initialize. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced */ GA.prototype.initialize = function () { var opts = this.options; // setup the tracker globals window.GoogleAnalyticsObject = 'ga'; window.ga = window.ga || function () { window.ga.q = window.ga.q || []; window.ga.q.push(arguments); }; window.ga.l = new Date().getTime(); window.ga('create', opts.trackingId, { cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string siteSpeedSampleRate: opts.siteSpeedSampleRate, allowLinker: true }); // send global id if (this.options.sendUserId && user.id()) { window.ga('set', '&uid', user.id()); } // anonymize after initializing, otherwise a warning is shown // in google analytics debugger if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true); this.load(); }; /** * Loaded? * * @return {Boolean} */ GA.prototype.loaded = function () { return !! window.gaplugins; }; /** * Load the Google Analytics library. * * @param {Function} callback */ GA.prototype.load = function (callback) { load('//www.google-analytics.com/analytics.js', callback); }; /** * Page. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/pages * * @param {Page} page */ GA.prototype.page = function (page) { var category = page.category(); var props = page.properties(); var name = page.fullName(); var track; this._category = category; // store for later window.ga('send', 'pageview', { page: path(props, this.options), title: name || props.title, location: props.url }); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { noninteraction: true }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { noninteraction: true }); } }; /** * Track. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/events * https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference * * @param {Track} event */ GA.prototype.track = function (track, options) { var opts = options || track.options(this.name); var props = track.properties(); var revenue = track.revenue(); var event = track.event(); window.ga('send', 'event', { eventAction: event, eventCategory: this._category || props.category || 'All', eventLabel: props.label, eventValue: formatValue(props.value || revenue), nonInteraction: props.noninteraction || opts.noninteraction }); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce * * @param {Track} track * @api private */ GA.prototype.completedOrder = function(track){ var orderId = track.orderId(); var products = track.products(); var props = track.properties(); // orderId is required. if (!orderId) return; // require ecommerce if (!this.ecommerce) { window.ga('require', 'ecommerce', 'ecommerce.js'); this.ecommerce = true; } // add transaction window.ga('ecommerce:addTransaction', { affiliation: props.affiliation, shipping: track.shipping(), revenue: track.total(), tax: track.tax(), id: orderId }); // add products each(products, function(product){ var track = new Track({ properties: product }); window.ga('ecommerce:addItem', { category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), sku: track.sku(), id: orderId }); }); // send window.ga('ecommerce:send'); }; /** * Initialize (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration */ GA.prototype.initializeClassic = function () { var opts = this.options; var anonymize = opts.anonymizeIp; var db = opts.doubleClick; var domain = opts.domain; var enhanced = opts.enhancedLinkAttribution; var ignore = opts.ignoreReferrer; var sample = opts.siteSpeedSampleRate; window._gaq = window._gaq || []; push('_setAccount', opts.trackingId); push('_setAllowLinker', true); if (anonymize) push('_gat._anonymizeIp'); if (domain) push('_setDomainName', domain); if (sample) push('_setSiteSpeedSampleRate', sample); if (enhanced) { var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:'; var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js'; push('_require', 'inpage_linkid', pluginUrl); } if (ignore) { if (!is.array(ignore)) ignore = [ignore]; each(ignore, function (domain) { push('_addIgnoredRef', domain); }); } this.load(); }; /** * Loaded? (classic) * * @return {Boolean} */ GA.prototype.loadedClassic = function () { return !! (window._gaq && window._gaq.push !== Array.prototype.push); }; /** * Load the classic Google Analytics library. * * @param {Function} callback */ GA.prototype.loadClassic = function (callback) { if (this.options.doubleClick) { load('//stats.g.doubleclick.net/dc.js', callback); } else { load({ http: 'http://www.google-analytics.com/ga.js', https: 'https://ssl.google-analytics.com/ga.js' }, callback); } }; /** * Page (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration * * @param {Page} page */ GA.prototype.pageClassic = function (page) { var opts = page.options(this.name); var category = page.category(); var props = page.properties(); var name = page.fullName(); var track; push('_trackPageview', path(props, this.options)); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { noninteraction: true }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { noninteraction: true }); } }; /** * Track (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking * * @param {Track} track */ GA.prototype.trackClassic = function (track, options) { var opts = options || track.options(this.name); var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var category = this._category || props.category || 'All'; var label = props.label; var value = formatValue(revenue || props.value); var noninteraction = props.noninteraction || opts.noninteraction; push('_trackEvent', category, event, label, value, noninteraction); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce * * @param {Track} track * @api private */ GA.prototype.completedOrderClassic = function(track){ var orderId = track.orderId(); var products = track.products() || []; var props = track.properties(); // required if (!orderId) return; // add transaction push('_addTrans' , orderId , props.affiliation , track.total() , track.tax() , track.shipping() , track.city() , track.state() , track.country()); // add items each(products, function(product){ var track = new Track({ properties: product }); push('_addItem' , orderId , track.sku() , track.name() , track.category() , track.price() , track.quantity()); }) // send push('_trackTrans'); }; /** * Return the path based on `properties` and `options`. * * @param {Object} properties * @param {Object} options */ function path (properties, options) { if (!properties) return; var str = properties.path; if (options.includeSearch && properties.search) str += properties.search; return str; } /** * Format the value property to Google's liking. * * @param {Number} value * @return {Number} */ function formatValue (value) { if (!value || value < 0) return 0; return Math.round(value); } }); require.register("segmentio-analytics.js-integrations/lib/google-tag-manager.js", function(exports, require, module){ var push = require('global-queue')('dataLayer', { wrap: false }); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(GTM); }; /** * Expose `GTM` */ var GTM = exports.Integration = integration('Google Tag Manager') .assumesPageview() .readyOnLoad() .global('dataLayer') .global('google_tag_manager') .option('containerId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) /** * Initialize * * https://developers.google.com/tag-manager * * @param {Object} page */ GTM.prototype.initialize = function(){ this.load(); }; /** * Loaded * * @return {Boolean} */ GTM.prototype.loaded = function(){ return !! (window.dataLayer && [].push != window.dataLayer.push); }; /** * Load. * * @param {Function} fn */ GTM.prototype.load = function(fn){ var id = this.options.containerId; push({ 'gtm.start': +new Date, event: 'gtm.js' }); load('//www.googletagmanager.com/gtm.js?id=' + id + '&l=dataLayer', fn); }; /** * Page. * * @param {Page} page * @api public */ GTM.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; var track; // all if (opts.trackAllPages) { this.track(page.track()); } // categorized if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * https://developers.google.com/tag-manager/devguide#events * * @param {Track} track * @api public */ GTM.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); push(props); }; }); require.register("segmentio-analytics.js-integrations/lib/gosquared.js", function(exports, require, module){ var Identify = require('facade').Identify; var Track = require('facade').Track; var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var onBody = require('on-body'); var each = require('each'); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(GoSquared); user = analytics.user(); // store reference for later }; /** * Expose `GoSquared` integration. */ var GoSquared = exports.Integration = integration('GoSquared') .assumesPageview() .readyOnLoad() .global('_gs') .option('siteToken', '') .option('anonymizeIP', false) .option('cookieDomain', null) .option('useCookies', true) .option('trackHash', false) .option('trackLocal', false) .option('trackParams', true); /** * Initialize. * * https://www.gosquared.com/developer/tracker * Options: https://www.gosquared.com/developer/tracker/configuration * * @param {Object} page */ GoSquared.prototype.initialize = function (page) { var self = this; var options = this.options; push(options.siteToken); each(options, function(name, value){ if ('siteToken' == name) return; if (null == value) return; push('set', name, value); }); self.identify(new Identify({ traits: user.traits(), userId: user.id() })); self.load(); }; /** * Loaded? (checks if the tracker version is set) * * @return {Boolean} */ GoSquared.prototype.loaded = function () { return !! (window._gs && window._gs.v); }; /** * Load the GoSquared library. * * @param {Function} callback */ GoSquared.prototype.load = function (callback) { load('//d1l6p2sc9645hc.cloudfront.net/tracker.js', callback); }; /** * Page. * * https://www.gosquared.com/developer/tracker/pageviews * * @param {Page} page */ GoSquared.prototype.page = function (page) { var props = page.properties(); var name = page.fullName(); push('track', props.path, name || props.title) }; /** * Identify. * * https://www.gosquared.com/developer/tracker/tagging * * @param {Identify} identify */ GoSquared.prototype.identify = function (identify) { var traits = identify.traits({ userId: 'userID' }); var username = identify.username(); var email = identify.email(); var id = identify.userId(); if (id) push('set', 'visitorID', id); var name = email || username || id; if (name) push('set', 'visitorName', name); push('set', 'visitor', traits); }; /** * Track. * * https://www.gosquared.com/developer/tracker/events * * @param {Track} track */ GoSquared.prototype.track = function (track) { push('event', track.event(), track.properties()); }; /** * Checked out. * * @param {Track} track * @api private */ GoSquared.prototype.completedOrder = function(track){ var products = track.products(); var items = []; each(products, function(product){ var track = new Track({ properties: product }); items.push({ category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), }); }) push('transaction', track.orderId(), { revenue: track.total(), track: true }, items); }; /** * Push to `_gs.q`. * * @param {...} args * @api private */ function push(){ var _gs = window._gs = window._gs || function(){ (_gs.q = _gs.q || []).push(arguments); }; _gs.apply(null, arguments); } }); require.register("segmentio-analytics.js-integrations/lib/heap.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Heap); }; /** * Expose `Heap` integration. */ var Heap = exports.Integration = integration('Heap') .assumesPageview() .readyOnInitialize() .global('heap') .global('_heapid') .option('apiKey', ''); /** * Initialize. * * https://heapanalytics.com/docs#installWeb * * @param {Object} page */ Heap.prototype.initialize = function (page) { window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)));};},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f]);}; window.heap.load(this.options.apiKey); this.load(); }; /** * Loaded? * * @return {Boolean} */ Heap.prototype.loaded = function () { return (window.heap && window.heap.appid); }; /** * Load the Heap library. * * @param {Function} callback */ Heap.prototype.load = function (callback) { load('//d36lvucg9kzous.cloudfront.net', callback); }; /** * Identify. * * https://heapanalytics.com/docs#identify * * @param {Identify} identify */ Heap.prototype.identify = function (identify) { var traits = identify.traits(); var username = identify.username(); var id = identify.userId(); var handle = username || id; if (handle) traits.handle = handle; delete traits.username; window.heap.identify(traits); }; /** * Track. * * https://heapanalytics.com/docs#track * * @param {Track} track */ Heap.prototype.track = function (track) { window.heap.track(track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/hittail.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(HitTail); }; /** * Expose `HitTail` integration. */ var HitTail = exports.Integration = integration('HitTail') .assumesPageview() .readyOnLoad() .global('htk') .option('siteId', ''); /** * Initialize. * * @param {Object} page */ HitTail.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ HitTail.prototype.loaded = function () { return is.fn(window.htk); }; /** * Load the HitTail library. * * @param {Function} callback */ HitTail.prototype.load = function (callback) { var id = this.options.siteId; load('//' + id + '.hittail.com/mlt.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/hubspot.js", function(exports, require, module){ var callback = require('callback'); var convert = require('convert-dates'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_hsq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(HubSpot); }; /** * Expose `HubSpot` integration. */ var HubSpot = exports.Integration = integration('HubSpot') .assumesPageview() .readyOnInitialize() .global('_hsq') .option('portalId', null); /** * Initialize. * * @param {Object} page */ HubSpot.prototype.initialize = function (page) { window._hsq = []; this.load(); }; /** * Loaded? * * @return {Boolean} */ HubSpot.prototype.loaded = function () { return !! (window._hsq && window._hsq.push !== Array.prototype.push); }; /** * Load the HubSpot library. * * @param {Function} fn */ HubSpot.prototype.load = function (fn) { if (document.getElementById('hs-analytics')) return callback.async(fn); var id = this.options.portalId; var cache = Math.ceil(new Date() / 300000) * 300000; var url = 'https://js.hs-analytics.net/analytics/' + cache + '/' + id + '.js'; var script = load(url, fn); script.id = 'hs-analytics'; }; /** * Page. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ HubSpot.prototype.page = function (page) { push('_trackPageview'); }; /** * Identify. * * @param {Identify} identify */ HubSpot.prototype.identify = function (identify) { if (!identify.email()) return; var traits = identify.traits(); traits = convertDates(traits); push('identify', traits); }; /** * Track. * * @param {Track} track */ HubSpot.prototype.track = function (track) { var props = track.properties(); props = convertDates(props); push('trackEvent', track.event(), props); }; /** * Convert all the dates in the HubSpot properties to millisecond times * * @param {Object} properties */ function convertDates (properties) { return convert(properties, function (date) { return date.getTime(); }); } }); require.register("segmentio-analytics.js-integrations/lib/improvely.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Improvely); }; /** * Expose `Improvely` integration. */ var Improvely = exports.Integration = integration('Improvely') .assumesPageview() .readyOnInitialize() .global('_improvely') .global('improvely') .option('domain', '') .option('projectId', null); /** * Initialize. * * http://www.improvely.com/docs/landing-page-code * * @param {Object} page */ Improvely.prototype.initialize = function (page) { window._improvely = []; window.improvely = {init: function (e, t) { window._improvely.push(["init", e, t]); }, goal: function (e) { window._improvely.push(["goal", e]); }, label: function (e) { window._improvely.push(["label", e]); } }; var domain = this.options.domain; var id = this.options.projectId; window.improvely.init(domain, id); this.load(); }; /** * Loaded? * * @return {Boolean} */ Improvely.prototype.loaded = function () { return !! (window.improvely && window.improvely.identify); }; /** * Load the Improvely library. * * @param {Function} callback */ Improvely.prototype.load = function (callback) { var domain = this.options.domain; load('//' + domain + '.iljmp.com/improvely.js', callback); }; /** * Identify. * * http://www.improvely.com/docs/labeling-visitors * * @param {Identify} identify */ Improvely.prototype.identify = function (identify) { var id = identify.userId(); if (id) window.improvely.label(id); }; /** * Track. * * http://www.improvely.com/docs/conversion-code * * @param {Track} track */ Improvely.prototype.track = function (track) { var props = track.properties({ revenue: 'amount' }); props.type = track.event(); window.improvely.goal(props); }; }); require.register("segmentio-analytics.js-integrations/lib/inspectlet.js", function(exports, require, module){ var integration = require('integration'); var alias = require('alias'); var clone = require('clone'); var load = require('load-script'); var push = require('global-queue')('__insp'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Inspectlet); }; /** * Expose `Inspectlet` integration. */ var Inspectlet = exports.Integration = integration('Inspectlet') .assumesPageview() .readyOnLoad() .global('__insp') .global('__insp_') .option('wid', ''); /** * Initialize. * * https://www.inspectlet.com/dashboard/embedcode/1492461759/initial * * @param {Object} page */ Inspectlet.prototype.initialize = function (page) { push('wid', this.options.wid); this.load(); }; /** * Loaded? * * @return {Boolean} */ Inspectlet.prototype.loaded = function () { return !! window.__insp_; }; /** * Load the Inspectlet library. * * @param {Function} callback */ Inspectlet.prototype.load = function (callback) { load('//www.inspectlet.com/inspectlet.js', callback); }; /** * Track. * * http://www.inspectlet.com/docs/tags * * @param {Track} track */ Inspectlet.prototype.track = function (track) { push('tagSession', track.event()); }; }); require.register("segmentio-analytics.js-integrations/lib/intercom.js", function(exports, require, module){ var alias = require('alias'); var convertDates = require('convert-dates'); var integration = require('integration'); var each = require('each'); var is = require('is'); var isEmail = require('is-email'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Intercom); }; /** * Expose `Intercom` integration. */ var Intercom = exports.Integration = integration('Intercom') .assumesPageview() .readyOnLoad() .global('Intercom') .option('activator', '#IntercomDefaultWidget') .option('appId', '') .option('inbox', false); /** * Initialize. * * http://docs.intercom.io/ * http://docs.intercom.io/#IntercomJS * * @param {Object} page */ Intercom.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ Intercom.prototype.loaded = function () { return is.fn(window.Intercom); }; /** * Load the Intercom library. * * @param {Function} callback */ Intercom.prototype.load = function (callback) { load('https://static.intercomcdn.com/intercom.v1.js', callback); }; /** * Identify. * * http://docs.intercom.io/#IntercomJS * * @param {Identify} identify */ Intercom.prototype.identify = function (identify) { var traits = identify.traits({ userId: 'user_id' }); var opts = identify.options(this.name); var companyCreated = identify.companyCreated(); var created = identify.created(); var email = identify.email(); var name = identify.name(); var id = identify.userId(); if (!id && !traits.email) return; // one is required traits.app_id = this.options.appId; // name if (name) traits.name = name; // handle dates if (companyCreated) traits.company.created = companyCreated; if (created) traits.created = created; // convert dates traits = convertDates(traits, formatDate); traits = alias(traits, { created: 'created_at'}); // company if (traits.company) { traits.company = alias(traits.company, { created: 'created_at' }); } // handle options if (opts.increments) traits.increments = opts.increments; if (opts.userHash) traits.user_hash = opts.userHash; if (opts.user_hash) traits.user_hash = opts.user_hash; if (this.options.inbox) { traits.widget = { activator: this.options.activator }; } var method = this._id !== id ? 'boot': 'update'; this._id = id; // cache for next time window.Intercom(method, traits); }; /** * Group. * * @param {Group} group */ Intercom.prototype.group = function (group) { var props = group.properties(); var id = group.groupId(); if (id) props.id = id; window.Intercom('update', { company: props }); }; /** * Track. * * @param {Track} track */ Intercom.prototype.track = function(track){ window.Intercom('trackUserEvent', track.event(), track.traits()); }; /** * Format a date to Intercom's liking. * * @param {Date} date * @return {Number} */ function formatDate (date) { return Math.floor(date / 1000); } }); require.register("segmentio-analytics.js-integrations/lib/keen-io.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Keen); }; /** * Expose `Keen IO` integration. */ var Keen = exports.Integration = integration('Keen IO') .readyOnInitialize() .global('Keen') .option('projectId', '') .option('readKey', '') .option('writeKey', '') .option('trackNamedPages', true) .option('trackAllPages', false) .option('trackCategorizedPages', true); /** * Initialize. * * https://keen.io/docs/ */ Keen.prototype.initialize = function () { var options = this.options; window.Keen = window.Keen||{configure:function(e){this._cf=e;},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i]);},setGlobalProperties:function(e){this._gp=e;},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e);}}; window.Keen.configure({ projectId: options.projectId, writeKey: options.writeKey, readKey: options.readKey }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Keen.prototype.loaded = function () { return !! (window.Keen && window.Keen.Base64); }; /** * Load the Keen IO library. * * @param {Function} callback */ Keen.prototype.load = function (callback) { load('//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js', callback); }; /** * Page. * * @param {Page} page */ Keen.prototype.page = function (page) { var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * TODO: migrate from old `userId` to simpler `id` * * @param {Identify} identify */ Keen.prototype.identify = function (identify) { var traits = identify.traits(); var id = identify.userId(); var user = {}; if (id) user.userId = id; if (traits) user.traits = traits; window.Keen.setGlobalProperties(function() { return { user: user }; }); }; /** * Track. * * @param {Track} track */ Keen.prototype.track = function (track) { window.Keen.addEvent(track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/kissmetrics.js", function(exports, require, module){ var alias = require('alias'); var Batch = require('batch'); var callback = require('callback'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_kmq'); var Track = require('facade').Track; var each = require('each'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(KISSmetrics); }; /** * Expose `KISSmetrics` integration. */ var KISSmetrics = exports.Integration = integration('KISSmetrics') .assumesPageview() .readyOnInitialize() .global('_kmq') .global('KM') .global('_kmil') .option('apiKey', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * http://support.kissmetrics.com/apis/javascript * * @param {Object} page */ KISSmetrics.prototype.initialize = function (page) { window._kmq = []; this.load(); }; /** * Loaded? * * @return {Boolean} */ KISSmetrics.prototype.loaded = function () { return is.object(window.KM); }; /** * Load. * * @param {Function} callback */ KISSmetrics.prototype.load = function (callback) { var key = this.options.apiKey; var useless = '//i.kissmetrics.com/i.js'; var library = '//doug1izaerwt3.cloudfront.net/' + key + '.1.js'; new Batch() .push(function (done) { load(useless, done); }) // :) .push(function (done) { load(library, done); }) .end(callback); }; /** * Page. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ KISSmetrics.prototype.page = function (page) { var category = page.category(); var name = page.fullName(); var opts = this.options; // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * @param {Identify} identify */ KISSmetrics.prototype.identify = function (identify) { var traits = identify.traits(); var id = identify.userId(); if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {Track} track */ KISSmetrics.prototype.track = function (track) { var props = track.properties({ revenue: 'Billing Amount' }); push('record', track.event(), props); }; /** * Alias. * * @param {Alias} to */ KISSmetrics.prototype.alias = function (alias) { push('alias', alias.to(), alias.from()); }; /** * Viewed product. * * @param {Track} track * @api private */ KISSmetrics.prototype.viewedProduct = function(track){ push('record', 'Product Viewed', toProduct(track)); }; /** * Product added. * * @param {Track} track * @api private */ KISSmetrics.prototype.addedProduct = function(track){ push('record', 'Product Added', toProduct(track)); }; /** * Completed order. * * @param {Track} track * @api private */ KISSmetrics.prototype.completedOrder = function(track){ var orderId = track.orderId(); var products = track.products(); // transaction push('record', 'Purchased', { 'Order ID': track.orderId(), 'Order Total': track.total() }); // items window._kmq.push(function(){ var km = window.KM; each(products, function(product, i){ var track = new Track({ properties: product }); var item = toProduct(track); item['Order ID'] = orderId; item._t = km.ts() + i; item._d = 1; km.set(item); }); }); }; /** * Get a product from the given `track`. * * @param {Track} track * @return {Object} * @api private */ function toProduct(track){ return { Quantity: track.quantity(), Price: track.price(), Name: track.name(), SKU: track.sku() }; } }); require.register("segmentio-analytics.js-integrations/lib/klaviyo.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_learnq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Klaviyo); }; /** * Expose `Klaviyo` integration. */ var Klaviyo = exports.Integration = integration('Klaviyo') .assumesPageview() .readyOnInitialize() .global('_learnq') .option('apiKey', ''); /** * Initialize. * * https://www.klaviyo.com/docs/getting-started * * @param {Object} page */ Klaviyo.prototype.initialize = function (page) { push('account', this.options.apiKey); this.load(); }; /** * Loaded? * * @return {Boolean} */ Klaviyo.prototype.loaded = function () { return !! (window._learnq && window._learnq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Klaviyo.prototype.load = function (callback) { load('//a.klaviyo.com/media/js/learnmarklet.js', callback); }; /** * Trait aliases. */ var aliases = { id: '$id', email: '$email', firstName: '$first_name', lastName: '$last_name', phone: '$phone_number', title: '$title' }; /** * Identify. * * @param {Identify} identify */ Klaviyo.prototype.identify = function (identify) { var traits = identify.traits(aliases); if (!traits.$id && !traits.$email) return; push('identify', traits); }; /** * Group. * * @param {Group} group */ Klaviyo.prototype.group = function (group) { var props = group.properties(); if (!props.name) return; push('identify', { $organization: props.name }); }; /** * Track. * * @param {Track} track */ Klaviyo.prototype.track = function (track) { push('track', track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/leadlander.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(LeadLander); }; /** * Expose `LeadLander` integration. */ var LeadLander = exports.Integration = integration('LeadLander') .assumesPageview() .readyOnLoad() .global('llactid') .global('trackalyzer') .option('accountId', null); /** * Initialize. * * @param {Object} page */ LeadLander.prototype.initialize = function (page) { window.llactid = this.options.accountId; this.load(); }; /** * Loaded? * * @return {Boolean} */ LeadLander.prototype.loaded = function () { return !! window.trackalyzer; }; /** * Load. * * @param {Function} callback */ LeadLander.prototype.load = function (callback) { load('http://t6.trackalyzer.com/trackalyze-nodoc.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/livechat.js", function(exports, require, module){ var each = require('each'); var integration = require('integration'); var load = require('load-script'); var clone = require('clone'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(LiveChat); }; /** * Expose `LiveChat` integration. */ var LiveChat = exports.Integration = integration('LiveChat') .assumesPageview() .readyOnLoad() .global('__lc') .option('group', 0) .option('license', ''); /** * Initialize. * * http://www.livechatinc.com/api/javascript-api * * @param {Object} page */ LiveChat.prototype.initialize = function (page) { window.__lc = clone(this.options); this.isLoaded = false; this.load(); }; /** * Loaded? * * @return {Boolean} */ LiveChat.prototype.loaded = function () { return this.isLoaded; }; /** * Load. * * @param {Function} callback */ LiveChat.prototype.load = function (callback) { var self = this; load('//cdn.livechatinc.com/tracking.js', function(err){ if (err) return callback(err); self.isLoaded = true; callback(); }); }; /** * Identify. * * @param {Identify} identify */ LiveChat.prototype.identify = function (identify) { var traits = identify.traits({ userId: 'User ID' }); window.LC_API.set_custom_variables(convert(traits)); }; /** * Convert a traits object into the format LiveChat requires. * * @param {Object} traits * @return {Array} */ function convert (traits) { var arr = []; each(traits, function (key, value) { arr.push({ name: key, value: value }); }); return arr; } }); require.register("segmentio-analytics.js-integrations/lib/lucky-orange.js", function(exports, require, module){ var Identify = require('facade').Identify; var integration = require('integration'); var load = require('load-script'); /** * User ref */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(LuckyOrange); user = analytics.user(); }; /** * Expose `LuckyOrange` integration. */ var LuckyOrange = exports.Integration = integration('Lucky Orange') .assumesPageview() .readyOnLoad() .global('_loq') .global('__wtw_watcher_added') .global('__wtw_lucky_site_id') .global('__wtw_lucky_is_segment_io') .global('__wtw_custom_user_data') .option('siteId', null); /** * Initialize. * * @param {Object} page */ LuckyOrange.prototype.initialize = function (page) { window._loq || (window._loq = []); window.__wtw_lucky_site_id = this.options.siteId; this.identify(new Identify({ traits: user.traits(), userId: user.id() })); this.load(); }; /** * Loaded? * * @return {Boolean} */ LuckyOrange.prototype.loaded = function () { return !! window.__wtw_watcher_added; }; /** * Load. * * @param {Function} callback */ LuckyOrange.prototype.load = function (callback) { var cache = Math.floor(new Date().getTime() / 60000); load({ http: 'http://www.luckyorange.com/w.js?' + cache, https: 'https://ssl.luckyorange.com/w.js?' + cache }, callback); }; /** * Identify. * * @param {Identify} identify */ LuckyOrange.prototype.identify = function (identify) { var traits = window.__wtw_custom_user_data = identify.traits(); var email = identify.email(); var name = identify.name(); if (name) traits.name = name; if (email) traits.email = email; }; }); require.register("segmentio-analytics.js-integrations/lib/lytics.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Lytics); }; /** * Expose `Lytics` integration. */ var Lytics = exports.Integration = integration('Lytics') .readyOnInitialize() .global('jstag') .option('cid', '') .option('cookie', 'seerid') .option('delay', 2000) .option('sessionTimeout', 1800) .option('url', '//c.lytics.io'); /** * Options aliases. */ var aliases = { sessionTimeout: 'sessecs' }; /** * Initialize. * * http://admin.lytics.io/doc#jstag * * @param {Object} page */ Lytics.prototype.initialize = function (page) { var options = alias(this.options, aliases); window.jstag = (function () {var t = {_q: [], _c: options, ts: (new Date()).getTime() }; t.send = function() {this._q.push([ 'ready', 'send', Array.prototype.slice.call(arguments) ]); return this; }; return t; })(); this.load(); }; /** * Loaded? * * @return {Boolean} */ Lytics.prototype.loaded = function () { return !! (window.jstag && window.jstag.bind); }; /** * Load the Lytics library. * * @param {Function} callback */ Lytics.prototype.load = function (callback) { load('//c.lytics.io/static/io.min.js', callback); }; /** * Page. * * @param {Page} page */ Lytics.prototype.page = function (page) { window.jstag.send(page.properties()); }; /** * Idenfity. * * @param {Identify} identify */ Lytics.prototype.identify = function (identify) { var traits = identify.traits({ userId: '_uid' }); window.jstag.send(traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Lytics.prototype.track = function (track) { var props = track.properties(); props._e = track.event(); window.jstag.send(props); }; }); require.register("segmentio-analytics.js-integrations/lib/mixpanel.js", function(exports, require, module){ var alias = require('alias'); var clone = require('clone'); var dates = require('convert-dates'); var integration = require('integration'); var iso = require('to-iso-string'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Mixpanel); }; /** * Expose `Mixpanel` integration. */ var Mixpanel = exports.Integration = integration('Mixpanel') .readyOnLoad() .global('mixpanel') .option('cookieName', '') .option('nameTag', true) .option('pageview', false) .option('people', false) .option('token', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Options aliases. */ var optionsAliases = { cookieName: 'cookie_name' }; /** * Initialize. * * https://mixpanel.com/help/reference/javascript#installing * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init */ Mixpanel.prototype.initialize = function () { (function (c, a) {window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function (b, c, f) {function d(a, b) {var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function () {a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []); var options = alias(this.options, optionsAliases); window.mixpanel.init(options.token, options); this.load(); }; /** * Loaded? * * @return {Boolean} */ Mixpanel.prototype.loaded = function () { return !! (window.mixpanel && window.mixpanel.config); }; /** * Load. * * @param {Function} callback */ Mixpanel.prototype.load = function (callback) { load('//cdn.mxpnl.com/libs/mixpanel-2.2.min.js', callback); }; /** * Page. * * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ Mixpanel.prototype.page = function (page) { var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Trait aliases. */ var traitAliases = { created: '$created', email: '$email', firstName: '$first_name', lastName: '$last_name', lastSeen: '$last_seen', name: '$name', username: '$username', phone: '$phone' }; /** * Identify. * * https://mixpanel.com/help/reference/javascript#super-properties * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript#storing-user-profiles * * @param {Identify} identify */ Mixpanel.prototype.identify = function (identify) { var username = identify.username(); var email = identify.email(); var id = identify.userId(); // id if (id) window.mixpanel.identify(id); // name tag var nametag = email || username || id; if (nametag) window.mixpanel.name_tag(nametag); // traits traits = identify.traits(traitAliases); window.mixpanel.register(traits); if (this.options.people) window.mixpanel.people.set(traits); }; /** * Track. * * https://mixpanel.com/help/reference/javascript#sending-events * https://mixpanel.com/help/reference/javascript#tracking-revenue * * @param {Track} track */ Mixpanel.prototype.track = function (track) { var props = track.properties(); var revenue = track.revenue(); props = dates(props, iso); window.mixpanel.track(track.event(), props); if (revenue && this.options.people) { window.mixpanel.people.track_charge(revenue); } }; /** * Alias. * * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias * * @param {Alias} alias */ Mixpanel.prototype.alias = function (alias) { var mp = window.mixpanel; var to = alias.to(); if (mp.get_distinct_id && mp.get_distinct_id() === to) return; // HACK: internal mixpanel API to ensure we don't overwrite if (mp.get_property && mp.get_property('$people_distinct_id') === to) return; // although undocumented, mixpanel takes an optional original id mp.alias(to, alias.from()); }; }); require.register("segmentio-analytics.js-integrations/lib/mojn.js", function(exports, require, module){ /** * Module dependencies. */ var integration = require('integration'); var load = require('load-script'); var is = require('is'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Mojn); }; /** * Expose `Mojn` */ var Mojn = exports.Integration = integration('Mojn') .option('customerCode', '') .global('_agTrack') .readyOnInitialize(); /** * Initialize. * * @param {Object} page */ Mojn.prototype.initialize = function(){ window._agTrack = window._agTrack || []; window._agTrack.push({ cid: this.options.customerCode }); this.load(); }; /** * Load the Mojn script. * * @param {Function} fn */ Mojn.prototype.load = function(fn) { load('https://track.idtargeting.com/' + this.options.customerCode + '/track.js', fn); }; /** * Loaded? * * @return {Boolean} */ Mojn.prototype.loaded = function () { return is.object(window._agTrack); }; /** * Identify. * * @param {Identify} identify */ Mojn.prototype.identify = function(identify) { var email = identify.email(); if (!email) return; var img = new Image(); img.src = '//matcher.idtargeting.com/analytics.gif?cid=' + this.options.customerCode + '&_mjnctid='+email; img.width = 1; img.height = 1; return img; }; /** * Track. * * @param {Track} event */ Mojn.prototype.track = function(track) { var properties = track.properties(); var revenue = properties.revenue; var currency = properties.currency || ''; var conv = currency + revenue; if (!revenue) return; window._agTrack.push({ conv: conv }); return conv; }; }); require.register("segmentio-analytics.js-integrations/lib/mouseflow.js", function(exports, require, module){ var push = require('global-queue')('_mfq'); var integration = require('integration'); var load = require('load-script'); var each = require('each'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(Mouseflow); }; /** * Expose `Mouseflow` */ var Mouseflow = exports.Integration = integration('Mouseflow') .assumesPageview() .readyOnLoad() .global('mouseflow') .global('_mfq') .option('apiKey', '') .option('mouseflowHtmlDelay', 0); /** * Iniitalize * * @param {Object} page */ Mouseflow.prototype.initialize = function(page){ this.load(); }; /** * Loaded? * * @return {Boolean} */ Mouseflow.prototype.loaded = function(){ return !! (window._mfq && [].push != window._mfq.push); }; /** * Load mouseflow. * * @param {Function} fn */ Mouseflow.prototype.load = function(fn){ var apiKey = this.options.apiKey; window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay; load('//cdn.mouseflow.com/projects/' + apiKey + '.js', fn); }; /** * Page. * * //mouseflow.zendesk.com/entries/22528817-Single-page-websites * * @param {Page} page */ Mouseflow.prototype.page = function(page){ if (!window.mouseflow) return; if ('function' != typeof mouseflow.newPageView) return; mouseflow.newPageView(); }; /** * Identify. * * //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Identify} identify */ Mouseflow.prototype.identify = function(identify){ set(identify.traits()); }; /** * Track. * * //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Track} track */ Mouseflow.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); set(props); }; /** * Push the given `hash`. * * @param {Object} hash */ function set(hash){ each(hash, function(k, v){ push('setVariable', k, v); }); } }); require.register("segmentio-analytics.js-integrations/lib/mousestats.js", function(exports, require, module){ var each = require('each'); var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(MouseStats); }; /** * Expose `MouseStats` integration. */ var MouseStats = exports.Integration = integration('MouseStats') .assumesPageview() .readyOnLoad() .global('msaa') .option('accountNumber', ''); /** * Initialize. * * http://www.mousestats.com/docs/pages/allpages * * @param {Object} page */ MouseStats.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ MouseStats.prototype.loaded = function () { return is.fn(window.msaa); }; /** * Load. * * @param {Function} callback */ MouseStats.prototype.load = function (callback) { var number = this.options.accountNumber; var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number; var cache = Math.floor(new Date().getTime() / 60000); var partial = '.mousestats.com/js/' + path + '.js?' + cache; var http = 'http://www2' + partial; var https = 'https://ssl' + partial; load({ http: http, https: https }, callback); }; /** * Identify. * * http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks * * @param {Identify} identify */ MouseStats.prototype.identify = function (identify) { each(identify.traits(), function (key, value) { window.MouseStatsVisitorPlaybacks.customVariable(key, value); }); }; }); require.register("segmentio-analytics.js-integrations/lib/olark.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var https = require('use-https'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Olark); }; /** * Expose `Olark` integration. */ var Olark = exports.Integration = integration('Olark') .assumesPageview() .readyOnInitialize() .global('olark') .option('identify', true) .option('page', true) .option('siteId', '') .option('track', false); /** * Initialize. * * http://www.olark.com/documentation * * @param {Object} page */ Olark.prototype.initialize = function (page) { window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]}); window.olark.identify(this.options.siteId); // keep track of the widget's open state var self = this; box('onExpand', function () { self._open = true; }); box('onShrink', function () { self._open = false; }); }; /** * Page. * * @param {Page} page */ Olark.prototype.page = function (page) { if (!this.options.page || !this._open) return; var props = page.properties(); var name = page.fullName(); if (!name && !props.url) return; var msg = name ? name.toLowerCase() + ' page' : props.url; chat('sendNotificationToOperator', { body: 'looking at ' + msg // lowercase since olark does }); }; /** * Identify. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) */ Olark.prototype.identify = function (identify) { if (!this.options.identify) return; var username = identify.username(); var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); var phone = identify.phone(); var name = identify.name() || identify.firstName(); visitor('updateCustomFields', traits); if (email) visitor('updateEmailAddress', { emailAddress: email }); if (phone) visitor('updatePhoneNumber', { phoneNumber: phone }); // figure out best name if (name) visitor('updateFullName', { fullName: name }); // figure out best nickname var nickname = name || email || username || id; if (name && email) nickname += ' (' + email + ')'; if (nickname) chat('updateVisitorNickname', { snippet: nickname }); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Olark.prototype.track = function (track) { if (!this.options.track || !this._open) return; chat('sendNotificationToOperator', { body: 'visitor triggered "' + track.event() + '"' // lowercase since olark does }); }; /** * Helper method for Olark box API calls. * * @param {String} action * @param {Object} value */ function box (action, value) { window.olark('api.box.' + action, value); } /** * Helper method for Olark visitor API calls. * * @param {String} action * @param {Object} value */ function visitor (action, value) { window.olark('api.visitor.' + action, value); } /** * Helper method for Olark chat API calls. * * @param {String} action * @param {Object} value */ function chat (action, value) { window.olark('api.chat.' + action, value); } }); require.register("segmentio-analytics.js-integrations/lib/optimizely.js", function(exports, require, module){ var bind = require('bind'); var callback = require('callback'); var each = require('each'); var integration = require('integration'); var push = require('global-queue')('optimizely'); var tick = require('next-tick'); /** * Analytics reference. */ var analytics; /** * Expose plugin. */ module.exports = exports = function (ajs) { ajs.addIntegration(Optimizely); analytics = ajs; // store for later }; /** * Expose `Optimizely` integration. */ var Optimizely = exports.Integration = integration('Optimizely') .readyOnInitialize() .option('variations', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * https://www.optimizely.com/docs/api#function-calls */ Optimizely.prototype.initialize = function () { if (this.options.variations) tick(this.replay); }; /** * Track. * * https://www.optimizely.com/docs/api#track-event * * @param {Track} track */ Optimizely.prototype.track = function (track) { var props = track.properties(); if (props.revenue) props.revenue *= 100; push('trackEvent', track.event(), props); }; /** * Page. * * https://www.optimizely.com/docs/api#track-event * * @param {Page} page */ Optimizely.prototype.page = function (page) { var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Replay experiment data as traits to other enabled providers. * * https://www.optimizely.com/docs/api#data-object */ Optimizely.prototype.replay = function () { if (!window.optimizely) return; // in case the snippet isnt on the page var data = window.optimizely.data; if (!data) return; var experiments = data.experiments; var map = data.state.variationNamesMap; var traits = {}; each(map, function (experimentId, variation) { var experiment = experiments[experimentId].name; traits['Experiment: ' + experiment] = variation; }); analytics.identify(traits); }; }); require.register("segmentio-analytics.js-integrations/lib/perfect-audience.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(PerfectAudience); }; /** * Expose `PerfectAudience` integration. */ var PerfectAudience = exports.Integration = integration('Perfect Audience') .assumesPageview() .readyOnLoad() .global('_pa') .option('siteId', ''); /** * Initialize. * * https://www.perfectaudience.com/docs#javascript_api_autoopen * * @param {Object} page */ PerfectAudience.prototype.initialize = function (page) { window._pa = window._pa || {}; this.load(); }; /** * Loaded? * * @return {Boolean} */ PerfectAudience.prototype.loaded = function () { return !! (window._pa && window._pa.track); }; /** * Load. * * @param {Function} callback */ PerfectAudience.prototype.load = function (callback) { var id = this.options.siteId; load('//tag.perfectaudience.com/serve/' + id + '.js', callback); }; /** * Track. * * @param {Track} event */ PerfectAudience.prototype.track = function (track) { window._pa.track(track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/pingdom.js", function(exports, require, module){ var date = require('load-date'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_prum'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Pingdom); }; /** * Expose `Pingdom` integration. */ var Pingdom = exports.Integration = integration('Pingdom') .assumesPageview() .readyOnLoad() .global('_prum') .option('id', ''); /** * Initialize. * * @param {Object} page */ Pingdom.prototype.initialize = function (page) { window._prum = window._prum || []; push('id', this.options.id); push('mark', 'firstbyte', date.getTime()); this.load(); }; /** * Loaded? * * @return {Boolean} */ Pingdom.prototype.loaded = function () { return !! (window._prum && window._prum.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Pingdom.prototype.load = function (callback) { load('//rum-static.pingdom.net/prum.min.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/preact.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var convertDates = require('convert-dates'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_lnq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Preact); }; /** * Expose `Preact` integration. */ var Preact = exports.Integration = integration('Preact') .assumesPageview() .readyOnInitialize() .global('_lnq') .option('projectCode', ''); /** * Initialize. * * http://www.preact.io/api/javascript * * @param {Object} page */ Preact.prototype.initialize = function (page) { window._lnq = window._lnq || []; push('_setCode', this.options.projectCode); this.load(); }; /** * Loaded? * * @return {Boolean} */ Preact.prototype.loaded = function () { return !! (window._lnq && window._lnq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Preact.prototype.load = function (callback) { load('//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js', callback); }; /** * Identify. * * @param {Identify} identify */ Preact.prototype.identify = function (identify) { if (!identify.userId()) return; var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); push('_setPersonData', { name: identify.name(), email: identify.email(), uid: identify.userId(), properties: traits }); }; /** * Group. * * @param {String} id * @param {Object} properties (optional) * @param {Object} options (optional) */ Preact.prototype.group = function (group) { if (!group.groupId()) return; push('_setAccount', group.traits()); }; /** * Track. * * @param {Track} track */ Preact.prototype.track = function (track) { var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var special = { name: event }; if (revenue) { special.revenue = revenue * 100; delete props.revenue; } if (props.note) { special.note = props.note; delete props.note; } push('_logEvent', special, props); }; /** * Convert a `date` to a format Preact supports. * * @param {Date} date * @return {Number} */ function convertDate (date) { return Math.floor(date / 1000); } }); require.register("segmentio-analytics.js-integrations/lib/qualaroo.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_kiq'); var Facade = require('facade'); var Identify = Facade.Identify; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Qualaroo); }; /** * Expose `Qualaroo` integration. */ var Qualaroo = exports.Integration = integration('Qualaroo') .assumesPageview() .readyOnInitialize() .global('_kiq') .option('customerId', '') .option('siteToken', '') .option('track', false); /** * Initialize. * * @param {Object} page */ Qualaroo.prototype.initialize = function (page) { window._kiq = window._kiq || []; this.load(); }; /** * Loaded? * * @return {Boolean} */ Qualaroo.prototype.loaded = function () { return !! (window._kiq && window._kiq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Qualaroo.prototype.load = function (callback) { var token = this.options.siteToken; var id = this.options.customerId; load('//s3.amazonaws.com/ki.js/' + id + '/' + token + '.js', callback); }; /** * Identify. * * http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers * http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties * * @param {Identify} identify */ Qualaroo.prototype.identify = function (identify) { var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); if (email) id = email; if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Qualaroo.prototype.track = function (track) { if (!this.options.track) return; var event = track.event(); var traits = {}; traits['Triggered: ' + event] = true; this.identify(new Identify({ traits: traits })); }; }); require.register("segmentio-analytics.js-integrations/lib/quantcast.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_qevents', { wrap: false }); /** * User reference. */ var user; /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Quantcast); user = analytics.user(); // store for later }; /** * Expose `Quantcast` integration. */ var Quantcast = exports.Integration = integration('Quantcast') .assumesPageview() .readyOnInitialize() .global('_qevents') .global('__qc') .option('pCode', null) .option('labelPages', false); /** * Initialize. * * https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/ * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {Object} page */ Quantcast.prototype.initialize = function (page) { page = page || {}; window._qevents = window._qevents || []; var opts = this.options; var settings = { qacct: opts.pCode }; if (user.id()) settings.uid = user.id(); push(settings); this.load(); }; /** * Loaded? * * @return {Boolean} */ Quantcast.prototype.loaded = function () { return !! window.__qc; }; /** * Load. * * @param {Function} callback */ Quantcast.prototype.load = function (callback) { load({ http: 'http://edge.quantserve.com/quant.js', https: 'https://secure.quantserve.com/quant.js' }, callback); }; /** * Page. * * https://cloudup.com/cBRRFAfq6mf * * @param {Page} page */ Quantcast.prototype.page = function (page) { var settings = { event: 'refresh', qacct: this.options.pCode, }; if (user.id()) settings.uid = user.id(); push(settings); }; /** * Identify. * * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {String} id (optional) */ Quantcast.prototype.identify = function (identify) { // edit the initial quantcast settings var id = identify.userId(); if (id) window._qevents[0].uid = id; }; /** * Track. * * https://cloudup.com/cBRRFAfq6mf * * @param {Track} track */ Quantcast.prototype.track = function (track) { var settings = { event: 'click', qacct: this.options.pCode }; if (user.id()) settings.uid = user.id(); push(settings); }; }); require.register("segmentio-analytics.js-integrations/lib/rollbar.js", function(exports, require, module){ var callback = require('callback'); var clone = require('clone'); var extend = require('extend'); var integration = require('integration'); var load = require('load-script'); var onError = require('on-error'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Rollbar); }; /** * Expose `Rollbar` integration. */ var Rollbar = exports.Integration = integration('Rollbar') .readyOnInitialize() .assumesPageview() .global('_rollbar') .option('accessToken', '') .option('identify', true); /** * Initialize. * * https://rollbar.com/docs/notifier/rollbar.js/ * * @param {Object} page */ Rollbar.prototype.initialize = function (page) { var options = this.options; window._rollbar = window._rollbar || window._ratchet || [options.accessToken, options]; onError(function() { window._rollbar.push.apply(window._rollbar, arguments); }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Rollbar.prototype.loaded = function () { return !! (window._rollbar && window._rollbar.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Rollbar.prototype.load = function (callback) { load('//d37gvrvc0wt4s1.cloudfront.net/js/1/rollbar.min.js', callback); }; /** * Identify. * * @param {Identify} identify */ Rollbar.prototype.identify = function (identify) { if (!this.options.identify) return; var traits = identify.traits(); var rollbar = window._rollbar; var params = rollbar.shift ? rollbar[1] = rollbar[1] || {} : rollbar.extraParams = rollbar.extraParams || {}; params.person = params.person || {}; extend(params.person, traits); }; }); require.register("segmentio-analytics.js-integrations/lib/saasquatch.js", function(exports, require, module){ /** * Module dependencies. */ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(SaaSquatch); }; /** * Expose `SaaSquatch` integration. */ var SaaSquatch = exports.Integration = integration('SaaSquatch') .readyOnInitialize() .option('tenantAlias', '') .global('_sqh'); /** * Initialize * * @param {Page} page */ SaaSquatch.prototype.initialize = function(page){}; /** * Loaded? * * @return {Boolean} */ SaaSquatch.prototype.loaded = function(){ return window._sqh && window._sqh.push != [].push; }; /** * Load the SaaSquatch library. * * @param {Function} fn */ SaaSquatch.prototype.load = function(fn){ load('//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js', fn); }; /** * Identify. * * @param {Facade} identify */ SaaSquatch.prototype.identify = function(identify){ var sqh = window._sqh = window._sqh || []; var accountId = identify.proxy('traits.accountId'); var image = identify.proxy('traits.referralImage'); var opts = identify.options(this.name); var id = identify.userId(); var email = identify.email(); if (!(id || email)) return; if (this.called) return; var init = { tenant_alias: this.options.tenantAlias, first_name: identify.firstName(), last_name: identify.lastName(), user_image: identify.avatar(), email: email, user_id: id, }; if (accountId) init.account_id = accountId; if (opts.checksum) init.checksum = opts.checksum; if (image) init.fb_share_image = image; sqh.push(['init', init]); this.called = true; this.load(); }; }); require.register("segmentio-analytics.js-integrations/lib/sentry.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Sentry); }; /** * Expose `Sentry` integration. */ var Sentry = exports.Integration = integration('Sentry') .readyOnLoad() .global('Raven') .option('config', ''); /** * Initialize. * * http://raven-js.readthedocs.org/en/latest/config/index.html */ Sentry.prototype.initialize = function () { var config = this.options.config; this.load(function () { // for now, raven basically requires `install` to be called // https://github.com/getsentry/raven-js/blob/master/src/raven.js#L113 window.Raven.config(config).install(); }); }; /** * Loaded? * * @return {Boolean} */ Sentry.prototype.loaded = function () { return is.object(window.Raven); }; /** * Load. * * @param {Function} callback */ Sentry.prototype.load = function (callback) { load('//cdn.ravenjs.com/1.1.10/native/raven.min.js', callback); }; /** * Identify. * * @param {Identify} identify */ Sentry.prototype.identify = function (identify) { window.Raven.setUser(identify.traits()); }; }); require.register("segmentio-analytics.js-integrations/lib/snapengage.js", function(exports, require, module){ var integration = require('integration'); var is = require('is'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(SnapEngage); }; /** * Expose `SnapEngage` integration. */ var SnapEngage = exports.Integration = integration('SnapEngage') .assumesPageview() .readyOnLoad() .global('SnapABug') .option('apiKey', ''); /** * Initialize. * * http://help.snapengage.com/installation-guide-getting-started-in-a-snap/ * * @param {Object} page */ SnapEngage.prototype.initialize = function (page) { this.load(); }; /** * Loaded? * * @return {Boolean} */ SnapEngage.prototype.loaded = function () { return is.object(window.SnapABug); }; /** * Load. * * @param {Function} callback */ SnapEngage.prototype.load = function (callback) { var key = this.options.apiKey; var url = '//commondatastorage.googleapis.com/code.snapengage.com/js/' + key + '.js'; load(url, callback); }; /** * Identify. * * @param {Identify} identify */ SnapEngage.prototype.identify = function (identify) { var email = identify.email(); if (!email) return; window.SnapABug.setUserEmail(email); }; }); require.register("segmentio-analytics.js-integrations/lib/spinnakr.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Spinnakr); }; /** * Expose `Spinnakr` integration. */ var Spinnakr = exports.Integration = integration('Spinnakr') .assumesPageview() .readyOnLoad() .global('_spinnakr_site_id') .global('_spinnakr') .option('siteId', ''); /** * Initialize. * * @param {Object} page */ Spinnakr.prototype.initialize = function (page) { window._spinnakr_site_id = this.options.siteId; this.load(); }; /** * Loaded? * * @return {Boolean} */ Spinnakr.prototype.loaded = function () { return !! window._spinnakr; }; /** * Load. * * @param {Function} callback */ Spinnakr.prototype.load = function (callback) { load('//d3ojzyhbolvoi5.cloudfront.net/js/so.js', callback); }; }); require.register("segmentio-analytics.js-integrations/lib/tapstream.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var slug = require('slug'); var push = require('global-queue')('_tsq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Tapstream); }; /** * Expose `Tapstream` integration. */ var Tapstream = exports.Integration = integration('Tapstream') .assumesPageview() .readyOnInitialize() .global('_tsq') .option('accountName', '') .option('trackAllPages', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * @param {Object} page */ Tapstream.prototype.initialize = function (page) { window._tsq = window._tsq || []; push('setAccountName', this.options.accountName); this.load(); }; /** * Loaded? * * @return {Boolean} */ Tapstream.prototype.loaded = function () { return !! (window._tsq && window._tsq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Tapstream.prototype.load = function (callback) { load('//cdn.tapstream.com/static/js/tapstream.js', callback); }; /** * Page. * * @param {Page} page */ Tapstream.prototype.page = function (page) { var category = page.category(); var opts = this.options; var name = page.fullName(); // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Track. * * @param {Track} track */ Tapstream.prototype.track = function (track) { var props = track.properties(); push('fireHit', slug(track.event()), [props.url]); // needs events as slugs }; }); require.register("segmentio-analytics.js-integrations/lib/trakio.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var clone = require('clone'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Trakio); }; /** * Expose `Trakio` integration. */ var Trakio = exports.Integration = integration('trak.io') .assumesPageview() .readyOnInitialize() .global('trak') .option('token', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Options aliases. */ var optionsAliases = { initialPageview: 'auto_track_page_view' }; /** * Initialize. * * https://docs.trak.io * * @param {Object} page */ Trakio.prototype.initialize = function (page) { var self = this; var options = this.options; window.trak = window.trak || []; window.trak.io = window.trak.io || {}; window.trak.io.load = function(e) {self.load(); var r = function(e) {return function() {window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); }; window.trak.io.load(options.token, alias(options, optionsAliases)); this.load(); }; /** * Loaded? * * @return {Boolean} */ Trakio.prototype.loaded = function () { return !! (window.trak && window.trak.loaded); }; /** * Load the trak.io library. * * @param {Function} callback */ Trakio.prototype.load = function (callback) { load('//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js', callback); }; /** * Page. * * @param {Page} page */ Trakio.prototype.page = function (page) { var category = page.category(); var props = page.properties(); var name = page.fullName(); window.trak.io.page_view(props.path, name || props.title); // named pages if (name && this.options.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && this.options.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Trait aliases. * * http://docs.trak.io/properties.html#special */ var traitAliases = { avatar: 'avatar_url', firstName: 'first_name', lastName: 'last_name' }; /** * Identify. * * @param {Identify} identify */ Trakio.prototype.identify = function (identify) { var traits = identify.traits(traitAliases); var id = identify.userId(); if (id) { window.trak.io.identify(id, traits); } else { window.trak.io.identify(traits); } }; /** * Group. * * @param {String} id (optional) * @param {Object} properties (optional) * @param {Object} options (optional) * * TODO: add group * TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special */ /** * Track. * * @param {Track} track */ Trakio.prototype.track = function (track) { window.trak.io.track(track.event(), track.properties()); }; /** * Alias. * * @param {Alias} alias */ Trakio.prototype.alias = function (alias) { if (!window.trak.io.distinct_id) return; var from = alias.from(); var to = alias.to(); if (to === window.trak.io.distinct_id()) return; if (from) { window.trak.io.alias(from, to); } else { window.trak.io.alias(to); } }; }); require.register("segmentio-analytics.js-integrations/lib/twitter-ads.js", function(exports, require, module){ var pixel = require('load-pixel')('//analytics.twitter.com/i/adsct'); var integration = require('integration'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(TwitterAds); }; /** * Expose `load` */ exports.load = pixel; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `TwitterAds` */ var TwitterAds = exports.Integration = integration('Twitter Ads') .readyOnInitialize() .option('events', {}); /** * Track. * * @param {Track} track */ TwitterAds.prototype.track = function(track){ var events = this.options.events; var event = track.event(); if (!has.call(events, event)) return; return exports.load({ txn_id: events[event], p_id: 'Twitter' }); }; }); require.register("segmentio-analytics.js-integrations/lib/usercycle.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_uc'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Usercycle); }; /** * Expose `Usercycle` integration. */ var Usercycle = exports.Integration = integration('USERcycle') .assumesPageview() .readyOnInitialize() .global('_uc') .option('key', ''); /** * Initialize. * * http://docs.usercycle.com/javascript_api * * @param {Object} page */ Usercycle.prototype.initialize = function (page) { push('_key', this.options.key); this.load(); }; /** * Loaded? * * @return {Boolean} */ Usercycle.prototype.loaded = function () { return !! (window._uc && window._uc.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Usercycle.prototype.load = function (callback) { load('//api.usercycle.com/javascripts/track.js', callback); }; /** * Identify. * * @param {Identify} identify */ Usercycle.prototype.identify = function (identify) { var traits = identify.traits(); var id = identify.userId(); if (id) push('uid', id); // there's a special `came_back` event used for retention and traits push('action', 'came_back', traits); }; /** * Track. * * @param {Track} track */ Usercycle.prototype.track = function (track) { push('action', track.event(), track.properties({ revenue: 'revenue_amount' })); }; }); require.register("segmentio-analytics.js-integrations/lib/userfox.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var convertDates = require('convert-dates'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_ufq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Userfox); }; /** * Expose `Userfox` integration. */ var Userfox = exports.Integration = integration('userfox') .assumesPageview() .readyOnInitialize() .global('_ufq') .option('clientId', ''); /** * Initialize. * * https://www.userfox.com/docs/ * * @param {Object} page */ Userfox.prototype.initialize = function (page) { window._ufq = []; this.load(); }; /** * Loaded? * * @return {Boolean} */ Userfox.prototype.loaded = function () { return !! (window._ufq && window._ufq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Userfox.prototype.load = function (callback) { load('//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js', callback); }; /** * Identify. * * https://www.userfox.com/docs/#custom-data * * @param {Identify} identify */ Userfox.prototype.identify = function (identify) { var traits = identify.traits({ created: 'signup_date' }); var email = identify.email(); if (!email) return; // initialize the library with the email now that we have it push('init', { clientId: this.options.clientId, email: email }); traits = convertDates(traits, formatDate); push('track', traits); }; /** * Convert a `date` to a format userfox supports. * * @param {Date} date * @return {String} */ function formatDate (date) { return Math.round(date.getTime() / 1000).toString(); } }); require.register("segmentio-analytics.js-integrations/lib/uservoice.js", function(exports, require, module){ var alias = require('alias'); var callback = require('callback'); var clone = require('clone'); var convertDates = require('convert-dates'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('UserVoice'); var unix = require('to-unix-timestamp'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(UserVoice); }; /** * Expose `UserVoice` integration. */ var UserVoice = exports.Integration = integration('UserVoice') .assumesPageview() .readyOnInitialize() .global('UserVoice') .global('showClassicWidget') .option('apiKey', '') .option('classic', false) .option('forumId', null) .option('showWidget', true) .option('mode', 'contact') .option('accentColor', '#448dd6') .option('smartvote', true) .option('trigger', null) .option('triggerPosition', 'bottom-right') .option('triggerColor', '#ffffff') .option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)') // BACKWARDS COMPATIBILITY: classic options .option('classicMode', 'full') .option('primaryColor', '#cc6d00') .option('linkColor', '#007dbf') .option('defaultMode', 'support') .option('tabLabel', 'Feedback & Support') .option('tabColor', '#cc6d00') .option('tabPosition', 'middle-right') .option('tabInverted', false); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ UserVoice.on('construct', function (integration) { if (!integration.options.classic) return; integration.group = undefined; integration.identify = integration.identifyClassic; integration.initialize = integration.initializeClassic; }); /** * Initialize. * * @param {Object} page */ UserVoice.prototype.initialize = function (page) { var options = this.options; var opts = formatOptions(options); push('set', opts); push('autoprompt', {}); if (options.showWidget) { options.trigger ? push('addTrigger', options.trigger, opts) : push('addTrigger', opts); } this.load(); }; /** * Loaded? * * @return {Boolean} */ UserVoice.prototype.loaded = function () { return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ UserVoice.prototype.load = function (callback) { var key = this.options.apiKey; load('//widget.uservoice.com/' + key + '.js', callback); }; /** * Identify. * * @param {Identify} identify */ UserVoice.prototype.identify = function (identify) { var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', traits); }; /** * Group. * * @param {Group} group */ UserVoice.prototype.group = function (group) { var traits = group.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', { account: traits }); }; /** * Initialize (classic). * * @param {Object} options * @param {Function} ready */ UserVoice.prototype.initializeClassic = function () { var options = this.options; window.showClassicWidget = showClassicWidget; // part of public api if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options)); this.load(); }; /** * Identify (classic). * * @param {Identify} identify */ UserVoice.prototype.identifyClassic = function (identify) { push('setCustomFields', identify.traits()); }; /** * Format the options for UserVoice. * * @param {Object} options * @return {Object} */ function formatOptions (options) { return alias(options, { forumId: 'forum_id', accentColor: 'accent_color', smartvote: 'smartvote_enabled', triggerColor: 'trigger_color', triggerBackgroundColor: 'trigger_background_color', triggerPosition: 'trigger_position' }); } /** * Format the classic options for UserVoice. * * @param {Object} options * @return {Object} */ function formatClassicOptions (options) { return alias(options, { forumId: 'forum_id', classicMode: 'mode', primaryColor: 'primary_color', tabPosition: 'tab_position', tabColor: 'tab_color', linkColor: 'link_color', defaultMode: 'default_mode', tabLabel: 'tab_label', tabInverted: 'tab_inverted' }); } /** * Show the classic version of the UserVoice widget. This method is usually part * of UserVoice classic's public API. * * @param {String} type ('showTab' or 'showLightbox') * @param {Object} options (optional) */ function showClassicWidget (type, options) { type = type || 'showLightbox'; push(type, 'classic_widget', options); } }); require.register("segmentio-analytics.js-integrations/lib/vero.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); var push = require('global-queue')('_veroq'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Vero); }; /** * Expose `Vero` integration. */ var Vero = exports.Integration = integration('Vero') .assumesPageview() .readyOnInitialize() .global('_veroq') .option('apiKey', ''); /** * Initialize. * * https://github.com/getvero/vero-api/blob/master/sections/js.md * * @param {Object} page */ Vero.prototype.initialize = function (pgae) { push('init', { api_key: this.options.apiKey }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Vero.prototype.loaded = function () { return !! (window._veroq && window._veroq.push !== Array.prototype.push); }; /** * Load. * * @param {Function} callback */ Vero.prototype.load = function (callback) { load('//d3qxef4rp70elm.cloudfront.net/m.js', callback); }; /** * Identify. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification * * @param {Identify} identify */ Vero.prototype.identify = function (identify) { var traits = identify.traits(); var email = identify.email(); var id = identify.userId(); if (!id || !email) return; // both required push('user', traits); }; /** * Track. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events * * @param {Track} track */ Vero.prototype.track = function (track) { push('track', track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", function(exports, require, module){ var callback = require('callback'); var each = require('each'); var integration = require('integration'); var tick = require('next-tick'); /** * Analytics reference. */ var analytics; /** * Expose plugin. */ module.exports = exports = function (ajs) { ajs.addIntegration(VWO); analytics = ajs; }; /** * Expose `VWO` integration. */ var VWO = exports.Integration = integration('Visual Website Optimizer') .readyOnInitialize() .option('replay', true); /** * Initialize. * * http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php */ VWO.prototype.initialize = function () { if (this.options.replay) this.replay(); }; /** * Replay the experiments the user has seen as traits to all other integrations. * Wait for the next tick to replay so that the `analytics` object and all of * the integrations are fully initialized. */ VWO.prototype.replay = function () { tick(function () { experiments(function (err, traits) { if (traits) analytics.identify(traits); }); }); }; /** * Get dictionary of experiment keys and variations. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {Function} callback * @return {Object} */ function experiments (callback) { enqueue(function () { var data = {}; var ids = window._vwo_exp_ids; if (!ids) return callback(); each(ids, function (id) { var name = variation(id); if (name) data['Experiment: ' + id] = name; }); callback(null, data); }); } /** * Add a `fn` to the VWO queue, creating one if it doesn't exist. * * @param {Function} fn */ function enqueue (fn) { window._vis_opt_queue = window._vis_opt_queue || []; window._vis_opt_queue.push(fn); } /** * Get the chosen variation's name from an experiment `id`. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {String} id * @return {String} */ function variation (id) { var experiments = window._vwo_exp; if (!experiments) return null; var experiment = experiments[id]; var variationId = experiment.combination_chosen; return variationId ? experiment.comb_n[variationId] : null; } }); require.register("segmentio-analytics.js-integrations/lib/webengage.js", function(exports, require, module){ var integration = require('integration'); var load = require('load-script'); /** * Expose plugin */ module.exports = exports = function(analytics){ analytics.addIntegration(WebEngage); }; /** * Expose `WebEngage` integration */ var WebEngage = exports.Integration = integration('WebEngage') .assumesPageview() .readyOnLoad() .global('_weq') .global('webengage') .option('widgetVersion', '4.0') .option('licenseCode', ''); /** * Initialize. * * @param {Object} page */ WebEngage.prototype.initialize = function(page){ var _weq = window._weq = window._weq || {}; _weq['webengage.licenseCode'] = this.options.licenseCode; _weq['webengage.widgetVersion'] = this.options.widgetVersion; this.load(); }; /** * Loaded? * * @return {Boolean} */ WebEngage.prototype.loaded = function(){ return !! window.webengage; }; /** * Load * * @param {Function} fn */ WebEngage.prototype.load = function(fn){ var path = '/js/widget/webengage-min-v-4.0.js'; load({ https: 'https://ssl.widgets.webengage.com' + path, http: 'http://cdn.widgets.webengage.com' + path }, fn); }; }); require.register("segmentio-analytics.js-integrations/lib/woopra.js", function(exports, require, module){ var each = require('each'); var extend = require('extend'); var integration = require('integration'); var isEmail = require('is-email'); var load = require('load-script'); var type = require('type'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Woopra); }; /** * Expose `Woopra` integration. */ var Woopra = exports.Integration = integration('Woopra') .readyOnLoad() .global('woopra') .option('domain', ''); /** * Initialize. * * http://www.woopra.com/docs/setup/javascript-tracking/ * * @param {Object} page */ Woopra.prototype.initialize = function (page) { (function () {var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () {var i, self = this; self._e = []; for (i = 0; i < f.length; i++) {(function (f) {self[f] = function () {self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++) { w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra'); window.woopra.config({ domain: this.options.domain }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Woopra.prototype.loaded = function () { return !! (window.woopra && window.woopra.loaded); }; /** * Load. * * @param {Function} callback */ Woopra.prototype.load = function (callback) { load('//static.woopra.com/js/w.js', callback); }; /** * Page. * * @param {String} category (optional) */ Woopra.prototype.page = function (page) { var props = page.properties(); var name = page.fullName(); if (name) props.title = name; window.woopra.track('pv', props); }; /** * Identify. * * @param {Identify} identify */ Woopra.prototype.identify = function (identify) { window.woopra.identify(identify.traits()).push(); // `push` sends it off async }; /** * Track. * * @param {Track} track */ Woopra.prototype.track = function (track) { window.woopra.track(track.event(), track.properties()); }; }); require.register("segmentio-analytics.js-integrations/lib/yandex-metrica.js", function(exports, require, module){ var callback = require('callback'); var integration = require('integration'); var load = require('load-script'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Yandex); }; /** * Expose `Yandex` integration. */ var Yandex = exports.Integration = integration('Yandex Metrica') .assumesPageview() .readyOnInitialize() .global('yandex_metrika_callbacks') .global('Ya') .option('counterId', null); /** * Initialize. * * http://api.yandex.com/metrika/ * https://metrica.yandex.com/22522351?step=2#tab=code * * @param {Object} page */ Yandex.prototype.initialize = function (page) { var id = this.options.counterId; push(function () { window['yaCounter' + id] = new window.Ya.Metrika({ id: id }); }); this.load(); }; /** * Loaded? * * @return {Boolean} */ Yandex.prototype.loaded = function () { return !! (window.Ya && window.Ya.Metrika); }; /** * Load. * * @param {Function} callback */ Yandex.prototype.load = function (callback) { load('//mc.yandex.ru/metrika/watch.js', callback); }; /** * Push a new callback on the global Yandex queue. * * @param {Function} callback */ function push (callback) { window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || []; window.yandex_metrika_callbacks.push(callback); } }); require.register("segmentio-canonical/index.js", function(exports, require, module){ module.exports = function canonical () { var tags = document.getElementsByTagName('link'); for (var i = 0, tag; tag = tags[i]; i++) { if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href'); } }; }); require.register("segmentio-extend/index.js", function(exports, require, module){ module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }); require.register("camshaft-require-component/index.js", function(exports, require, module){ /** * Require a module with a fallback */ module.exports = function(parent) { function require(name, fallback) { try { return parent(name); } catch (e) { try { return parent(fallback || name+"-component"); } catch(e2) { throw e; } } }; // Merge the old properties for (var key in parent) { require[key] = parent[key]; } return require; }; }); require.register("ianstormtaylor-to-camel-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toCamelCase`. */ module.exports = toCamelCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toCamelCase (string) { return toSpace(string).replace(/\s(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }); require.register("ianstormtaylor-to-capital-case/index.js", function(exports, require, module){ var clean = require('to-no-case'); /** * Expose `toCapitalCase`. */ module.exports = toCapitalCase; /** * Convert a `string` to capital case. * * @param {String} string * @return {String} */ function toCapitalCase (string) { return clean(string).replace(/(^|\s)(\w)/g, function (matches, previous, letter) { return previous + letter.toUpperCase(); }); } }); require.register("ianstormtaylor-to-constant-case/index.js", function(exports, require, module){ var snake = require('to-snake-case'); /** * Expose `toConstantCase`. */ module.exports = toConstantCase; /** * Convert a `string` to constant case. * * @param {String} string * @return {String} */ function toConstantCase (string) { return snake(string).toUpperCase(); } }); require.register("ianstormtaylor-to-dot-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toDotCase`. */ module.exports = toDotCase; /** * Convert a `string` to slug case. * * @param {String} string * @return {String} */ function toDotCase (string) { return toSpace(string).replace(/\s/g, '.'); } }); require.register("ianstormtaylor-to-no-case/index.js", function(exports, require, module){ /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasCamel = /[a-z][A-Z]/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) string = unseparate(string); if (hasCamel.test(string)) string = uncamelize(string); return string.toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }); require.register("ianstormtaylor-to-pascal-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toPascalCase`. */ module.exports = toPascalCase; /** * Convert a `string` to pascal case. * * @param {String} string * @return {String} */ function toPascalCase (string) { return toSpace(string).replace(/(?:^|\s)(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }); require.register("ianstormtaylor-to-sentence-case/index.js", function(exports, require, module){ var clean = require('to-no-case'); /** * Expose `toSentenceCase`. */ module.exports = toSentenceCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toSentenceCase (string) { return clean(string).replace(/[a-z]/i, function (letter) { return letter.toUpperCase(); }); } }); require.register("ianstormtaylor-to-slug-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toSlugCase`. */ module.exports = toSlugCase; /** * Convert a `string` to slug case. * * @param {String} string * @return {String} */ function toSlugCase (string) { return toSpace(string).replace(/\s/g, '-'); } }); require.register("ianstormtaylor-to-snake-case/index.js", function(exports, require, module){ var toSpace = require('to-space-case'); /** * Expose `toSnakeCase`. */ module.exports = toSnakeCase; /** * Convert a `string` to snake case. * * @param {String} string * @return {String} */ function toSnakeCase (string) { return toSpace(string).replace(/\s/g, '_'); } }); require.register("ianstormtaylor-to-space-case/index.js", function(exports, require, module){ var clean = require('to-no-case'); /** * Expose `toSpaceCase`. */ module.exports = toSpaceCase; /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); } }); require.register("component-escape-regexp/index.js", function(exports, require, module){ /** * Escape regexp special characters in `str`. * * @param {String} str * @return {String} * @api public */ module.exports = function(str){ return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1'); }; }); require.register("ianstormtaylor-map/index.js", function(exports, require, module){ var each = require('each'); /** * Map an array or object. * * @param {Array|Object} obj * @param {Function} iterator * @return {Mixed} */ module.exports = function map (obj, iterator) { var arr = []; each(obj, function (o) { arr.push(iterator.apply(null, arguments)); }); return arr; }; }); require.register("ianstormtaylor-title-case-minors/index.js", function(exports, require, module){ module.exports = [ 'a', 'an', 'and', 'as', 'at', 'but', 'by', 'en', 'for', 'from', 'how', 'if', 'in', 'neither', 'nor', 'of', 'on', 'only', 'onto', 'out', 'or', 'per', 'so', 'than', 'that', 'the', 'to', 'until', 'up', 'upon', 'v', 'v.', 'versus', 'vs', 'vs.', 'via', 'when', 'with', 'without', 'yet' ]; }); require.register("ianstormtaylor-to-title-case/index.js", function(exports, require, module){ var capital = require('to-capital-case') , escape = require('escape-regexp') , map = require('map') , minors = require('title-case-minors'); /** * Expose `toTitleCase`. */ module.exports = toTitleCase; /** * Minors. */ var escaped = map(minors, escape); var minorMatcher = new RegExp('[^^]\\b(' + escaped.join('|') + ')\\b', 'ig'); var colonMatcher = /:\s*(\w)/g; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toTitleCase (string) { return capital(string) .replace(minorMatcher, function (minor) { return minor.toLowerCase(); }) .replace(colonMatcher, function (letter) { return letter.toUpperCase(); }); } }); require.register("ianstormtaylor-case/lib/index.js", function(exports, require, module){ var cases = require('./cases'); /** * Expose `determineCase`. */ module.exports = exports = determineCase; /** * Determine the case of a `string`. * * @param {String} string * @return {String|Null} */ function determineCase (string) { for (var key in cases) { if (key == 'none') continue; var convert = cases[key]; if (convert(string) == string) return key; } return null; } /** * Define a case by `name` with a `convert` function. * * @param {String} name * @param {Object} convert */ exports.add = function (name, convert) { exports[name] = cases[name] = convert; }; /** * Add all the `cases`. */ for (var key in cases) { exports.add(key, cases[key]); } }); require.register("ianstormtaylor-case/lib/cases.js", function(exports, require, module){ var camel = require('to-camel-case') , capital = require('to-capital-case') , constant = require('to-constant-case') , dot = require('to-dot-case') , none = require('to-no-case') , pascal = require('to-pascal-case') , sentence = require('to-sentence-case') , slug = require('to-slug-case') , snake = require('to-snake-case') , space = require('to-space-case') , title = require('to-title-case'); /** * Camel. */ exports.camel = camel; /** * Pascal. */ exports.pascal = pascal; /** * Dot. Should precede lowercase. */ exports.dot = dot; /** * Slug. Should precede lowercase. */ exports.slug = slug; /** * Snake. Should precede lowercase. */ exports.snake = snake; /** * Space. Should precede lowercase. */ exports.space = space; /** * Constant. Should precede uppercase. */ exports.constant = constant; /** * Capital. Should precede sentence and title. */ exports.capital = capital; /** * Title. */ exports.title = title; /** * Sentence. */ exports.sentence = sentence; /** * Convert a `string` to lower case from camel, slug, etc. Different that the * usual `toLowerCase` in that it will try to break apart the input first. * * @param {String} string * @return {String} */ exports.lower = function (string) { return none(string).toLowerCase(); }; /** * Convert a `string` to upper case from camel, slug, etc. Different that the * usual `toUpperCase` in that it will try to break apart the input first. * * @param {String} string * @return {String} */ exports.upper = function (string) { return none(string).toUpperCase(); }; /** * Invert each character in a `string` from upper to lower and vice versa. * * @param {String} string * @return {String} */ exports.inverse = function (string) { for (var i = 0, char; char = string[i]; i++) { if (!/[a-z]/i.test(char)) continue; var upper = char.toUpperCase(); var lower = char.toLowerCase(); string[i] = char == upper ? lower : upper; } return string; }; /** * None. */ exports.none = none; }); require.register("segmentio-obj-case/index.js", function(exports, require, module){ var Case = require('case'); var cases = [ Case.upper, Case.lower, Case.snake, Case.pascal, Case.camel, Case.constant, Case.title, Case.capital, Case.sentence ]; /** * Module exports, export */ module.exports = module.exports.find = multiple(find); /** * Export the replacement function, return the modified object */ module.exports.replace = function (obj, key, val) { multiple(replace).apply(this, arguments); return obj; }; /** * Export the delete function, return the modified object */ module.exports.del = function (obj, key) { multiple(del).apply(this, arguments); return obj; }; /** * Compose applying the function to a nested key */ function multiple (fn) { return function (obj, key, val) { var keys = key.split('.'); if (keys.length === 0) return; while (keys.length > 1) { key = keys.shift(); obj = find(obj, key); if (obj === null || obj === undefined) return; } key = keys.shift(); return fn(obj, key, val); }; } /** * Find an object by its key * * find({ first_name : 'Calvin' }, 'firstName') */ function find (obj, key) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) return obj[cased]; } } /** * Delete a value for a given key * * del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' } */ function del (obj, key) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) delete obj[cased]; } return obj; } /** * Replace an objects existing value with a new one * * replace({ a : 'b' }, 'a', 'c') -> { a : 'c' } */ function replace (obj, key, val) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) obj[cased] = val; } return obj; } }); require.register("segmentio-facade/lib/index.js", function(exports, require, module){ var Facade = require('./facade'); /** * Expose `Facade` facade. */ module.exports = Facade; /** * Expose specific-method facades. */ Facade.Alias = require('./alias'); Facade.Group = require('./group'); Facade.Identify = require('./identify'); Facade.Track = require('./track'); Facade.Page = require('./page'); }); require.register("segmentio-facade/lib/alias.js", function(exports, require, module){ var Facade = require('./facade'); var component = require('require-component')(require); var inherit = component('inherit'); /** * Expose `Alias` facade. */ module.exports = Alias; /** * Initialize a new `Alias` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @property {String} from * @property {String} to * @property {Object} options */ function Alias (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Alias, Facade); /** * Return type of facade. * * @return {String} */ Alias.prototype.action = function () { return 'alias'; }; /** * Setup some basic proxies. */ Alias.prototype.from = Facade.field('from'); Alias.prototype.to = Facade.field('to'); }); require.register("segmentio-facade/lib/facade.js", function(exports, require, module){ var component = require('require-component')(require); var clone = component('clone'); var isEnabled = component('./is-enabled'); var objCase = component('obj-case'); /** * Expose `Facade`. */ module.exports = Facade; /** * Initialize a new `Facade` with an `obj` of arguments. * * @param {Object} obj */ function Facade (obj) { if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = new Date(obj.timestamp); this.obj = obj; } /** * Return a proxy function for a `field` that will attempt to first use methods, * and fallback to accessing the underlying object directly. You can specify * deeply nested fields too like: * * this.proxy('options.Librato'); * * @param {String} field */ Facade.prototype.proxy = function (field) { var fields = field.split('.'); field = fields.shift(); // Call a function at the beginning to take advantage of facaded fields var obj = this[field] || this.field(field); if (!obj) return obj; if (typeof obj === 'function') obj = obj.call(this) || {}; if (fields.length === 0) return clone(obj); obj = objCase(obj, fields.join('.')); return clone(obj); }; /** * Directly access a specific `field` from the underlying object, returning a * clone so outsiders don't mess with stuff. * * @param {String} field * @return {Mixed} */ Facade.prototype.field = function (field) { return clone(this.obj[field]); }; /** * Utility method to always proxy a particular `field`. You can specify deeply * nested fields too like: * * Facade.proxy('options.Librato'); * * @param {String} field * @return {Function} */ Facade.proxy = function (field) { return function () { return this.proxy(field); }; }; /** * Utility method to directly access a `field`. * * @param {String} field * @return {Function} */ Facade.field = function (field) { return function () { return this.field(field); }; }; /** * Get the basic json object of this facade. * * @return {Object} */ Facade.prototype.json = function () { return clone(this.obj); }; /** * Get the options of a call (formerly called "context"). If you pass an * integration name, it will get the options for that specific integration, or * undefined if the integration is not enabled. * * @param {String} integration (optional) * @return {Object or Null} */ Facade.prototype.options = function (integration) { var options = clone(this.obj.options || this.obj.context) || {}; if (!integration) return clone(options); if (!this.enabled(integration)) return; options = options[integration] || objCase(options, integration) || {}; return typeof options === 'boolean' ? {} : clone(options); }; /** * Check whether an integration is enabled. * * @param {String} integration * @return {Boolean} */ Facade.prototype.enabled = function (integration) { var allEnabled = this.proxy('options.providers.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all'); if (typeof allEnabled !== 'boolean') allEnabled = true; var enabled = allEnabled && isEnabled(integration); var options = this.options(); // If the integration is explicitly enabled or disabled, use that // First, check options.providers for backwards compatibility if (options.providers && options.providers.hasOwnProperty(integration)) { enabled = options.providers[integration]; } // Next, check for the integration's existence in 'options' to enable it. // If the settings are a boolean, use that, otherwise it should be enabled. if (options.hasOwnProperty(integration)) { var settings = options[integration]; if (typeof settings === 'boolean') { enabled = settings; } else { enabled = true; } } return enabled ? true : false; }; /** * Get the `userAgent` option. * * @return {String} */ Facade.prototype.userAgent = function () {}; /** * Check whether the user is active. * * @return {Boolean} */ Facade.prototype.active = function () { var active = this.proxy('options.active'); if (active === null || active === undefined) active = true; return active; }; /** * Setup some basic proxies. */ Facade.prototype.userId = Facade.field('userId'); Facade.prototype.sessionId = Facade.field('sessionId'); Facade.prototype.channel = Facade.field('channel'); Facade.prototype.timestamp = Facade.field('timestamp'); Facade.prototype.ip = Facade.proxy('options.ip'); }); require.register("segmentio-facade/lib/group.js", function(exports, require, module){ var Facade = require('./facade'); var component = require('require-component')(require); var inherit = component('inherit'); var newDate = component('new-date'); /** * Expose `Group` facade. */ module.exports = Group; /** * Initialize a new `Group` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} groupId * @param {Object} properties * @param {Object} options */ function Group (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Group, Facade); /** * Get the facade's action. */ Group.prototype.action = function () { return 'group'; }; /** * Setup some basic proxies. */ Group.prototype.groupId = Facade.field('groupId'); /** * Get created or createdAt. * * @return {Date} */ Group.prototype.created = function(){ var created = this.proxy('traits.createdAt') || this.proxy('traits.created') || this.proxy('properties.createdAt') || this.proxy('properties.created'); if (created) return newDate(created); }; /** * Get the group's traits. * * @param {Object} aliases * @return {Object} */ Group.prototype.traits = function (aliases) { var ret = this.properties(); var id = this.groupId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get traits or properties. * * TODO: remove me * * @return {Object} */ Group.prototype.properties = function(){ return this.field('traits') || this.field('properties') || {}; }; }); require.register("segmentio-facade/lib/page.js", function(exports, require, module){ var component = require('require-component')(require); var Facade = component('./facade'); var inherit = component('inherit'); var Track = require('./track'); /** * Expose `Page` facade */ module.exports = Page; /** * Initialize new `Page` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Page(dictionary){ Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Page, Facade); /** * Get the facade's action. * * @return {String} */ Page.prototype.action = function(){ return 'page'; }; /** * Proxies */ Page.prototype.category = Facade.field('category'); Page.prototype.name = Facade.field('name'); /** * Get the page properties mixing `category` and `name`. * * @return {Object} */ Page.prototype.properties = function(){ var props = this.field('properties') || {}; var category = this.category(); var name = this.name(); if (category) props.category = category; if (name) props.name = name; return props; }; /** * Get the page fullName. * * @return {String} */ Page.prototype.fullName = function(){ var category = this.category(); var name = this.name(); return name && category ? category + ' ' + name : name; }; /** * Get event with `name`. * * @return {String} */ Page.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Page' : 'Loaded a Page'; }; /** * Convert this Page to a Track facade with `name`. * * @param {String} name * @return {Track} */ Page.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), properties: props }); }; }); require.register("segmentio-facade/lib/identify.js", function(exports, require, module){ var component = require('require-component')(require); var clone = component('clone'); var Facade = component('./facade'); var inherit = component('inherit'); var isEmail = component('is-email'); var newDate = component('new-date'); var trim = component('trim'); /** * Expose `Idenfity` facade. */ module.exports = Identify; /** * Initialize a new `Identify` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} sessionId * @param {Object} traits * @param {Object} options */ function Identify (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Identify, Facade); /** * Get the facade's action. */ Identify.prototype.action = function () { return 'identify'; }; /** * Get the user's traits. * * @param {Object} aliases * @return {Object} */ Identify.prototype.traits = function (aliases) { var ret = this.field('traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get the user's email, falling back to their user ID if it's a valid email. * * @return {String} */ Identify.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the user's created date, optionally looking for `createdAt` since lots of * people do that instead. * * @return {Date or Undefined} */ Identify.prototype.created = function () { var created = this.proxy('traits.created') || this.proxy('traits.createdAt'); if (created) return newDate(created); }; /** * Get the company created date. * * @return {Date or undefined} */ Identify.prototype.companyCreated = function(){ var created = this.proxy('traits.company.created') || this.proxy('traits.company.createdAt'); if (created) return newDate(created); }; /** * Get the user's name, optionally combining a first and last name if that's all * that was provided. * * @return {String or Undefined} */ Identify.prototype.name = function () { var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name); var firstName = this.firstName(); var lastName = this.lastName(); if (firstName && lastName) return trim(firstName + ' ' + lastName); }; /** * Get the user's first name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.firstName = function () { var firstName = this.proxy('traits.firstName'); if (typeof firstName === 'string') return trim(firstName); var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name).split(' ')[0]; }; /** * Get the user's last name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.lastName = function () { var lastName = this.proxy('traits.lastName'); if (typeof lastName === 'string') return trim(lastName); var name = this.proxy('traits.name'); if (typeof name !== 'string') return; var space = trim(name).indexOf(' '); if (space === -1) return; return trim(name.substr(space + 1)); }; /** * Get the user's unique id. * * @return {String or undefined} */ Identify.prototype.uid = function(){ return this.userId() || this.username() || this.email(); }; /** * Get description. * * @return {String} */ Identify.prototype.description = function(){ return this.proxy('traits.description') || this.proxy('traits.background'); }; /** * Setup sme basic "special" trait proxies. */ Identify.prototype.username = Facade.proxy('traits.username'); Identify.prototype.website = Facade.proxy('traits.website'); Identify.prototype.phone = Facade.proxy('traits.phone'); Identify.prototype.address = Facade.proxy('traits.address'); Identify.prototype.avatar = Facade.proxy('traits.avatar'); }); require.register("segmentio-facade/lib/is-enabled.js", function(exports, require, module){ /** * A few integrations are disabled by default. They must be explicitly * enabled by setting options[Provider] = true. */ var disabled = { Salesforce: true, Marketo: true }; /** * Check whether an integration should be enabled by default. * * @param {String} integration * @return {Boolean} */ module.exports = function (integration) { return ! disabled[integration]; }; }); require.register("segmentio-facade/lib/track.js", function(exports, require, module){ var component = require('require-component')(require); var clone = component('clone'); var Facade = component('./facade'); var Identify = component('./identify'); var inherit = component('inherit'); var isEmail = component('is-email'); var traverse = component('isodate-traverse'); /** * Expose `Track` facade. */ module.exports = Track; /** * Initialize a new `Track` facade with a `dictionary` of arguments. * * @param {object} dictionary * @property {String} event * @property {String} userId * @property {String} sessionId * @property {Object} properties * @property {Object} options */ function Track (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Track, Facade); /** * Return the facade's action. * * @return {String} */ Track.prototype.action = function () { return 'track'; }; /** * Setup some basic proxies. */ Track.prototype.event = Facade.field('event'); Track.prototype.value = Facade.proxy('properties.value'); /** * Misc */ Track.prototype.category = Facade.proxy('properties.category'); Track.prototype.country = Facade.proxy('properties.country'); Track.prototype.state = Facade.proxy('properties.state'); Track.prototype.city = Facade.proxy('properties.city'); Track.prototype.zip = Facade.proxy('properties.zip'); /** * Ecommerce */ Track.prototype.id = Facade.proxy('properties.id'); Track.prototype.sku = Facade.proxy('properties.sku'); Track.prototype.tax = Facade.proxy('properties.tax'); Track.prototype.name = Facade.proxy('properties.name'); Track.prototype.price = Facade.proxy('properties.price'); Track.prototype.total = Facade.proxy('properties.total'); Track.prototype.coupon = Facade.proxy('properties.coupon'); Track.prototype.orderId = Facade.proxy('properties.orderId'); Track.prototype.shipping = Facade.proxy('properties.shipping'); /** * Order id. * * @return {String} * @api public */ Track.prototype.orderId = function(){ return this.proxy('properties.id') || this.proxy('properties.orderId'); }; /** * Get subtotal. * * @return {Number} */ Track.prototype.subtotal = function(){ var subtotal = this.obj.properties.subtotal; var total = this.total(); var n; if (subtotal) return subtotal; if (!total) return 0; if (n = this.tax()) total -= n; if (n = this.shipping()) total -= n; return total; }; /** * Get products. * * @return {Array} */ Track.prototype.products = function(){ var props = this.obj.properties || {}; return props.products || []; }; /** * Get quantity. * * @return {Number} */ Track.prototype.quantity = function(){ var props = this.obj.properties || {}; return props.quantity || 1; }; /** * Get currency. * * @return {String} */ Track.prototype.currency = function(){ var props = this.obj.properties || {}; return props.currency || 'USD'; }; /** * BACKWARDS COMPATIBILITY: should probably re-examine where these come from. */ Track.prototype.referrer = Facade.proxy('properties.referrer'); Track.prototype.query = Facade.proxy('options.query'); /** * Get the call's properties. * * @param {Object} aliases * @return {Object} */ Track.prototype.properties = function (aliases) { var ret = this.field('properties') || {}; aliases = aliases || {}; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('properties.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return clone(traverse(ret)); }; /** * Get the call's "super properties" which are just traits that have been * passed in as if from an identify call. * * @return {Object} */ Track.prototype.traits = function () { return this.proxy('options.traits') || {}; }; /** * Get the call's username. * * @return {String or Undefined} */ Track.prototype.username = function () { return this.proxy('traits.username') || this.proxy('properties.username') || this.userId() || this.sessionId(); }; /** * Get the call's email, using an the user ID if it's a valid email. * * @return {String or Undefined} */ Track.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the call's revenue, parsing it from a string with an optional leading * dollar sign. * * @return {String or Undefined} */ Track.prototype.revenue = function () { var revenue = this.proxy('properties.revenue'); if (!revenue) return; if (typeof revenue === 'number') return revenue; if (typeof revenue !== 'string') return; revenue = revenue.replace(/\$/g, ''); revenue = parseFloat(revenue); if (!isNaN(revenue)) return revenue; }; /** * Get cents. * * @return {Number} */ Track.prototype.cents = function(){ var revenue = this.revenue(); return 'number' != typeof revenue ? this.value() || 0 : revenue * 100; }; /** * A utility to turn the pieces of a track call into an identify. Used for * integrations with super properties or rate limits. * * TODO: remove me. * * @return {Facade} */ Track.prototype.identify = function () { var json = this.json(); json.traits = this.traits(); return new Identify(json); }; }); require.register("segmentio-is-email/index.js", function(exports, require, module){ /** * Expose `isEmail`. */ module.exports = isEmail; /** * Email address matcher. */ var matcher = /.+\@.+\..+/; /** * Loosely validate an email address. * * @param {String} string * @return {Boolean} */ function isEmail (string) { return matcher.test(string); } }); require.register("segmentio-is-meta/index.js", function(exports, require, module){ module.exports = function isMeta (e) { if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true; // Logic that handles checks for the middle mouse button, based // on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466). var which = e.which, button = e.button; if (!which && button !== undefined) { return (!button & 1) && (!button & 2) && (button & 4); } else if (which === 2) { return true; } return false; }; }); require.register("segmentio-isodate/index.js", function(exports, require, module){ /** * Matcher, slightly modified from: * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js */ var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/; /** * Convert an ISO date string to a date. Fallback to native `Date.parse`. * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js * * @param {String} iso * @return {Date} */ exports.parse = function (iso) { var numericKeys = [1, 5, 6, 7, 8, 11, 12]; var arr = matcher.exec(iso); var offset = 0; // fallback to native parsing if (!arr) return new Date(iso); // remove undefined values for (var i = 0, val; val = numericKeys[i]; i++) { arr[val] = parseInt(arr[val], 10) || 0; } // allow undefined days and months arr[2] = parseInt(arr[2], 10) || 1; arr[3] = parseInt(arr[3], 10) || 1; // month is 0-11 arr[2]--; // allow abitrary sub-second precision if (arr[8]) arr[8] = (arr[8] + '00').substring(0, 3); // apply timezone if one exists if (arr[4] == ' ') { offset = new Date().getTimezoneOffset(); } else if (arr[9] !== 'Z' && arr[10]) { offset = arr[11] * 60 + arr[12]; if ('+' == arr[10]) offset = 0 - offset; } var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]); return new Date(millis); }; /** * Checks whether a `string` is an ISO date string. `strict` mode requires that * the date string at least have a year, month and date. * * @param {String} string * @param {Boolean} strict * @return {Boolean} */ exports.is = function (string, strict) { if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false; return matcher.test(string); }; }); require.register("segmentio-isodate-traverse/index.js", function(exports, require, module){ var is = require('is'); var isodate = require('isodate'); var each; try { each = require('each'); } catch (err) { each = require('each-component'); } /** * Expose `traverse`. */ module.exports = traverse; /** * Traverse an object or array, and return a clone with all ISO strings parsed * into Date objects. * * @param {Object} obj * @return {Object} */ function traverse (input, strict) { if (strict === undefined) strict = true; if (is.object(input)) { return object(input, strict); } else if (is.array(input)) { return array(input, strict); } } /** * Object traverser. * * @param {Object} obj * @param {Boolean} strict * @return {Object} */ function object (obj, strict) { each(obj, function (key, val) { if (isodate.is(val, strict)) { obj[key] = isodate.parse(val); } else if (is.object(val) || is.array(val)) { traverse(val, strict); } }); return obj; } /** * Array traverser. * * @param {Array} arr * @param {Boolean} strict * @return {Array} */ function array (arr, strict) { each(arr, function (val, x) { if (is.object(val)) { traverse(val, strict); } else if (isodate.is(val, strict)) { arr[x] = isodate.parse(val); } }); return arr; } }); require.register("component-json-fallback/index.js", function(exports, require, module){ /* json2.js 2014-02-04 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx, escapable, gap, indent, meta, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); module.exports = JSON; }); require.register("segmentio-json/index.js", function(exports, require, module){ module.exports = 'undefined' == typeof JSON ? require('json-fallback') : JSON; }); require.register("segmentio-new-date/lib/index.js", function(exports, require, module){ var is = require('is'); var isodate = require('isodate'); var milliseconds = require('./milliseconds'); var seconds = require('./seconds'); /** * Returns a new Javascript Date object, allowing a variety of extra input types * over the native Date constructor. * * @param {Date|String|Number} val */ module.exports = function newDate (val) { if (is.date(val)) return val; if (is.number(val)) return new Date(toMs(val)); // date strings if (isodate.is(val)) return isodate.parse(val); if (milliseconds.is(val)) return milliseconds.parse(val); if (seconds.is(val)) return seconds.parse(val); // fallback to Date.parse return new Date(val); }; /** * If the number passed val is seconds from the epoch, turn it into milliseconds. * Milliseconds would be greater than 31557600000 (December 31, 1970). * * @param {Number} num */ function toMs (num) { if (num < 31557600000) return num * 1000; return num; } }); require.register("segmentio-new-date/lib/milliseconds.js", function(exports, require, module){ /** * Matcher. */ var matcher = /\d{13}/; /** * Check whether a string is a millisecond date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a millisecond string to a date. * * @param {String} millis * @return {Date} */ exports.parse = function (millis) { millis = parseInt(millis, 10); return new Date(millis); }; }); require.register("segmentio-new-date/lib/seconds.js", function(exports, require, module){ /** * Matcher. */ var matcher = /\d{10}/; /** * Check whether a string is a second date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a second string to a date. * * @param {String} seconds * @return {Date} */ exports.parse = function (seconds) { var millis = parseInt(seconds, 10) * 1000; return new Date(millis); }; }); require.register("segmentio-store.js/store.js", function(exports, require, module){ ;(function(win){ var store = {}, doc = win.document, localStorageName = 'localStorage', namespace = '__storejs__', storage store.disabled = false store.set = function(key, value) {} store.get = function(key) {} store.remove = function(key) {} store.clear = function() {} store.transact = function(key, defaultVal, transactionFn) { var val = store.get(key) if (transactionFn == null) { transactionFn = defaultVal defaultVal = null } if (typeof val == 'undefined') { val = defaultVal || {} } transactionFn(val) store.set(key, val) } store.getAll = function() {} store.serialize = function(value) { return JSON.stringify(value) } store.deserialize = function(value) { if (typeof value != 'string') { return undefined } try { return JSON.parse(value) } catch(e) { return value || undefined } } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 function isLocalStorageNameSupported() { try { return (localStorageName in win && win[localStorageName]) } catch(err) { return false } } if (isLocalStorageNameSupported()) { storage = win[localStorageName] store.set = function(key, val) { if (val === undefined) { return store.remove(key) } storage.setItem(key, store.serialize(val)) return val } store.get = function(key) { return store.deserialize(storage.getItem(key)) } store.remove = function(key) { storage.removeItem(key) } store.clear = function() { storage.clear() } store.getAll = function() { var ret = {} for (var i=0; i<storage.length; ++i) { var key = storage.key(i) ret[key] = store.get(key) } return ret } } else if (doc.documentElement.addBehavior) { var storageOwner, storageContainer // Since #userData storage applies only to specific paths, we need to // somehow link our data to a specific path. We choose /favicon.ico // as a pretty safe option, since all browsers already make a request to // this URL anyway and being a 404 will not hurt us here. We wrap an // iframe pointing to the favicon in an ActiveXObject(htmlfile) object // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx) // since the iframe access rules appear to allow direct access and // manipulation of the document element, even for a 404 page. This // document can be used instead of the current document (which would // have been limited to the current path) to perform #userData storage. try { storageContainer = new ActiveXObject('htmlfile') storageContainer.open() storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>') storageContainer.close() storageOwner = storageContainer.w.frames[0].document storage = storageOwner.createElement('div') } catch(e) { // somehow ActiveXObject instantiation failed (perhaps some special // security settings or otherwse), fall back to per-path storage storage = doc.createElement('div') storageOwner = doc.body } function withIEStorage(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx storageOwner.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(store, args) storageOwner.removeChild(storage) return result } } // In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40 var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g") function ieKeyFix(key) { return key.replace(forbiddenCharsRegex, '___') } store.set = withIEStorage(function(storage, key, val) { key = ieKeyFix(key) if (val === undefined) { return store.remove(key) } storage.setAttribute(key, store.serialize(val)) storage.save(localStorageName) return val }) store.get = withIEStorage(function(storage, key) { key = ieKeyFix(key) return store.deserialize(storage.getAttribute(key)) }) store.remove = withIEStorage(function(storage, key) { key = ieKeyFix(key) storage.removeAttribute(key) storage.save(localStorageName) }) store.clear = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes storage.load(localStorageName) for (var i=0, attr; attr=attributes[i]; i++) { storage.removeAttribute(attr.name) } storage.save(localStorageName) }) store.getAll = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes var ret = {} for (var i=0, attr; attr=attributes[i]; ++i) { var key = ieKeyFix(attr.name) ret[attr.name] = store.deserialize(storage.getAttribute(key)) } return ret }) } try { store.set(namespace, namespace) if (store.get(namespace) != namespace) { store.disabled = true } store.remove(namespace) } catch(e) { store.disabled = true } store.enabled = !store.disabled if (typeof module != 'undefined' && module.exports) { module.exports = store } else if (typeof define === 'function' && define.amd) { define(store) } else { win.store = store } })(this.window || global); }); require.register("segmentio-top-domain/index.js", function(exports, require, module){ var url = require('url'); // Official Grammar: http://tools.ietf.org/html/rfc883#page-56 // Look for tlds with up to 2-6 characters. module.exports = function (urlStr) { var host = url.parse(urlStr).hostname , topLevel = host.match(/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i); return topLevel ? topLevel[0] : host; }; }); require.register("visionmedia-debug/index.js", function(exports, require, module){ if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }); require.register("visionmedia-debug/debug.js", function(exports, require, module){ /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }); require.register("yields-prevent/index.js", function(exports, require, module){ /** * prevent default on the given `e`. * * examples: * * anchor.onclick = prevent; * anchor.onclick = function(e){ * if (something) return prevent(e); * }; * * @param {Event} e */ module.exports = function(e){ e = e || window.event return e.preventDefault ? e.preventDefault() : e.returnValue = false; }; }); require.register("analytics/lib/index.js", function(exports, require, module){ /** * Analytics.js * * (C) 2013 Segment.io Inc. */ var Analytics = require('./analytics'); var createIntegration = require('integration'); var each = require('each'); var Integrations = require('integrations'); /** * Expose the `analytics` singleton. */ var analytics = module.exports = exports = new Analytics(); /** * Expose require */ analytics.require = require; /** * Expose `VERSION`. */ exports.VERSION = '1.3.7'; /** * Add integrations. */ each(Integrations, function (name, Integration) { analytics.use(Integration); }); }); require.register("analytics/lib/analytics.js", function(exports, require, module){ var after = require('after'); var bind = require('bind'); var callback = require('callback'); var canonical = require('canonical'); var clone = require('clone'); var cookie = require('./cookie'); var debug = require('debug'); var defaults = require('defaults'); var each = require('each'); var Emitter = require('emitter'); var group = require('./group'); var is = require('is'); var isEmail = require('is-email'); var isMeta = require('is-meta'); var newDate = require('new-date'); var on = require('event').bind; var prevent = require('prevent'); var querystring = require('querystring'); var size = require('object').length; var store = require('./store'); var url = require('url'); var user = require('./user'); var Facade = require('facade'); var Identify = Facade.Identify; var Group = Facade.Group; var Alias = Facade.Alias; var Track = Facade.Track; var Page = Facade.Page; /** * Expose `Analytics`. */ module.exports = Analytics; /** * Initialize a new `Analytics` instance. */ function Analytics () { this.Integrations = {}; this._integrations = {}; this._readied = false; this._timeout = 300; this._user = user; // BACKWARDS COMPATIBILITY bind.all(this); var self = this; this.on('initialize', function (settings, options) { if (options.initialPageview) self.page(); }); this.on('initialize', function () { self._parseQuery(); }); } /** * Event Emitter. */ Emitter(Analytics.prototype); /** * Use a `plugin`. * * @param {Function} plugin * @return {Analytics} */ Analytics.prototype.use = function (plugin) { plugin(this); return this; }; /** * Define a new `Integration`. * * @param {Function} Integration * @return {Analytics} */ Analytics.prototype.addIntegration = function (Integration) { var name = Integration.prototype.name; if (!name) throw new TypeError('attempted to add an invalid integration'); this.Integrations[name] = Integration; return this; }; /** * Initialize with the given integration `settings` and `options`. Aliased to * `init` for convenience. * * @param {Object} settings * @param {Object} options (optional) * @return {Analytics} */ Analytics.prototype.init = Analytics.prototype.initialize = function (settings, options) { settings = settings || {}; options = options || {}; this._options(options); this._readied = false; this._integrations = {}; // load user now that options are set user.load(); group.load(); // clean unknown integrations from settings var self = this; each(settings, function (name) { var Integration = self.Integrations[name]; if (!Integration) delete settings[name]; }); // make ready callback var ready = after(size(settings), function () { self._readied = true; self.emit('ready'); }); // initialize integrations, passing ready each(settings, function (name, opts) { var Integration = self.Integrations[name]; if (options.initialPageview && opts.initialPageview === false) { Integration.prototype.page = after(2, Integration.prototype.page); } var integration = new Integration(clone(opts)); integration.once('ready', ready); integration.initialize(); self._integrations[name] = integration; }); // backwards compat with angular plugin. // TODO: remove this.initialized = true; this.emit('initialize', settings, options); return this; }; /** * Identify a user by optional `id` and `traits`. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.identify = function (id, traits, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = user.id(); // clone traits before we manipulate so we don't do anything uncouth, and take // from `user` so that we carryover anonymous traits user.identify(id, traits); id = user.id(); traits = user.traits(); this._invoke('identify', new Identify({ options: options, traits: traits, userId: id })); // emit this.emit('identify', id, traits, options); this._callback(fn); return this; }; /** * Return the current user. * * @return {Object} */ Analytics.prototype.user = function () { return user; }; /** * Identify a group by optional `id` and `traits`. Or, if no arguments are * supplied, return the current group. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics or Object} */ Analytics.prototype.group = function (id, traits, options, fn) { if (0 === arguments.length) return group; if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = group.id(); // grab from group again to make sure we're taking from the source group.identify(id, traits); id = group.id(); traits = group.traits(); this._invoke('group', new Group({ options: options, traits: traits, groupId: id })); this.emit('group', id, traits, options); this._callback(fn); return this; }; /** * Track an `event` that a user has triggered with optional `properties`. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.track = function (event, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = null, properties = null; this._invoke('track', new Track({ properties: properties, options: options, event: event })); this.emit('track', event, properties, options); this._callback(fn); return this; }; /** * Helper method to track an outbound link that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackClick`. * * @param {Element or Array} links * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackClick = Analytics.prototype.trackLink = function (links, event, properties) { if (!links) return this; if (is.element(links)) links = [links]; // always arrays, handles jquery var self = this; each(links, function (el) { on(el, 'click', function (e) { var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); if (el.href && el.target !== '_blank' && !isMeta(e)) { prevent(e); self._callback(function () { window.location.href = el.href; }); } }); }); return this; }; /** * Helper method to track an outbound form that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackSubmit`. * * @param {Element or Array} forms * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function (forms, event, properties) { if (!forms) return this; if (is.element(forms)) forms = [forms]; // always arrays, handles jquery var self = this; each(forms, function (el) { function handler (e) { prevent(e); var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); self._callback(function () { el.submit(); }); } // support the events happening through jQuery or Zepto instead of through // the normal DOM API, since `el.submit` doesn't bubble up events... var $ = window.jQuery || window.Zepto; if ($) { $(el).submit(handler); } else { on(el, 'submit', handler); } }); return this; }; /** * Trigger a pageview, labeling the current page with an optional `category`, * `name` and `properties`. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object or String} properties (or path) (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.page = function (category, name, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = properties = null; if (is.fn(name)) fn = name, options = properties = name = null; if (is.object(category)) options = name, properties = category, name = category = null; if (is.object(name)) options = properties, properties = name, name = null; if (is.string(category) && !is.string(name)) name = category, category = null; var defs = { path: canonicalPath(), referrer: document.referrer, title: document.title, url: canonicalUrl(), search: location.search }; if (name) defs.name = name; if (category) defs.category = category; properties = clone(properties) || {}; defaults(properties, defs); this._invoke('page', new Page({ properties: properties, category: category, options: options, name: name })); this.emit('page', category, name, properties, options); this._callback(fn); return this; }; /** * BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call. * * @param {String} url (optional) * @param {Object} options (optional) * @return {Analytics} * @api private */ Analytics.prototype.pageview = function (url, options) { var properties = {}; if (url) properties.path = url; this.page(properties); return this; }; /** * Merge two previously unassociated user identities. * * @param {String} to * @param {String} from (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.alias = function (to, from, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(from)) fn = from, options = null, from = null; if (is.object(from)) options = from, from = null; this._invoke('alias', new Alias({ options: options, from: from, to: to })); this.emit('alias', to, from, options); this._callback(fn); return this; }; /** * Register a `fn` to be fired when all the analytics services are ready. * * @param {Function} fn * @return {Analytics} */ Analytics.prototype.ready = function (fn) { if (!is.fn(fn)) return this; this._readied ? callback.async(fn) : this.once('ready', fn); return this; }; /** * Set the `timeout` (in milliseconds) used for callbacks. * * @param {Number} timeout */ Analytics.prototype.timeout = function (timeout) { this._timeout = timeout; }; /** * Enable or disable debug. * * @param {String or Boolean} str */ Analytics.prototype.debug = function(str){ if (0 == arguments.length || str) { debug.enable('analytics:' + (str || '*')); } else { debug.disable(); } }; /** * Apply options. * * @param {Object} options * @return {Analytics} * @api private */ Analytics.prototype._options = function (options) { options = options || {}; cookie.options(options.cookie); store.options(options.localStorage); user.options(options.user); group.options(options.group); return this; }; /** * Callback a `fn` after our defined timeout period. * * @param {Function} fn * @return {Analytics} * @api private */ Analytics.prototype._callback = function (fn) { callback.async(fn, this._timeout); return this; }; /** * Call `method` with `facade` on all enabled integrations. * * @param {String} method * @param {Facade} facade * @return {Analytics} * @api private */ Analytics.prototype._invoke = function (method, facade) { var options = facade.options(); each(this._integrations, function (name, integration) { if (!facade.enabled(name)) return; integration.invoke.call(integration, method, facade); }); return this; }; /** * Push `args`. * * @param {Array} args * @api private */ Analytics.prototype.push = function(args){ var method = args.shift(); if (!this[method]) return; this[method].apply(this, args); }; /** * Parse the query string for callable methods. * * @return {Analytics} * @api private */ Analytics.prototype._parseQuery = function () { // Identify and track any `ajs_uid` and `ajs_event` parameters in the URL. var q = querystring.parse(window.location.search); if (q.ajs_uid) this.identify(q.ajs_uid); if (q.ajs_event) this.track(q.ajs_event); return this; }; /** * Return the canonical path for the page. * * @return {String} */ function canonicalPath () { var canon = canonical(); if (!canon) return window.location.pathname; var parsed = url.parse(canon); return parsed.pathname; } /** * Return the canonical URL for the page, without the hash. * * @return {String} */ function canonicalUrl () { var canon = canonical(); if (canon) return canon; var url = window.location.href; var i = url.indexOf('#'); return -1 == i ? url : url.slice(0, i); } }); require.register("analytics/lib/cookie.js", function(exports, require, module){ var bind = require('bind'); var cookie = require('cookie'); var clone = require('clone'); var defaults = require('defaults'); var json = require('json'); var topDomain = require('top-domain'); /** * Initialize a new `Cookie` with `options`. * * @param {Object} options */ function Cookie (options) { this.options(options); } /** * Get or set the cookie options. * * @param {Object} options * @field {Number} maxage (1 year) * @field {String} domain * @field {String} path * @field {Boolean} secure */ Cookie.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; var domain = '.' + topDomain(window.location.href); // localhost cookies are special: http://curl.haxx.se/rfc/cookie_spec.html if (domain === '.localhost') domain = ''; defaults(options, { maxage: 31536000000, // default to a year path: '/', domain: domain }); this._options = options; }; /** * Set a `key` and `value` in our cookie. * * @param {String} key * @param {Object} value * @return {Boolean} saved */ Cookie.prototype.set = function (key, value) { try { value = json.stringify(value); cookie(key, value, clone(this._options)); return true; } catch (e) { return false; } }; /** * Get a value from our cookie by `key`. * * @param {String} key * @return {Object} value */ Cookie.prototype.get = function (key) { try { var value = cookie(key); value = value ? json.parse(value) : null; return value; } catch (e) { return null; } }; /** * Remove a value from our cookie by `key`. * * @param {String} key * @return {Boolean} removed */ Cookie.prototype.remove = function (key) { try { cookie(key, null, clone(this._options)); return true; } catch (e) { return false; } }; /** * Expose the cookie singleton. */ module.exports = bind.all(new Cookie()); /** * Expose the `Cookie` constructor. */ module.exports.Cookie = Cookie; }); require.register("analytics/lib/entity.js", function(exports, require, module){ var traverse = require('isodate-traverse'); var defaults = require('defaults'); var cookie = require('./cookie'); var store = require('./store'); var extend = require('extend'); var clone = require('clone'); /** * Expose `Entity` */ module.exports = Entity; /** * Initialize new `Entity` with `options`. * * @param {Object} options */ function Entity(options){ this.options(options); } /** * Get or set storage `options`. * * @param {Object} options * @property {Object} cookie * @property {Object} localStorage * @property {Boolean} persist (default: `true`) */ Entity.prototype.options = function (options) { if (arguments.length === 0) return this._options; options || (options = {}); defaults(options, this.defaults || {}); this._options = options; }; /** * Get or set the entity's `id`. * * @param {String} id */ Entity.prototype.id = function (id) { switch (arguments.length) { case 0: return this._getId(); case 1: return this._setId(id); } }; /** * Get the entity's id. * * @return {String} */ Entity.prototype._getId = function () { var ret = this._options.persist ? cookie.get(this._options.cookie.key) : this._id; return ret === undefined ? null : ret; }; /** * Set the entity's `id`. * * @param {String} id */ Entity.prototype._setId = function (id) { if (this._options.persist) { cookie.set(this._options.cookie.key, id); } else { this._id = id; } }; /** * Get or set the entity's `traits`. * * BACKWARDS COMPATIBILITY: aliased to `properties` * * @param {Object} traits */ Entity.prototype.properties = Entity.prototype.traits = function (traits) { switch (arguments.length) { case 0: return this._getTraits(); case 1: return this._setTraits(traits); } }; /** * Get the entity's traits. Always convert ISO date strings into real dates, * since they aren't parsed back from local storage. * * @return {Object} */ Entity.prototype._getTraits = function () { var ret = this._options.persist ? store.get(this._options.localStorage.key) : this._traits; return ret ? traverse(clone(ret)) : {}; }; /** * Set the entity's `traits`. * * @param {Object} traits */ Entity.prototype._setTraits = function (traits) { traits || (traits = {}); if (this._options.persist) { store.set(this._options.localStorage.key, traits); } else { this._traits = traits; } }; /** * Identify the entity with an `id` and `traits`. If we it's the same entity, * extend the existing `traits` instead of overwriting. * * @param {String} id * @param {Object} traits */ Entity.prototype.identify = function (id, traits) { traits || (traits = {}); var current = this.id(); if (current === null || current === id) traits = extend(this.traits(), traits); if (id) this.id(id); this.debug('identify %o, %o', id, traits); this.traits(traits); this.save(); }; /** * Save the entity to local storage and the cookie. * * @return {Boolean} */ Entity.prototype.save = function () { if (!this._options.persist) return false; cookie.set(this._options.cookie.key, this.id()); store.set(this._options.localStorage.key, this.traits()); return true; }; /** * Log the entity out, reseting `id` and `traits` to defaults. */ Entity.prototype.logout = function () { this.id(null); this.traits({}); cookie.remove(this._options.cookie.key); store.remove(this._options.localStorage.key); }; /** * Reset all entity state, logging out and returning options to defaults. */ Entity.prototype.reset = function () { this.logout(); this.options({}); }; /** * Load saved entity `id` or `traits` from storage. */ Entity.prototype.load = function () { this.id(cookie.get(this._options.cookie.key)); this.traits(store.get(this._options.localStorage.key)); }; }); require.register("analytics/lib/group.js", function(exports, require, module){ var debug = require('debug')('analytics:group'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); /** * Group defaults */ Group.defaults = { persist: true, cookie: { key: 'ajs_group_id' }, localStorage: { key: 'ajs_group_properties' } }; /** * Initialize a new `Group` with `options`. * * @param {Object} options */ function Group (options) { this.defaults = Group.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(Group, Entity); /** * Expose the group singleton. */ module.exports = bind.all(new Group()); /** * Expose the `Group` constructor. */ module.exports.Group = Group; }); require.register("analytics/lib/store.js", function(exports, require, module){ var bind = require('bind'); var defaults = require('defaults'); var store = require('store'); /** * Initialize a new `Store` with `options`. * * @param {Object} options */ function Store (options) { this.options(options); } /** * Set the `options` for the store. * * @param {Object} options * @field {Boolean} enabled (true) */ Store.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; defaults(options, { enabled : true }); this.enabled = options.enabled && store.enabled; this._options = options; }; /** * Set a `key` and `value` in local storage. * * @param {String} key * @param {Object} value */ Store.prototype.set = function (key, value) { if (!this.enabled) return false; return store.set(key, value); }; /** * Get a value from local storage by `key`. * * @param {String} key * @return {Object} */ Store.prototype.get = function (key) { if (!this.enabled) return null; return store.get(key); }; /** * Remove a value from local storage by `key`. * * @param {String} key */ Store.prototype.remove = function (key) { if (!this.enabled) return false; return store.remove(key); }; /** * Expose the store singleton. */ module.exports = bind.all(new Store()); /** * Expose the `Store` constructor. */ module.exports.Store = Store; }); require.register("analytics/lib/user.js", function(exports, require, module){ var debug = require('debug')('analytics:user'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); var cookie = require('./cookie'); /** * User defaults */ User.defaults = { persist: true, cookie: { key: 'ajs_user_id', oldKey: 'ajs_user' }, localStorage: { key: 'ajs_user_traits' } }; /** * Initialize a new `User` with `options`. * * @param {Object} options */ function User (options) { this.defaults = User.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(User, Entity); /** * Load saved user `id` or `traits` from storage. */ User.prototype.load = function () { if (this._loadOldCookie()) return; Entity.prototype.load.call(this); }; /** * BACKWARDS COMPATIBILITY: Load the old user from the cookie. * * @return {Boolean} * @api private */ User.prototype._loadOldCookie = function () { var user = cookie.get(this._options.cookie.oldKey); if (!user) return false; this.id(user.id); this.traits(user.traits); cookie.remove(this._options.cookie.oldKey); return true; }; /** * Expose the user singleton. */ module.exports = bind.all(new User()); /** * Expose the `User` constructor. */ module.exports.User = User; }); require.register("segmentio-analytics.js-integrations/lib/slugs.json", function(exports, require, module){ module.exports = [ "adroll", "adwords", "amplitude", "awesm", "awesomatic", "bing-ads", "bronto", "bugherd", "bugsnag", "chartbeat", "churnbee", "clicktale", "clicky", "comscore", "crazy-egg", "curebit", "customerio", "drip", "errorception", "evergage", "facebook-ads", "foxmetrics", "gauges", "get-satisfaction", "google-analytics", "google-tag-manager", "gosquared", "heap", "hittail", "hubspot", "improvely", "inspectlet", "intercom", "keen-io", "kissmetrics", "klaviyo", "leadlander", "livechat", "lucky-orange", "lytics", "mixpanel", "mojn", "mouseflow", "mousestats", "olark", "optimizely", "perfect-audience", "pingdom", "preact", "qualaroo", "quantcast", "rollbar", "saasquatch", "sentry", "snapengage", "spinnakr", "tapstream", "trakio", "twitter-ads", "usercycle", "userfox", "uservoice", "vero", "visual-website-optimizer", "webengage", "woopra", "yandex-metrica" ] }); require.alias("avetisk-defaults/index.js", "analytics/deps/defaults/index.js"); require.alias("avetisk-defaults/index.js", "defaults/index.js"); require.alias("component-clone/index.js", "analytics/deps/clone/index.js"); require.alias("component-clone/index.js", "clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-cookie/index.js", "analytics/deps/cookie/index.js"); require.alias("component-cookie/index.js", "cookie/index.js"); require.alias("component-each/index.js", "analytics/deps/each/index.js"); require.alias("component-each/index.js", "each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("component-emitter/index.js", "analytics/deps/emitter/index.js"); require.alias("component-emitter/index.js", "emitter/index.js"); require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js"); require.alias("component-event/index.js", "analytics/deps/event/index.js"); require.alias("component-event/index.js", "event/index.js"); require.alias("component-inherit/index.js", "analytics/deps/inherit/index.js"); require.alias("component-inherit/index.js", "inherit/index.js"); require.alias("component-object/index.js", "analytics/deps/object/index.js"); require.alias("component-object/index.js", "object/index.js"); require.alias("component-querystring/index.js", "analytics/deps/querystring/index.js"); require.alias("component-querystring/index.js", "querystring/index.js"); require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js"); require.alias("component-url/index.js", "analytics/deps/url/index.js"); require.alias("component-url/index.js", "url/index.js"); require.alias("ianstormtaylor-bind/index.js", "analytics/deps/bind/index.js"); require.alias("ianstormtaylor-bind/index.js", "bind/index.js"); require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js"); require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js"); require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js"); require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js"); require.alias("ianstormtaylor-callback/index.js", "analytics/deps/callback/index.js"); require.alias("ianstormtaylor-callback/index.js", "callback/index.js"); require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js"); require.alias("ianstormtaylor-is/index.js", "analytics/deps/is/index.js"); require.alias("ianstormtaylor-is/index.js", "is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-after/index.js", "analytics/deps/after/index.js"); require.alias("segmentio-after/index.js", "after/index.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "analytics/deps/integration/lib/index.js"); require.alias("segmentio-analytics.js-integration/lib/protos.js", "analytics/deps/integration/lib/protos.js"); require.alias("segmentio-analytics.js-integration/lib/events.js", "analytics/deps/integration/lib/events.js"); require.alias("segmentio-analytics.js-integration/lib/statics.js", "analytics/deps/integration/lib/statics.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "analytics/deps/integration/index.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "integration/index.js"); require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integration/deps/defaults/index.js"); require.alias("component-clone/index.js", "segmentio-analytics.js-integration/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-emitter/index.js", "segmentio-analytics.js-integration/deps/emitter/index.js"); require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js"); require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integration/deps/bind/index.js"); require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js"); require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js"); require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js"); require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js"); require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integration/deps/callback/index.js"); require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js"); require.alias("segmentio-after/index.js", "segmentio-analytics.js-integration/deps/after/index.js"); require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integration/deps/next-tick/index.js"); require.alias("yields-slug/index.js", "segmentio-analytics.js-integration/deps/slug/index.js"); require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integration/deps/debug/index.js"); require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integration/deps/debug/debug.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integration/index.js"); require.alias("segmentio-analytics.js-integrations/index.js", "analytics/deps/integrations/index.js"); require.alias("segmentio-analytics.js-integrations/lib/adroll.js", "analytics/deps/integrations/lib/adroll.js"); require.alias("segmentio-analytics.js-integrations/lib/adwords.js", "analytics/deps/integrations/lib/adwords.js"); require.alias("segmentio-analytics.js-integrations/lib/amplitude.js", "analytics/deps/integrations/lib/amplitude.js"); require.alias("segmentio-analytics.js-integrations/lib/awesm.js", "analytics/deps/integrations/lib/awesm.js"); require.alias("segmentio-analytics.js-integrations/lib/awesomatic.js", "analytics/deps/integrations/lib/awesomatic.js"); require.alias("segmentio-analytics.js-integrations/lib/bing-ads.js", "analytics/deps/integrations/lib/bing-ads.js"); require.alias("segmentio-analytics.js-integrations/lib/bronto.js", "analytics/deps/integrations/lib/bronto.js"); require.alias("segmentio-analytics.js-integrations/lib/bugherd.js", "analytics/deps/integrations/lib/bugherd.js"); require.alias("segmentio-analytics.js-integrations/lib/bugsnag.js", "analytics/deps/integrations/lib/bugsnag.js"); require.alias("segmentio-analytics.js-integrations/lib/chartbeat.js", "analytics/deps/integrations/lib/chartbeat.js"); require.alias("segmentio-analytics.js-integrations/lib/churnbee.js", "analytics/deps/integrations/lib/churnbee.js"); require.alias("segmentio-analytics.js-integrations/lib/clicktale.js", "analytics/deps/integrations/lib/clicktale.js"); require.alias("segmentio-analytics.js-integrations/lib/clicky.js", "analytics/deps/integrations/lib/clicky.js"); require.alias("segmentio-analytics.js-integrations/lib/comscore.js", "analytics/deps/integrations/lib/comscore.js"); require.alias("segmentio-analytics.js-integrations/lib/crazy-egg.js", "analytics/deps/integrations/lib/crazy-egg.js"); require.alias("segmentio-analytics.js-integrations/lib/curebit.js", "analytics/deps/integrations/lib/curebit.js"); require.alias("segmentio-analytics.js-integrations/lib/customerio.js", "analytics/deps/integrations/lib/customerio.js"); require.alias("segmentio-analytics.js-integrations/lib/drip.js", "analytics/deps/integrations/lib/drip.js"); require.alias("segmentio-analytics.js-integrations/lib/errorception.js", "analytics/deps/integrations/lib/errorception.js"); require.alias("segmentio-analytics.js-integrations/lib/evergage.js", "analytics/deps/integrations/lib/evergage.js"); require.alias("segmentio-analytics.js-integrations/lib/facebook-ads.js", "analytics/deps/integrations/lib/facebook-ads.js"); require.alias("segmentio-analytics.js-integrations/lib/foxmetrics.js", "analytics/deps/integrations/lib/foxmetrics.js"); require.alias("segmentio-analytics.js-integrations/lib/gauges.js", "analytics/deps/integrations/lib/gauges.js"); require.alias("segmentio-analytics.js-integrations/lib/get-satisfaction.js", "analytics/deps/integrations/lib/get-satisfaction.js"); require.alias("segmentio-analytics.js-integrations/lib/google-analytics.js", "analytics/deps/integrations/lib/google-analytics.js"); require.alias("segmentio-analytics.js-integrations/lib/google-tag-manager.js", "analytics/deps/integrations/lib/google-tag-manager.js"); require.alias("segmentio-analytics.js-integrations/lib/gosquared.js", "analytics/deps/integrations/lib/gosquared.js"); require.alias("segmentio-analytics.js-integrations/lib/heap.js", "analytics/deps/integrations/lib/heap.js"); require.alias("segmentio-analytics.js-integrations/lib/hittail.js", "analytics/deps/integrations/lib/hittail.js"); require.alias("segmentio-analytics.js-integrations/lib/hubspot.js", "analytics/deps/integrations/lib/hubspot.js"); require.alias("segmentio-analytics.js-integrations/lib/improvely.js", "analytics/deps/integrations/lib/improvely.js"); require.alias("segmentio-analytics.js-integrations/lib/inspectlet.js", "analytics/deps/integrations/lib/inspectlet.js"); require.alias("segmentio-analytics.js-integrations/lib/intercom.js", "analytics/deps/integrations/lib/intercom.js"); require.alias("segmentio-analytics.js-integrations/lib/keen-io.js", "analytics/deps/integrations/lib/keen-io.js"); require.alias("segmentio-analytics.js-integrations/lib/kissmetrics.js", "analytics/deps/integrations/lib/kissmetrics.js"); require.alias("segmentio-analytics.js-integrations/lib/klaviyo.js", "analytics/deps/integrations/lib/klaviyo.js"); require.alias("segmentio-analytics.js-integrations/lib/leadlander.js", "analytics/deps/integrations/lib/leadlander.js"); require.alias("segmentio-analytics.js-integrations/lib/livechat.js", "analytics/deps/integrations/lib/livechat.js"); require.alias("segmentio-analytics.js-integrations/lib/lucky-orange.js", "analytics/deps/integrations/lib/lucky-orange.js"); require.alias("segmentio-analytics.js-integrations/lib/lytics.js", "analytics/deps/integrations/lib/lytics.js"); require.alias("segmentio-analytics.js-integrations/lib/mixpanel.js", "analytics/deps/integrations/lib/mixpanel.js"); require.alias("segmentio-analytics.js-integrations/lib/mojn.js", "analytics/deps/integrations/lib/mojn.js"); require.alias("segmentio-analytics.js-integrations/lib/mouseflow.js", "analytics/deps/integrations/lib/mouseflow.js"); require.alias("segmentio-analytics.js-integrations/lib/mousestats.js", "analytics/deps/integrations/lib/mousestats.js"); require.alias("segmentio-analytics.js-integrations/lib/olark.js", "analytics/deps/integrations/lib/olark.js"); require.alias("segmentio-analytics.js-integrations/lib/optimizely.js", "analytics/deps/integrations/lib/optimizely.js"); require.alias("segmentio-analytics.js-integrations/lib/perfect-audience.js", "analytics/deps/integrations/lib/perfect-audience.js"); require.alias("segmentio-analytics.js-integrations/lib/pingdom.js", "analytics/deps/integrations/lib/pingdom.js"); require.alias("segmentio-analytics.js-integrations/lib/preact.js", "analytics/deps/integrations/lib/preact.js"); require.alias("segmentio-analytics.js-integrations/lib/qualaroo.js", "analytics/deps/integrations/lib/qualaroo.js"); require.alias("segmentio-analytics.js-integrations/lib/quantcast.js", "analytics/deps/integrations/lib/quantcast.js"); require.alias("segmentio-analytics.js-integrations/lib/rollbar.js", "analytics/deps/integrations/lib/rollbar.js"); require.alias("segmentio-analytics.js-integrations/lib/saasquatch.js", "analytics/deps/integrations/lib/saasquatch.js"); require.alias("segmentio-analytics.js-integrations/lib/sentry.js", "analytics/deps/integrations/lib/sentry.js"); require.alias("segmentio-analytics.js-integrations/lib/snapengage.js", "analytics/deps/integrations/lib/snapengage.js"); require.alias("segmentio-analytics.js-integrations/lib/spinnakr.js", "analytics/deps/integrations/lib/spinnakr.js"); require.alias("segmentio-analytics.js-integrations/lib/tapstream.js", "analytics/deps/integrations/lib/tapstream.js"); require.alias("segmentio-analytics.js-integrations/lib/trakio.js", "analytics/deps/integrations/lib/trakio.js"); require.alias("segmentio-analytics.js-integrations/lib/twitter-ads.js", "analytics/deps/integrations/lib/twitter-ads.js"); require.alias("segmentio-analytics.js-integrations/lib/usercycle.js", "analytics/deps/integrations/lib/usercycle.js"); require.alias("segmentio-analytics.js-integrations/lib/userfox.js", "analytics/deps/integrations/lib/userfox.js"); require.alias("segmentio-analytics.js-integrations/lib/uservoice.js", "analytics/deps/integrations/lib/uservoice.js"); require.alias("segmentio-analytics.js-integrations/lib/vero.js", "analytics/deps/integrations/lib/vero.js"); require.alias("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", "analytics/deps/integrations/lib/visual-website-optimizer.js"); require.alias("segmentio-analytics.js-integrations/lib/webengage.js", "analytics/deps/integrations/lib/webengage.js"); require.alias("segmentio-analytics.js-integrations/lib/woopra.js", "analytics/deps/integrations/lib/woopra.js"); require.alias("segmentio-analytics.js-integrations/lib/yandex-metrica.js", "analytics/deps/integrations/lib/yandex-metrica.js"); require.alias("segmentio-analytics.js-integrations/index.js", "integrations/index.js"); require.alias("component-clone/index.js", "segmentio-analytics.js-integrations/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-domify/index.js", "segmentio-analytics.js-integrations/deps/domify/index.js"); require.alias("component-each/index.js", "segmentio-analytics.js-integrations/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("component-once/index.js", "segmentio-analytics.js-integrations/deps/once/index.js"); require.alias("component-type/index.js", "segmentio-analytics.js-integrations/deps/type/index.js"); require.alias("component-url/index.js", "segmentio-analytics.js-integrations/deps/url/index.js"); require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integrations/deps/callback/index.js"); require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js"); require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integrations/deps/bind/index.js"); require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js"); require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js"); require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js"); require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-analytics.js-integrations/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-alias/index.js", "segmentio-analytics.js-integrations/deps/alias/index.js"); require.alias("component-clone/index.js", "segmentio-alias/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-type/index.js", "segmentio-alias/deps/type/index.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/lib/index.js"); require.alias("segmentio-analytics.js-integration/lib/protos.js", "segmentio-analytics.js-integrations/deps/integration/lib/protos.js"); require.alias("segmentio-analytics.js-integration/lib/events.js", "segmentio-analytics.js-integrations/deps/integration/lib/events.js"); require.alias("segmentio-analytics.js-integration/lib/statics.js", "segmentio-analytics.js-integrations/deps/integration/lib/statics.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/index.js"); require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integration/deps/defaults/index.js"); require.alias("component-clone/index.js", "segmentio-analytics.js-integration/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-emitter/index.js", "segmentio-analytics.js-integration/deps/emitter/index.js"); require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js"); require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integration/deps/bind/index.js"); require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js"); require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js"); require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js"); require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js"); require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integration/deps/callback/index.js"); require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js"); require.alias("segmentio-after/index.js", "segmentio-analytics.js-integration/deps/after/index.js"); require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integration/deps/next-tick/index.js"); require.alias("yields-slug/index.js", "segmentio-analytics.js-integration/deps/slug/index.js"); require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integration/deps/debug/index.js"); require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integration/deps/debug/debug.js"); require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integration/index.js"); require.alias("segmentio-canonical/index.js", "segmentio-analytics.js-integrations/deps/canonical/index.js"); require.alias("segmentio-convert-dates/index.js", "segmentio-analytics.js-integrations/deps/convert-dates/index.js"); require.alias("component-clone/index.js", "segmentio-convert-dates/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-convert-dates/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-extend/index.js", "segmentio-analytics.js-integrations/deps/extend/index.js"); require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/lib/index.js"); require.alias("segmentio-facade/lib/alias.js", "segmentio-analytics.js-integrations/deps/facade/lib/alias.js"); require.alias("segmentio-facade/lib/facade.js", "segmentio-analytics.js-integrations/deps/facade/lib/facade.js"); require.alias("segmentio-facade/lib/group.js", "segmentio-analytics.js-integrations/deps/facade/lib/group.js"); require.alias("segmentio-facade/lib/page.js", "segmentio-analytics.js-integrations/deps/facade/lib/page.js"); require.alias("segmentio-facade/lib/identify.js", "segmentio-analytics.js-integrations/deps/facade/lib/identify.js"); require.alias("segmentio-facade/lib/is-enabled.js", "segmentio-analytics.js-integrations/deps/facade/lib/is-enabled.js"); require.alias("segmentio-facade/lib/track.js", "segmentio-analytics.js-integrations/deps/facade/lib/track.js"); require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/index.js"); require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js"); require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js"); require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js"); require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js"); require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js"); require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js"); require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js"); require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js"); require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js"); require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js"); require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js"); require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js"); require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js"); require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js"); require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js"); require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js"); require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js"); require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js"); require.alias("segmentio-global-queue/index.js", "segmentio-analytics.js-integrations/deps/global-queue/index.js"); require.alias("segmentio-is-email/index.js", "segmentio-analytics.js-integrations/deps/is-email/index.js"); require.alias("segmentio-load-date/index.js", "segmentio-analytics.js-integrations/deps/load-date/index.js"); require.alias("segmentio-load-script/index.js", "segmentio-analytics.js-integrations/deps/load-script/index.js"); require.alias("component-type/index.js", "segmentio-load-script/deps/type/index.js"); require.alias("segmentio-on-body/index.js", "segmentio-analytics.js-integrations/deps/on-body/index.js"); require.alias("component-each/index.js", "segmentio-on-body/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("segmentio-on-error/index.js", "segmentio-analytics.js-integrations/deps/on-error/index.js"); require.alias("segmentio-to-iso-string/index.js", "segmentio-analytics.js-integrations/deps/to-iso-string/index.js"); require.alias("segmentio-to-unix-timestamp/index.js", "segmentio-analytics.js-integrations/deps/to-unix-timestamp/index.js"); require.alias("segmentio-use-https/index.js", "segmentio-analytics.js-integrations/deps/use-https/index.js"); require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integrations/deps/next-tick/index.js"); require.alias("yields-slug/index.js", "segmentio-analytics.js-integrations/deps/slug/index.js"); require.alias("visionmedia-batch/index.js", "segmentio-analytics.js-integrations/deps/batch/index.js"); require.alias("component-emitter/index.js", "visionmedia-batch/deps/emitter/index.js"); require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js"); require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integrations/deps/debug/index.js"); require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integrations/deps/debug/debug.js"); require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js"); require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js"); require.alias("component-querystring/index.js", "segmentio-load-pixel/deps/querystring/index.js"); require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js"); require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js"); require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js"); require.alias("segmentio-substitute/index.js", "segmentio-substitute/index.js"); require.alias("segmentio-load-pixel/index.js", "segmentio-load-pixel/index.js"); require.alias("segmentio-canonical/index.js", "analytics/deps/canonical/index.js"); require.alias("segmentio-canonical/index.js", "canonical/index.js"); require.alias("segmentio-extend/index.js", "analytics/deps/extend/index.js"); require.alias("segmentio-extend/index.js", "extend/index.js"); require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/lib/index.js"); require.alias("segmentio-facade/lib/alias.js", "analytics/deps/facade/lib/alias.js"); require.alias("segmentio-facade/lib/facade.js", "analytics/deps/facade/lib/facade.js"); require.alias("segmentio-facade/lib/group.js", "analytics/deps/facade/lib/group.js"); require.alias("segmentio-facade/lib/page.js", "analytics/deps/facade/lib/page.js"); require.alias("segmentio-facade/lib/identify.js", "analytics/deps/facade/lib/identify.js"); require.alias("segmentio-facade/lib/is-enabled.js", "analytics/deps/facade/lib/is-enabled.js"); require.alias("segmentio-facade/lib/track.js", "analytics/deps/facade/lib/track.js"); require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/index.js"); require.alias("segmentio-facade/lib/index.js", "facade/index.js"); require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js"); require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js"); require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js"); require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js"); require.alias("component-type/index.js", "component-clone/deps/type/index.js"); require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js"); require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js"); require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js"); require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js"); require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js"); require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js"); require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js"); require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js"); require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js"); require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js"); require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js"); require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js"); require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js"); require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js"); require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js"); require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js"); require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js"); require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js"); require.alias("segmentio-is-email/index.js", "analytics/deps/is-email/index.js"); require.alias("segmentio-is-email/index.js", "is-email/index.js"); require.alias("segmentio-is-meta/index.js", "analytics/deps/is-meta/index.js"); require.alias("segmentio-is-meta/index.js", "is-meta/index.js"); require.alias("segmentio-isodate-traverse/index.js", "analytics/deps/isodate-traverse/index.js"); require.alias("segmentio-isodate-traverse/index.js", "isodate-traverse/index.js"); require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js"); require.alias("component-type/index.js", "component-each/deps/type/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js"); require.alias("segmentio-json/index.js", "analytics/deps/json/index.js"); require.alias("segmentio-json/index.js", "json/index.js"); require.alias("component-json-fallback/index.js", "segmentio-json/deps/json-fallback/index.js"); require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/lib/index.js"); require.alias("segmentio-new-date/lib/milliseconds.js", "analytics/deps/new-date/lib/milliseconds.js"); require.alias("segmentio-new-date/lib/seconds.js", "analytics/deps/new-date/lib/seconds.js"); require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/index.js"); require.alias("segmentio-new-date/lib/index.js", "new-date/index.js"); require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js"); require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js"); require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js"); require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js"); require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js"); require.alias("segmentio-store.js/store.js", "analytics/deps/store/store.js"); require.alias("segmentio-store.js/store.js", "analytics/deps/store/index.js"); require.alias("segmentio-store.js/store.js", "store/index.js"); require.alias("segmentio-store.js/store.js", "segmentio-store.js/index.js"); require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js"); require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js"); require.alias("segmentio-top-domain/index.js", "top-domain/index.js"); require.alias("component-url/index.js", "segmentio-top-domain/deps/url/index.js"); require.alias("segmentio-top-domain/index.js", "segmentio-top-domain/index.js"); require.alias("visionmedia-debug/index.js", "analytics/deps/debug/index.js"); require.alias("visionmedia-debug/debug.js", "analytics/deps/debug/debug.js"); require.alias("visionmedia-debug/index.js", "debug/index.js"); require.alias("yields-prevent/index.js", "analytics/deps/prevent/index.js"); require.alias("yields-prevent/index.js", "prevent/index.js"); require.alias("analytics/lib/index.js", "analytics/index.js");if (typeof exports == "object") { module.exports = require("analytics"); } else if (typeof define == "function" && define.amd) { define([], function(){ return require("analytics"); }); } else { this["analytics"] = require("analytics"); }})();
__tests__/components/LoginForm-test.js
linde12/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React from 'react'; import renderer from 'react-test-renderer'; import LoginForm from '../../src/js/components/LoginForm'; // needed because this: // https://github.com/facebook/jest/issues/1353 jest.mock('react-dom'); describe('LoginForm', () => { it('has correct default options', () => { const component = renderer.create( <LoginForm onSubmit={() => {}} /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders login button as disabled when onSubmit is undefined', () => { const component = renderer.create( <LoginForm /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('onChange behaves properly', () => { const onChangeFn = jest.fn(); const component = renderer.create( <LoginForm onSubmit={() => {}} onChange={onChangeFn} /> ); component.getInstance()._onUsernameChange( { target: { value: '[email protected]' }}); component.getInstance()._onPasswordChange( { target: { value: 'm0desty' }}); component.getInstance()._onRememberMeChange( { target: { value: true }}); expect(onChangeFn.mock.calls.length).toBe(3); expect(onChangeFn.mock.calls[0][0].username).toBe('[email protected]'); }); it('renders errors properly with both string and JSX errors', () => { const errors = [ 'Some detailed error.', (<span> You need to use <a href="#">some external resource</a> to resolve this. </span>) ]; const component = renderer.create( <LoginForm onSubmit={() => {}} errors={errors} /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
ajax/libs/6to5/2.3.0/browser.js
froala/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.11.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,curPosition()]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowHashBang: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>=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,inType;var metParenL;var templates;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 _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};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 _arrow={type:"=>",beforeExpr:true},_template={type:"template"},_templateContinued={type:"templateContinued"};var _ellipsis={type:"...",prefix:true,beforeExpr:true};var _paamayimNekudotayim={type:"::",beforeExpr:true};var _at={type:"@"};var _hash={type:"#"};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,paamayimNekudotayim:_paamayimNekudotayim,exponent:_exponent,at:_at,hash:_hash,template:_template,templateContinued:_templateContinued};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 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 decimalNumber=/^\d+$/;var hexNumber=/^[\da-fA-F]+$/;var newline=/[\n\r\u2028\u2029]/;function isNewLine(code){return code===10||code===13||code===8232||code==8233}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(line,col){this.line=line;this.column=col}Position.prototype.offset=function(n){return new Position(this.line,this.column+n)};function curPosition(){return new Position(tokCurLine,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;inType=inXJSChild=inXJSTag=false;templates=[];if(tokPos===0&&options.allowHashBang&&input.slice(0,2)==="#!"){skipLineComment(2)}}function finishToken(type,val,shouldSkipSpace){tokEnd=tokPos;if(options.locations)tokEndLoc=curPosition();tokType=type;if(shouldSkipSpace!==false)skipSpace();tokVal=val;tokRegexpAllowed=type.beforeExpr;if(options.onToken){options.onToken(new Token)}}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&curPosition();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&&curPosition())}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&curPosition();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&&curPosition())}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.playground&&next===63){tokPos+=2;return finishToken(_dotQuestion)}else 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(!inType&&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)}}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;if(templates.length)++templates[templates.length-1];return finishToken(_braceL);case 125:++tokPos;if(templates.length&&--templates[templates.length-1]===0)return readTemplateString(_templateContinued);else return finishToken(_braceR);case 63:++tokPos;return finishToken(_question);case 64:if(options.playground){++tokPos;return finishToken(_at)}case 35:if(options.playground){++tokPos;return finishToken(_hash)}case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_paamayimNekudotayim)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return readTemplateString(_template)}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=curPosition();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(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 readTemplateString(type){if(type==_templateContinued)templates.pop();var out="",start=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated template");var ch=input.charAt(tokPos);if(ch==="`"||ch==="$"&&input.charCodeAt(tokPos+1)===123){var raw=input.slice(start,tokPos);++tokPos;if(ch=="$"){++tokPos;templates.push(1)}return finishToken(type,{cooked:out,raw:raw})}if(ch==="\\"){out+=readEscapedChar()}else{++tokPos;if(newline.test(ch)){if(ch==="\r"&&input.charCodeAt(tokPos)===10){++tokPos;ch="\n"}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=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");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}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 finishNodeAt(node,type,pos){if(options.locations){node.loc.end=pos[1];pos=pos[0]}node.type=type;node.end=pos;if(options.ranges)node.range[1]=pos;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 ":"Assigning to ")+expr.name+" in strict mode");break;case"MemberExpression":if(isBinding)raise(expr.start,"Binding to member expression");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(true);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(topLevel){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 _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:case _import:if(!topLevel&&!options.allowImportExportEverywhere)raise(tokStart,"'import' and 'export' may only appear at the top level");return starttype===_import?parseImport(node):parseExport(node);default:var maybeName=tokVal,expr=parseExpression();if(starttype===_name){if(expr.type==="FunctionExpression"&&expr.async){expr.type="FunctionDeclaration";return expr}else if(expr.type==="Identifier"){if(eat(_colon)){return parseLabeledStatement(node,maybeName,expr)}if(options.ecmaVersion>=7&&expr.name==="private"&&tokType===_name){return parsePrivate(node)}else if(expr.name==="declare"){if(tokType===_class||tokType===_name||tokType===_function||tokType===_var){return parseDeclare(node)}}else if(tokType===_name){if(expr.name==="interface"){return parseInterface(node)}else if(expr.name==="type"){return parseTypeAlias(node)}}}}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();if(options.ecmaVersion>=6)eat(_semi);else 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 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);if(tokType===_colon){decl.id.typeAnnotation=parseTypeAnnotation();finishNode(decl.id,decl.id.type)}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,noLess){var start=storeCurrentPos();var left=parseMaybeConditional(noIn,noLess);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,noLess){var start=storeCurrentPos();var expr=parseExprOps(noIn,noLess);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,noLess){var start=storeCurrentPos();return parseExprOp(parseMaybeUnary(),start,-1,noIn,noLess)}function parseExprOp(left,leftStart,minPrec,noIn,noLess){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)&&(!noLess||tokType!==_lt)){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(_hash)){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(_paamayimNekudotayim)){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===_template){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 _at:var start=storeCurrentPos();var node=startNode();next();node.object={type:"ThisExpression"};node.property=parseSubscripts(parseIdent(),start);node.computed=false;return finishNode(node,"MemberExpression");case _yield:if(inGenerator)return parseYield();case _name:var start=storeCurrentPos();var node=startNode();var id=parseIdent(tokType!==_name);if(options.ecmaVersion>=7){if(id.name==="async"){if(tokType===_parenL){next();var oldParenL=++metParenL;if(tokType!==_parenR){val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){return parseArrowExpression(node,exprList,true)}else{node.callee=id;node.arguments=exprList;return parseSubscripts(finishNode(node,"CallExpression"),start)}}else if(tokType===_name){id=parseIdent();if(eat(_arrow)){return parseArrowExpression(node,[id],true)}return id}if(tokType===_function){next();return parseFunction(node,false,true)}}else if(id.name==="await"){if(inAsync)return parseAwait(node)}}if(eat(_arrow)){return parseArrowExpression(node,[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 _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _template:return parseTemplate();case _lt:return parseXJSElement();case _hash:return parseBindFunctionExpression();default:unexpected()}}function parseBindFunctionExpression(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return finishNode(node,"BindFunctionExpression")}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 parseTemplateElement(){var elem=startNodeAt(options.locations?[tokStart+1,tokStartLoc.offset(1)]:tokStart+1);elem.value=tokVal;elem.tail=input.charCodeAt(tokEnd-1)!==123;next();var endOff=elem.tail?1:2;return finishNodeAt(elem,"TemplateElement",options.locations?[lastEnd-endOff,lastEndLoc.offset(-endOff)]:lastEnd-endOff)}function parseTemplate(){var node=startNode();node.expressions=[];var curElt=parseTemplateElement();node.quasis=[curElt];while(!curElt.tail){node.expressions.push(parseExpression());if(tokType!==_templateContinued)unexpected();node.quasis.push(curElt=parseTemplateElement())}return finishNode(node,"TemplateLiteral")}function parseObj(){var node=startNode(),first=true,propHash={};node.properties=[];next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),isGenerator=false,isAsync=false;if(options.ecmaVersion>=7&&tokType===_ellipsis){prop=parseMaybeUnary();prop.type="SpreadProperty";node.properties.push(prop);continue}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;isGenerator=eat(_star)}if(options.ecmaVersion>=7&&tokType===_name&&tokVal==="async"){var asyncId=parseIdent();if(tokType===_colon||tokType===_parenL){prop.key=asyncId}else{isAsync=true;parsePropertyName(prop)}}else{parsePropertyName(prop)}var typeParameters;if(tokType===_lt){typeParameters=parseTypeParameterDeclaration();if(tokType!==_parenL)unexpected()}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"||options.playground&&prop.key.name==="memo")&&(tokType!=_comma&&tokType!=_braceR)){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();prop.value.typeParameters=typeParameters;checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}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){node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}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);parseFunctionParam(node.rest);expect(_parenR);defaults.push(null);break}else{var param=options.ecmaVersion>=6?toAssignable(parseExprAtom(),false,true):parseIdent();parseFunctionParam(param);node.params.push(param);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;if(tokType===_colon){node.returnType=parseTypeAnnotation()}}function parseFunctionParam(param){if(tokType===_colon){param.typeAnnotation=parseTypeAnnotation()}else if(eat(_question)){param.optional=true}finishNode(param,param.type)}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 parsePrivate(node){node.declarations=[];do{node.declarations.push(parseIdent())}while(eat(_comma));semicolon();return finishNode(node,"PrivateDeclaration")}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}node.superClass=eat(_extends)?parseMaybeAssign(false,true):null;if(node.superClass)checkLVal(node.superClass);if(node.superClass&&tokType===_lt){node.superTypeParameters=parseTypeParameterInstantiation()}if(tokType===_name&&tokVal==="implements"){next();node.implements=parseClassImplements()}var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){var method=startNode();if(options.ecmaVersion>=7&&tokType===_name&&tokVal==="private"){next();classBody.body.push(parsePrivate(method));continue}if(tokType===_name&&tokVal==="static"){next();method["static"]=true}else{method["static"]=false}var isAsync=false;var isGenerator=eat(_star);if(options.ecmaVersion>=7&&!isGenerator&&tokType===_name&&tokVal==="async"){var asyncId=parseIdent();if(tokType===_colon||tokType===_parenL){method.key=asyncId}else{isAsync=true;parsePropertyName(method)}}else{parsePropertyName(method)}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set"||options.playground&&method.key.name==="memo")){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}if(tokType===_colon){if(isGenerator||isAsync)unexpected();method.typeAnnotation=parseTypeAnnotation();semicolon();classBody.body.push(finishNode(method,"ClassProperty"))}else{var typeParameters;if(tokType===_lt){typeParameters=parseTypeParameterDeclaration()}method.value=parseMethod(isGenerator,isAsync);method.value.typeParameters=typeParameters;classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseClassImplements(){var implemented=[];do{var node=startNode();node.id=parseIdent();if(tokType===_lt){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}implemented.push(finishNode(node,"ClassImplements"))}while(eat(_comma));return implemented}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===_name&&tokVal==="async"){node.declaration=parseStatement();node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){var declar=node.declaration=parseExpression(true);if(declar.id){if(declar.type==="FunctionExpression"){declar.type="FunctionDeclaration"}else if(declar.type==="ClassExpression"){declar.type="ClassDeclaration"}}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()}else{node.specifiers=parseImportSpecifiers();if(tokType!==_name||tokVal!=="from")unexpected();next();node.source=tokType===_string?parseExprAtom():unexpected()}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_name){var node=startNode();node.id=startNode();node.name=parseIdent();checkLVal(node.name,true);node.id.name="default";finishNode(node.id,"Identifier");nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}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}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(node){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;next();node.expression=tokType===_braceR?parseXJSEmptyExpression():parseExpression();inXJSTag=origInXJSTag;inXJSChild=origInXJSChild;if(inXJSChild){tokPos=tokEnd}expect(_braceR);return finishNode(node,"XJSExpressionContainer")}function parseXJSAttribute(){if(tokType===_braceL){var tokStart1=tokStart,tokStartLoc1=tokStartLoc;var origInXJSTag=inXJSTag;inXJSTag=false;next();if(tokType!==_ellipsis)unexpected();var node=parseMaybeUnary();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")}function parseDeclareClass(node){next();parseInterfaceish(node,true);return finishNode(node,"DeclareClass")}function parseDeclareFunction(node){next();var id=node.id=parseIdent();var typeNode=startNode();var typeContainer=startNode();if(tokType===_lt){typeNode.typeParameters=parseTypeParameterDeclaration()}else{typeNode.typeParameters=null}expect(_parenL);var tmp=parseFunctionTypeParams();typeNode.params=tmp.params;typeNode.rest=tmp.rest;expect(_parenR);expect(_colon);typeNode.returnType=parseType();typeContainer.typeAnnotation=finishNode(typeNode,"FunctionTypeAnnotation");id.typeAnnotation=finishNode(typeContainer,"TypeAnnotation");finishNode(id,id.type);semicolon();return finishNode(node,"DeclareFunction")}function parseDeclare(node){if(tokType===_class){return parseDeclareClass(node)}else if(tokType===_function){return parseDeclareFunction(node)}else if(tokType===_var){return parseDeclareVariable(node)}else if(tokType===_name&&tokVal==="module"){return parseDeclareModule(node)}else{unexpected()}}function parseDeclareVariable(node){next();node.id=parseTypeAnnotatableIdentifier();semicolon();return finishNode(node,"DeclareVariable")}function parseDeclareModule(node){next();if(tokType===_string){node.id=parseExprAtom()}else{node.id=parseIdent()}var bodyNode=node.body=startNode();var body=bodyNode.body=[];expect(_braceL);while(tokType!==_braceR){var node2=startNode();next();body.push(parseDeclare(node2))}expect(_braceR);finishNode(bodyNode,"BlockStatement");return finishNode(node,"DeclareModule")}function parseInterfaceish(node,allowStatic){node.id=parseIdent();if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}node.extends=[];if(eat(_extends)){do{node.extends.push(parseInterfaceExtends())}while(eat(_comma))}node.body=parseObjectType(allowStatic)}function parseInterfaceExtends(){var node=startNode();node.id=parseIdent();if(tokType===_lt){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}return finishNode(node,"InterfaceExtends")}function parseInterface(node){parseInterfaceish(node,false);return finishNode(node,"InterfaceDeclaration")}function parseTypeAlias(node){node.id=parseIdent();if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}expect(_eq);node.right=parseType();semicolon();return finishNode(node,"TypeAlias")}function parseTypeParameterDeclaration(){var node=startNode();node.params=[];expect(_lt);while(tokType!==_gt){node.params.push(parseIdent());if(tokType!==_gt){expect(_comma)}}expect(_gt);return finishNode(node,"TypeParameterDeclaration")}function parseTypeParameterInstantiation(){var node=startNode(),oldInType=inType;node.params=[];inType=true;expect(_lt);while(tokType!==_gt){node.params.push(parseType());if(tokType!==_gt){expect(_comma)}}expect(_gt);inType=oldInType;return finishNode(node,"TypeParameterInstantiation")}function parseObjectPropertyKey(){return tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function parseObjectTypeIndexer(node,isStatic){node.static=isStatic;expect(_bracketL);node.id=parseObjectPropertyKey();expect(_colon);node.key=parseType();expect(_bracketR);expect(_colon);node.value=parseType();return finishNode(node,"ObjectTypeIndexer")}function parseObjectTypeMethodish(node){node.params=[];node.rest=null;node.typeParameters=null;if(tokType===_lt){node.typeParameters=parseTypeParameterDeclaration()}expect(_parenL);while(tokType===_name){node.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){node.rest=parseFunctionTypeParam()}expect(_parenR);expect(_colon);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}function parseObjectTypeMethod(start,isStatic,key){var node=startNodeAt(start);node.value=parseObjectTypeMethodish(startNodeAt(start));node.static=isStatic;node.key=key;node.optional=false;return finishNode(node,"ObjectTypeProperty")}function parseObjectTypeCallProperty(node,isStatic){var valueNode=startNode();node.static=isStatic;node.value=parseObjectTypeMethodish(valueNode);return finishNode(node,"ObjectTypeCallProperty")}function parseObjectType(allowStatic){var nodeStart=startNode();var node;var optional=false;var property;var propertyKey;var propertyTypeAnnotation;var token;var isStatic;nodeStart.callProperties=[];nodeStart.properties=[];nodeStart.indexers=[];expect(_braceL);while(tokType!==_braceR){var start=storeCurrentPos();node=startNode();if(allowStatic&&tokType===_name&&tokVal==="static"){next();isStatic=true}if(tokType===_bracketL){nodeStart.indexers.push(parseObjectTypeIndexer(node,isStatic))}else if(tokType===_parenL||tokType===_lt){nodeStart.callProperties.push(parseObjectTypeCallProperty(node,allowStatic))}else{if(isStatic&&tokType===_colon){propertyKey=parseIdent()}else{propertyKey=parseObjectPropertyKey()}if(tokType===_lt||tokType===_parenL){nodeStart.properties.push(parseObjectTypeMethod(start,isStatic,propertyKey))}else{if(eat(_question)){optional=true}expect(_colon);node.key=propertyKey;node.value=parseType();node.optional=optional;node.static=isStatic;nodeStart.properties.push(finishNode(node,"ObjectTypeProperty"))}}if(!eat(_semi)&&tokType!==_braceR){unexpected()}}expect(_braceR);return finishNode(nodeStart,"ObjectTypeAnnotation")}function parseGenericType(start,id){var node=startNodeAt(start);node.typeParameters=null;node.id=id;while(eat(_dot)){var node2=startNodeAt(start);node2.qualification=node.id;node2.id=parseIdent();node.id=finishNode(node2,"QualifiedTypeIdentifier")}if(tokType===_lt){node.typeParameters=parseTypeParameterInstantiation()}return finishNode(node,"GenericTypeAnnotation")}function parseVoidType(){var node=startNode();expect(keywordTypes["void"]);return finishNode(node,"VoidTypeAnnotation")}function parseTypeofType(){var node=startNode();expect(keywordTypes["typeof"]);node.argument=parsePrimaryType();return finishNode(node,"TypeofTypeAnnotation")}function parseTupleType(){var node=startNode();node.types=[];expect(_bracketL);while(tokPos<inputLen&&tokType!==_bracketR){node.types.push(parseType());if(tokType===_bracketR)break;expect(_comma)}expect(_bracketR);return finishNode(node,"TupleTypeAnnotation")}function parseFunctionTypeParam(){var optional=false;var node=startNode();node.name=parseIdent();if(eat(_question)){optional=true}expect(_colon);node.optional=optional;node.typeAnnotation=parseType();return finishNode(node,"FunctionTypeParam")}function parseFunctionTypeParams(){var ret={params:[],rest:null};while(tokType===_name){ret.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){ret.rest=parseFunctionTypeParam()}return ret}function identToTypeAnnotation(start,node,id){switch(id.name){case"any":return finishNode(node,"AnyTypeAnnotation");case"bool":case"boolean":return finishNode(node,"BooleanTypeAnnotation");case"number":return finishNode(node,"NumberTypeAnnotation");case"string":return finishNode(node,"StringTypeAnnotation");default:return parseGenericType(start,id)}}function parsePrimaryType(){var typeIdentifier=null;var params=null;var returnType=null;var start=storeCurrentPos();var node=startNode();var rest=null;var tmp;var typeParameters;var token;var type;var isGroupedType=false;switch(tokType){case _name:return identToTypeAnnotation(start,node,parseIdent());case _braceL:return parseObjectType();case _bracketL:return parseTupleType();case _lt:node.typeParameters=parseTypeParameterDeclaration();expect(_parenL);tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation");case _parenL:next();var tmpId;if(tokType!==_parenR&&tokType!==_ellipsis){if(tokType===_name){}else{isGroupedType=true}}if(isGroupedType){if(tmpId&&_parenR){type=tmpId}else{type=parseType();expect(_parenR)}if(eat(_arrow)){raise(node,"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType")}return type}tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();node.typeParameters=null;return finishNode(node,"FunctionTypeAnnotation");case _string:node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"StringLiteralTypeAnnotation");default:if(tokType.keyword){switch(tokType.keyword){case"void":return parseVoidType();case"typeof":return parseTypeofType()}}}unexpected()}function parsePostfixType(){var node=startNode();var type=node.elementType=parsePrimaryType();if(tokType===_bracketL){expect(_bracketL);expect(_bracketR);return finishNode(node,"ArrayTypeAnnotation")}return type}function parsePrefixType(){var node=startNode();if(eat(_question)){node.typeAnnotation=parsePrefixType();return finishNode(node,"NullableTypeAnnotation")}return parsePostfixType()}function parseIntersectionType(){var node=startNode();var type=parsePrefixType();node.types=[type];while(eat(_bitwiseAND)){node.types.push(parsePrefixType())}return node.types.length===1?type:finishNode(node,"IntersectionTypeAnnotation")}function parseUnionType(){var node=startNode();var type=parseIntersectionType();node.types=[type];while(eat(_bitwiseOR)){node.types.push(parseIntersectionType())}return node.types.length===1?type:finishNode(node,"UnionTypeAnnotation")}function parseType(){var oldInType=inType;inType=true;var type=parseUnionType();inType=oldInType;return type}function parseTypeAnnotation(){var node=startNode();expect(_colon);node.typeAnnotation=parseType();return finishNode(node,"TypeAnnotation")}function parseTypeAnnotatableIdentifier(requireTypeAnnotation,canBeOptionalParam){var node=startNode();var ident=parseIdent();var isOptionalParam=false;if(canBeOptionalParam&&eat(_question)){expect(_question);isOptionalParam=true}if(requireTypeAnnotation||tokType===_colon){ident.typeAnnotation=parseTypeAnnotation();finishNode(ident,ident.type)}if(isOptionalParam){ident.optional=true;finishNode(ident,ident.type)}return ident}})},{}],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":31}],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.transformers=this.getTransformers();this.uids={};this.ast={}}File.declarations=["inherits","prototype-properties","apply-constructor","tagged-template-literal","interop-require","to-array","sliced-to-array","object-without-properties","has-own","slice"];File.normaliseOptions=function(opts){opts=_.cloneDeep(opts||{});_.defaults(opts,{experimental:false,playground:false,whitespace:true,moduleIds:opts.amdModuleIds||false,blacklist:[],whitelist:[],sourceMap:false,optional:[],comments:true,filename:"unknown",modules:"common",runtime:false,code:true,ast: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);transform._ensureTransformerNames("optional",opts.optional);return opts};File.prototype.getTransformers=function(){var file=this;var transformers=[];_.each(transform.transformers,function(transformer){if(transformer.canRun(file)){transformers.push(transformer)}});return transformers};File.prototype.toArray=function(node,i){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{var declarationName="to-array";var args=[node];if(i){args.push(t.literal(i));declarationName="sliced-to-array"}return t.callExpression(this.addDeclaration(declarationName),args)}};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 "+JSON.stringify(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.addCode=function(code){code=(code||"")+"";this.code=code;return this.parseShebang(code)};File.prototype.parse=function(code){var self=this;code=this.addCode(code);return util.parse(this.opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){var self=this;this.ast=ast;this.scope=new Scope(ast.program);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var astRun=function(key){_.each(self.transformers,function(transformer){transformer.astRun(self,key)})};astRun("enter");_.each(this.transformers,function(transformer){transformer.transform(self)});astRun("exit")};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;var result={code:"",map:null,ast:null};if(opts.ast)result.ast=ast;if(!opts.code)return result;var _result=generate(ast,opts,this.code);result.code=_result.code;result.map=_result.map;if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}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":31,"./traverse/scope":70,"./types":73,"./util":75,lodash:123}],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(){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.format.compact)return;if(_.isBoolean(i)){removeLast=i;i=null}if(_.isNumber(i)){if(this.endsWith("{\n"))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":75,lodash:123}],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,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"),flow:require("./generators/flow"),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);var comments=[];_.each(ast.comments,function(comment){if(!comment._displayed)comments.push(comment)});this._printComments(comments);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);if(!self.buffer.get())lines=0}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=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 of type "+JSON.stringify(node.type)+" with constructor "+JSON.stringify(node&&node.constructor.name))}};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){_.each(self.ast.comments,function(origComment){if(origComment.start===comment.start){origComment._displayed=true;return false}});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":73,"../util":75,"./buffer":4,"./generators/base":6,"./generators/classes":7,"./generators/comprehensions":8,"./generators/expressions":9,"./generators/flow":10,"./generators/jsx":11,"./generators/methods":12,"./generators/modules":13,"./generators/playground":14,"./generators/statements":15,"./generators/template-literals":16,"./generators/types":17,"./node":18,"./position":21,"./source-map":22,"./whitespace":23,lodash:123}],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.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)};var SCIENTIFIC_NOTATION=/e/i; exports.MemberExpression=function(node,print){var obj=node.object;print(obj);if(node.computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(obj)&&util.isInteger(obj.value)&&!SCIENTIFIC_NOTATION.test(obj.value.toString())){this.push(".")}this.push(".");print(node.property)}}},{"../../types":73,"../../util":75}],10:[function(require,module,exports){exports.ClassProperty=function(){throw new Error("not implemented")}},{}],11:[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":73,lodash:123}],12:[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":73}],13:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=function(node,print){if(node.id&&node.id.name==="default"){print(node.name)}else{return exports.ExportSpecifier.apply(this,arguments)}};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(", ")}var isDefault=spec.id&&spec.id.name==="default";if(!isDefault&&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":73,lodash:123}],14:[function(require,module,exports){var _=require("lodash");_.each(["BindMemberExpression","BindFunctionExpression"],function(type){exports[type]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(type))}})},{lodash:123}],15:[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.newline();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.PrivateDeclaration=function(node,print){this.push("private ");print.join(node.declarations,{separator:", "});this.semicolon()};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.push(" = ");print(node.init)}else{print(node.id)}}},{"../../types":73}],16:[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:123}],17:[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(/[\u000A\u000D\u2028\u2029]/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:123}],18:[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":73,"./parentheses":19,"./whitespace":20,lodash:123}],19:[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.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":73,lodash:123}],20:[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:{AssignmentExpression:function(node){if(t.isFunction(node.right)){return 1}}},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":73,lodash:123}],21:[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:123}],22:[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":73,"source-map":165}],23:[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}});if(endToken.type.type==="eof"){return 1}else{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:123}],24:[function(require,module,exports){var t=require("./types");var _=require("lodash");var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS);var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;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("PrivateDeclaration").bases("Declaration").build("declarations").field("declarations",[def("Identifier")]);def("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("arguments",[def("Expression")]);def("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);types.finalize()},{"./types":73,"ast-types":89,estraverse:117,lodash:123}],25:[function(require,module,exports){module.exports=DefaultFormatter;var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");function DefaultFormatter(file){this.file=file;this.localExports=this.getLocalExports();this.remapAssignments()}DefaultFormatter.prototype.getLocalExports=function(){var localExports={};traverse(this.file.ast,{enter:function(node){var declar=node&&node.declaration;if(t.isExportDeclaration(node)&&declar&&t.isStatement(declar)){_.extend(localExports,t.getIds(declar,true))}}});return localExports};DefaultFormatter.prototype.remapExportAssignment=function(node){return t.assignmentExpression("=",node.left,t.assignmentExpression(node.operator,t.memberExpression(t.identifier("exports"),node.left),node.right))};DefaultFormatter.prototype.remapAssignments=function(){var localExports=this.localExports;var self=this;var isLocalReference=function(node,scope){var name=node.name;return t.isIdentifier(node)&&localExports[name]&&localExports[name]===scope.get(name,true)};traverse(this.file.ast,{enter:function(node,parent,scope){if(t.isUpdateExpression(node)&&isLocalReference(node.argument,scope)){this.stop();var assign=t.assignmentExpression(node.operator[0]+"=",node.argument,t.literal(1));var remapped=self.remapExportAssignment(assign);if(t.isExpressionStatement(parent)||node.prefix){return remapped}var nodes=[];nodes.push(remapped);var operator;if(node.operator==="--"){operator="+"}else{operator="-"}nodes.push(t.binaryExpression(operator,node.argument,t.literal(1)));return t.sequenceExpression(nodes)}if(t.isAssignmentExpression(node)&&isLocalReference(node.left,scope)){this.stop();return self.remapExportAssignment(node)}}})};DefaultFormatter.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};DefaultFormatter.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};DefaultFormatter.prototype._hoistExport=function(declar,assign,priority){if(t.isFunctionDeclaration(declar)){assign._blockHoist=priority||1}return assign};DefaultFormatter.prototype._exportSpecifier=function(getRef,specifier,node,nodes){var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){if(t.isExportBatchSpecifier(specifier)){nodes.push(this._exportsWildcard(getRef(),node))}else{nodes.push(this._exportsAssign(t.getSpecifierName(specifier),t.memberExpression(getRef(),specifier.id),node))}}else{nodes.push(this._exportsAssign(t.getSpecifierName(specifier),specifier.id,node))}};DefaultFormatter.prototype._exportsWildcard=function(objectIdentifier){return util.template("exports-wildcard",{OBJECT:objectIdentifier},true)};DefaultFormatter.prototype._exportsAssign=function(id,init){return util.template("exports-assign",{VALUE:init,KEY:id},true)};DefaultFormatter.prototype.exportDeclaration=function(node,nodes){var declar=node.declaration;var id=declar.id;if(node.default){id=t.identifier("default")}var assign;if(t.isVariableDeclaration(declar)){for(var i in declar.declarations){var decl=declar.declarations[i];decl.init=this._exportsAssign(decl.id,decl.init,node).expression;var newDeclar=t.variableDeclaration(declar.kind,[decl]);if(i==="0")t.inherits(newDeclar,declar);nodes.push(newDeclar)}}else{var ref=declar;if(t.isFunctionDeclaration(declar)||t.isClassDeclaration(declar)){ref=declar.id;nodes.push(declar)}assign=this._exportsAssign(id,ref,node);nodes.push(assign);this._hoistExport(declar,assign)}}},{"../../traverse":69,"../../types":73,"../../util":75,lodash:123}],26:[function(require,module,exports){module.exports=AMDFormatter;var DefaultFormatter=require("./_default");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(){DefaultFormatter.apply(this,arguments);this.ids={}}util.inherits(AMDFormatter,DefaultFormatter);AMDFormatter.prototype.buildDependencyLiterals=function(){var names=[];for(var name in this.ids){names.push(t.literal(name))}return names};AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")].concat(this.buildDependencyLiterals());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.moduleIds){return DefaultFormatter.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.importDeclaration=function(node){this._push(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var ref=this._push(node);if(t.isImportBatchSpecifier(specifier)){}else if(t.isSpecifierDefault(specifier)&&!this.noInteropRequire){ref=t.callExpression(this.file.addDeclaration("interop-require"),[ref])}else{ref=t.memberExpression(ref,specifier.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":73,"../../util":75,"./_default":25,lodash:123}],27:[function(require,module,exports){module.exports=CommonJSFormatter;var DefaultFormatter=require("./_default");var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");function CommonJSFormatter(file){DefaultFormatter.apply(this,arguments);var hasNonDefaultExports=false;traverse(file.ast,{enter:function(node){if(t.isExportDeclaration(node)&&!node.default)hasNonDefaultExports=true}});this.hasNonDefaultExports=hasNonDefaultExports}util.inherits(CommonJSFormatter,DefaultFormatter);CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(t.isSpecifierDefault(specifier)){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addDeclaration("interop-require"),[util.template("require",{MODULE_NAME:node.source})]))]))}else{var templateName="require-assign";if(specifier.type!=="ImportBatchSpecifier")templateName+="-key";nodes.push(util.template(templateName,{VARIABLE_NAME:variableName,MODULE_NAME:node.source,KEY:specifier.id}))}};CommonJSFormatter.prototype.importDeclaration=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source},true))};CommonJSFormatter.prototype.exportDeclaration=function(node,nodes){if(node.default){var declar=node.declaration;var templateName="exports-default-module";if(this.hasNonDefaultExports)templateName="exports-default-module-override";var assign=util.template(templateName,{VALUE:this._pushStatement(declar,nodes)},true);nodes.push(this._hoistExport(declar,assign,2))}else{DefaultFormatter.prototype.exportDeclaration.apply(this,arguments)}};CommonJSFormatter.prototype.exportSpecifier=function(specifier,node,nodes){this._exportSpecifier(function(){return t.callExpression(t.identifier("require"),[node.source])},specifier,node,nodes)}},{"../../traverse":69,"../../types":73,"../../util":75,"./_default":25}],28:[function(require,module,exports){module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.exportDeclaration=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.importDeclaration=IgnoreFormatter.prototype.importSpecifier=IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":73}],29:[function(require,module,exports){module.exports=SystemFormatter;var AMDFormatter=require("./amd");var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");function SystemFormatter(file){this.exportIdentifier=file.generateUidIdentifier("export");this.noInteropRequire=true;AMDFormatter.apply(this,arguments)}util.inherits(SystemFormatter,AMDFormatter);SystemFormatter.prototype._addImportSource=function(node,exportNode){node._importSource=exportNode.source&&exportNode.source.value;return node};SystemFormatter.prototype._exportsWildcard=function(objectIdentifier,node){var leftIdentifier=this.file.generateUidIdentifier("key");var valIdentifier=t.memberExpression(objectIdentifier,leftIdentifier,true);var left=t.variableDeclaration("var",[t.variableDeclarator(leftIdentifier)]);var right=objectIdentifier;var block=t.blockStatement([this.buildExportCall(leftIdentifier,valIdentifier)]);return this._addImportSource(t.forInStatement(left,right,block),node)};SystemFormatter.prototype._exportsAssign=function(id,init,node){var call=this.buildExportCall(t.literal(id.name),init,true);return this._addImportSource(call,node)};SystemFormatter.prototype.remapExportAssignment=function(node){return this.buildExportCall(t.literal(node.left.name),node)};SystemFormatter.prototype.buildExportCall=function(id,init,isStatement){var call=t.callExpression(this.exportIdentifier,[id,init]);if(isStatement){return t.expressionStatement(call)}else{return call}};SystemFormatter.prototype.importSpecifier=function(specifier,node,nodes){AMDFormatter.prototype.importSpecifier.apply(this,arguments);this._addImportSource(_.last(nodes),node)};SystemFormatter.prototype.buildRunnerSetters=function(block,hoistDeclarators){return t.arrayExpression(_.map(this.ids,function(uid,source){var nodes=[];traverse(block,{enter:function(node){if(node._importSource===source){if(t.isVariableDeclaration(node)){_.each(node.declarations,function(declar){hoistDeclarators.push(t.variableDeclarator(declar.id));nodes.push(t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init)))})}else{nodes.push(node)}this.remove()}}});return t.functionExpression(null,[uid],t.blockStatement(nodes))}))};SystemFormatter.prototype.transform=function(ast){var program=ast.program;var hoistDeclarators=[];var moduleName=this.getModuleName();var moduleNameLiteral=t.literal(moduleName);var block=t.blockStatement(program.body);var runner=util.template("system",{MODULE_NAME:moduleNameLiteral,MODULE_DEPENDENCIES:t.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(block,hoistDeclarators),EXECUTE:t.functionExpression(null,[],block)},true);var handlerBody=runner.expression.arguments[2].body.body;if(!moduleName)runner.expression.arguments.shift();var returnStatement=handlerBody.pop();traverse(block,{enter:function(node,parent,scope){if(t.isFunction(node)){return this.stop()}if(t.isVariableDeclaration(node)){if(node.kind!=="var"&&!t.isProgram(parent)){return}var nodes=[];_.each(node.declarations,function(declar){hoistDeclarators.push(t.variableDeclarator(declar.id));if(declar.init){var assign=t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init));nodes.push(assign)}});if(t.isFor(parent)){if(parent.left===node){return node.declarations[0].id}if(parent.init===node){return t.toSequenceExpression(nodes,scope)}}return nodes}}});if(hoistDeclarators.length){var hoistDeclar=t.variableDeclaration("var",hoistDeclarators);hoistDeclar._blockHoist=true;handlerBody.unshift(hoistDeclar)}traverse(block,{enter:function(node){if(t.isFunction(node))this.stop();if(t.isFunctionDeclaration(node)||node._blockHoist){handlerBody.push(node);this.remove()}}});handlerBody.push(returnStatement);program.body=[runner]}},{"../../traverse":69,"../../types":73,"../../util":75,"./amd":26,lodash:123}],30:[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=[];for(var name in this.ids){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":73,"../../util":75,"./amd":26,lodash:123}],31:[function(require,module,exports){module.exports=transform;var Transformer=require("./transformer");var File=require("../file");var util=require("../util");var _=require("lodash");function transform(code,opts){var file=new File(opts); return file.parse(code)}transform.fromAst=function(ast,code,opts){ast=util.normaliseAst(ast);var file=new File(opts);file.addCode(code);file.transform(ast);return file.generate()};transform._ensureTransformerNames=function(type,keys){for(var i in keys){var key=keys[i];if(!_.has(transform.transformers,key)){throw new ReferenceError("unknown transformer "+key+" specified in "+type)}}};transform.transformers={};transform.moduleFormatters={common:require("./modules/common"),system:require("./modules/system"),ignore:require("./modules/ignore"),amd:require("./modules/amd"),umd:require("./modules/umd")};_.each({specBlockHoistFunctions:require("./transformers/spec-block-hoist-functions"),specNoForInOfAssignment:require("./transformers/spec-no-for-in-of-assignment"),specNoDuplicateProperties:require("./transformers/spec-no-duplicate-properties"),methodBinding:require("./transformers/playground-method-binding"),memoizationOperator:require("./transformers/playground-memoization-operator"),objectGetterMemoization:require("./transformers/playground-object-getter-memoization"),react:require("./transformers/react"),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"),destructuring:require("./transformers/es6-destructuring"),defaultParameters:require("./transformers/es6-default-parameters"),forOf:require("./transformers/es6-for-of"),unicodeRegex:require("./transformers/es6-unicode-regex"),abstractReferences:require("./transformers/es7-abstract-references"),constants:require("./transformers/es6-constants"),letScoping:require("./transformers/es6-let-scoping"),_blockHoist:require("./transformers/_block-hoist"),generators:require("./transformers/es6-generators"),restParameters:require("./transformers/es6-rest-parameters"),_declarations:require("./transformers/_declarations"),coreAliasing:require("./transformers/optional-core-aliasing"),_aliasFunctions:require("./transformers/_alias-functions"),useStrict:require("./transformers/use-strict"),_moduleFormatter:require("./transformers/_module-formatter"),specPropertyLiterals:require("./transformers/spec-property-literals"),specMemberExpressionLiterals:require("./transformers/spec-member-expression-literals")},function(transformer,key){transform.transformers[key]=new Transformer(key,transformer)})},{"../file":3,"../util":75,"./modules/amd":26,"./modules/common":27,"./modules/ignore":28,"./modules/system":29,"./modules/umd":30,"./transformer":32,"./transformers/_alias-functions":33,"./transformers/_block-hoist":34,"./transformers/_declarations":35,"./transformers/_module-formatter":36,"./transformers/es5-property-method-assignment":37,"./transformers/es6-arrow-functions":38,"./transformers/es6-classes":39,"./transformers/es6-computed-property-names":40,"./transformers/es6-constants":41,"./transformers/es6-default-parameters":42,"./transformers/es6-destructuring":43,"./transformers/es6-for-of":44,"./transformers/es6-generators":45,"./transformers/es6-let-scoping":46,"./transformers/es6-modules":47,"./transformers/es6-property-name-shorthand":48,"./transformers/es6-rest-parameters":49,"./transformers/es6-spread":50,"./transformers/es6-template-literals":51,"./transformers/es6-unicode-regex":52,"./transformers/es7-abstract-references":53,"./transformers/es7-array-comprehension":54,"./transformers/es7-exponentiation-operator":55,"./transformers/es7-generator-comprehension":56,"./transformers/es7-object-spread":57,"./transformers/optional-core-aliasing":58,"./transformers/playground-memoization-operator":59,"./transformers/playground-method-binding":60,"./transformers/playground-object-getter-memoization":61,"./transformers/react":62,"./transformers/spec-block-hoist-functions":63,"./transformers/spec-member-expression-literals":64,"./transformers/spec-no-duplicate-properties":65,"./transformers/spec-no-for-in-of-assignment":66,"./transformers/spec-property-literals":67,"./transformers/use-strict":68,lodash:123}],32:[function(require,module,exports){module.exports=Transformer;var traverse=require("../traverse");var t=require("../types");var _=require("lodash");function Transformer(key,transformer,opts){this.experimental=!!transformer.experimental;this.transformer=Transformer.normalise(transformer);this.optional=!!transformer.optional;this.opts=opts||{};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};if(!_.isObject(fns))return;transformer[type]=fns;var aliases=t.FLIPPED_ALIAS_KEYS[type];if(aliases){_.each(aliases,function(alias){transformer[alias]=fns})}});return transformer};Transformer.prototype.astRun=function(file,key){var transformer=this.transformer;var ast=file.ast;if(transformer.ast&&transformer.ast[key]){transformer.ast[key](ast,file)}};Transformer.prototype.transform=function(file){var transformer=this.transformer;var ast=file.ast;var build=function(exit){return function(node,parent,scope){var fns=transformer[node.type];if(!fns)return;var fn=fns.enter;if(exit)fn=fns.exit;if(!fn)return;return fn(node,parent,file,scope)}};this.astRun(file,"before");traverse(ast,{enter:build(),exit:build(true)});this.astRun(file,"after")};Transformer.prototype.canRun=function(file){var opts=file.opts;var key=this.key;if(key[0]==="_")return true;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false;if(this.optional&&!_.contains(opts.optional,key))return false;if(this.experimental&&!opts.experimental)return false;return true}},{"../traverse":69,"../types":73,lodash:123}],33:[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,{enter:function(node){if(!node._aliasFunction){if(t.isFunction(node)){return this.stop()}else{return}}traverse(node,{enter:function(node,parent){if(t.isFunction(node)&&!node._aliasFunction){return this.stop()}if(node._ignoreAliasFunctions)return this.stop();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 this.stop()}});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":69,"../../types":73}],34:[function(require,module,exports){var _=require("lodash");exports.BlockStatement=exports.Program={exit:function(node){var hasChange=false;for(var i in node.body){var bodyNode=node.body[i];if(bodyNode&&bodyNode._blockHoist)hasChange=true}if(!hasChange)return;var nodePriorities=_.groupBy(node.body,function(bodyNode){return bodyNode._blockHoist||0});node.body=_.flatten(_.values(nodePriorities).reverse())}}},{lodash:123}],35:[function(require,module,exports){var t=require("../../types");exports.BlockStatement=exports.Program=function(node){var kinds={};var kind;for(var i in node._declarations){var declar=node._declarations[i];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]))}}for(kind in kinds){node.body.unshift(t.variableDeclaration(kind,kinds[kind]))}}},{"../../types":73}],36:[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":31}],37:[function(require,module,exports){var util=require("../../util");exports.Property=function(node){if(node.method)node.method=false};exports.ObjectExpression=function(node,parent,file){var mutatorMap={};var hasAny=false;node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){hasAny=true;util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.value);return false}else{return true}});if(!hasAny)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":75}],38:[function(require,module,exports){var t=require("../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction="arrow";node.expression=false;node.type="FunctionExpression";return node}},{"../../types":73}],39:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");exports.ClassDeclaration=function(node,parent,file,scope){var closure=true;if(t.isProgram(parent)||t.isBlockStatement(parent)){closure=false}var factory=new Class(node,file,scope,closure);var newNode=factory.run();if(factory.closure){if(closure){scope.push({kind:"var",key:node.id.key,id:node.id});return t.assignmentExpression("=",node.id,newNode)}else{return t.variableDeclaration("let",[t.variableDeclarator(node.id,newNode)])}}else{return newNode}};exports.ClassExpression=function(node,parent,file,scope){return new Class(node,file,scope,true).run()};function Class(node,file,scope,closure){this.closure=closure;this.scope=scope;this.node=node;this.file=file;this.hasInstanceMutators=false;this.hasStaticMutators=false;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||file.generateUidIdentifier("class",scope);this.superName=node.superClass}Class.prototype.run=function(){var superName=this.superName;var className=this.className;var file=this.file;var body=this.body=[];var constructor=t.functionExpression(null,[],t.blockStatement([]));if(this.node.id)constructor.id=className;this.constructor=constructor;body.push(t.variableDeclaration("let",[t.variableDeclarator(className,constructor)]));if(superName&&t.isDynamic(superName)){var superRefName="super";if(className)superRefName=className.name+"Super";var superRef=file.generateUidIdentifier(superRefName,this.scope);body.unshift(t.variableDeclaration("var",[t.variableDeclarator(superRef,superName)]));superName=superRef}this.superName=superName;if(superName){body.push(t.expressionStatement(t.callExpression(file.addDeclaration("inherits"),[className,superName])))}this.buildBody();t.inheritsComments(body[0],this.node);if(this.closure){if(body.length===1){return constructor}else{body.push(t.returnStatement(className));return t.callExpression(t.functionExpression(null,[],t.blockStatement(body)),[])}}else{return body}};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;for(var i in classBody){var node=classBody[i];if(t.isMethodDefinition(node)){self.replaceInstanceSuperReferences(node);if(node.key.name==="constructor"){self.pushConstructor(node)}else{self.pushMethod(node)}}else if(t.isPrivateDeclaration(node)){self.closure=true;body.unshift(node)}}if(!this.hasConstructor&&superName&&!t.isFalsyExpression(superName)){constructor.body.body.push(util.template("class-super-constructor-call",{SUPER_NAME:superName},true))}var instanceProps;var staticProps;if(this.hasInstanceMutators){var protoId=util.template("prototype-identifier",{CLASS_NAME:className});instanceProps=util.buildDefineProperties(this.instanceMutatorMap,protoId)}if(this.hasStaticMutators){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("prototype-properties"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var kind=node.kind;if(kind===""){var className=this.className;if(!node.static)className=t.memberExpression(className,t.identifier("prototype"));methodName=t.memberExpression(className,methodName,node.computed);var expr=t.expressionStatement(t.assignmentExpression("=",methodName,node.value));t.inheritsComments(expr,node);this.body.push(expr)}else{var mutatorMap=this.instanceMutatorMap;if(node.static){this.hasStaticMutators=true;mutatorMap=this.staticMutatorMap}else{this.hasInstanceMutators=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,{enter: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":69,"../../types":73,"../../util":75}],40:[function(require,module,exports){var util=require("../../util");var t=require("../../types");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;var containerBody=containerCallee.body.body;containerCallee._aliasFunction=true;for(var i in computed){var prop=computed[i];containerBody.unshift(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,true),prop.value)))}return container}},{"../../types":73,"../../util":75}],41:[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 hasConstants=false;var constants={};var check=function(parent,names,scope){for(var name in names){var nameNode=names[name];if(!_.has(constants,name))continue;if(parent&&t.isBlockStatement(parent)&&parent!==constants[name])continue;if(scope){var defined=scope.get(name);if(defined&&defined===nameNode)continue}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(t.isExportDeclaration(child)){child=child.declaration}if(t.isVariableDeclaration(child,{kind:"const"})){for(var i in child.declarations){var declar=child.declarations[i];var ids=getIds(declar);for(var name in ids){var nameNode=ids[name];var names={};names[name]=nameNode;check(parent,names);constants[name]=parent;hasConstants=true}declar._ignoreConstant=true}child._ignoreConstant=true;child.kind="let"}});if(!hasConstants)return;traverse(node,{enter:function(child,parent,scope){if(child._ignoreConstant)return;if(t.isVariableDeclaration(child))return;if(t.isVariableDeclarator(child)||t.isDeclaration(child)||t.isAssignmentExpression(child)){check(parent,getIds(child),scope)}}})}},{"../../traverse":69,"../../types":73,lodash:123}],42:[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 iife=false;var i;var def;for(i in node.defaults){def=node.defaults[i];if(!def)continue;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(ids.indexOf(node.name)>=0){throw file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}if(scope.has(node.name)){iife=true}};check(def,node);traverse(def,{enter:check})});var has=scope.get(param.name);if(has&&node.params.indexOf(has)<0){iife=true}}var body=[];for(i in node.defaults){def=node.defaults[i];if(!def)continue;body.push(util.template("if-undefined-set-to",{VARIABLE:node.params[i],DEFAULT:def},true))}if(iife){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":69,"../../types":73,"../../util":75,lodash:123}],43:[function(require,module,exports){var t=require("../../types");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){for(var i in pattern.properties){var prop=pattern.properties[i];if(t.isSpreadProperty(prop)){var keys=[];for(var i2 in pattern.properties){var prop2=pattern.properties[i2];if(i2>=i)break;if(t.isSpreadProperty(prop2))continue;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-without-properties"),[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){if(!pattern.elements)return;var i;var hasSpreadElement=false;for(i in pattern.elements){if(t.isSpreadElement(pattern.elements[i])){hasSpreadElement=true;break}}var toArray=opts.file.toArray(parentId,!hasSpreadElement&&pattern.elements.length);var _parentId=opts.file.generateUidIdentifier("ref",opts.scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(_parentId,toArray)]));parentId=_parentId;for(i in pattern.elements){var elem=pattern.elements[i];if(!elem)continue;i=+i;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 i;var declar;var hasPattern=false;for(i in node.declarations){declar=node.declarations[i];if(t.isPattern(declar.id)){hasPattern=true;break}}if(!hasPattern)return;for(i in node.declarations){declar=node.declarations[i];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)){declar=null;for(i in nodes){node=nodes[i];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":73}],44:[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.inheritsComments(node2,node);t.ensureBlock(node);var block=node2.body;block.body.push(declar);block.body=block.body.concat(node.body.body);return node2}},{"../../types":73,"../../util":75}],45:[function(require,module,exports){exports.ast={before:require("regenerator").transform}},{regenerator:131}],46:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");var isLet=function(node,parent){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;if(!t.isFor(parent)||t.isFor(parent)&&parent.left!==node){_.each(node.declarations,function(declar){declar.init=declar.init||t.identifier("undefined")})}node._let=true;node.kind="var";return true};var isVar=function(node,parent){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node,parent)};var standardiseLets=function(declars){for(var i in declars){delete declars[i]._let}};exports.VariableDeclaration=function(node,parent){isLet(node,parent)};exports.Loop=function(node,parent,file,scope){var init=node.left||node.init;if(isLet(init,node)){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.isLoop(parent)){var letScoping=new LetScoping(false,block,parent,file,scope);letScoping.run()}};function LetScoping(loopParent,block,parent,file,scope){this.loopParent=loopParent;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.checkLoop();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(!this.info.hasDuplicates)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,{enter:replace})};var loopParent=this.loopParent;if(loopParent){traverseReplace(loopParent.right,loopParent);traverseReplace(loopParent.test,loopParent);traverseReplace(loopParent.update,loopParent)}traverse(block,{enter:replace})};LetScoping.prototype.getInfo=function(){var block=this.block;var scope=this.scope;var file=this.file;var opts={outsideKeys:[],declarators:block._letDeclars||[],duplicates:{},hasDuplicates:false,keys:[]};var duplicates=function(id,key){var has=scope.parentGet(key);if(has&&has!==id){opts.duplicates[key]=id.name=file.generateUid(key,scope);opts.hasDuplicates=true}};var i;var declar;for(i in opts.declarators){declar=opts.declarators[i];opts.declarators.push(declar);var keys=t.getIds(declar,true);_.each(keys,duplicates);keys=Object.keys(keys);opts.outsideKeys=opts.outsideKeys.concat(keys);opts.keys=opts.keys.concat(keys)}for(i in block.body){declar=block.body[i];if(!isLet(declar,block))continue;_.each(t.getIds(declar,true),function(id,key){duplicates(id,key);opts.keys.push(key)})}return opts};LetScoping.prototype.checkLoop=function(){var has={hasContinue:false,hasReturn:false,hasBreak:false};traverse(this.block,{enter:function(node,parent){var replace;if(t.isFunction(node)||t.isLoop(node)){return this.stop()}if(node&&!node.label){if(t.isBreakStatement(node)){if(t.isSwitchCase(parent))return;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,{enter:function(node,parent){if(t.isForStatement(node)){if(isVar(node.init,node)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left,node)){node.left=node.left.declarations[0].id}}else if(isVar(node,parent)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return this.stop()}}})};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,{enter:function(node,parent,scope){if(t.isFunction(node)){traverse(node,{enter: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 this.stop()}else if(t.isLoop(node)){return this.stop()}}});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=[];for(var i in node.declarations){var declar=node.declarations[i];if(!declar.init)continue;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 loopParent=this.loopParent;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=loopParent.label=loopParent.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":69,"../../types":73,"../../util":75,lodash:123}],47:[function(require,module,exports){var t=require("../../types");exports.ImportDeclaration=function(node,parent,file){var nodes=[];if(node.specifiers.length){for(var i in node.specifiers){file.moduleFormatter.importSpecifier(node.specifiers[i],node,nodes,parent)}}else{file.moduleFormatter.importDeclaration(node,nodes,parent)}return nodes};exports.ExportDeclaration=function(node,parent,file){var nodes=[];if(node.declaration){if(t.isVariableDeclaration(node.declaration)){var declar=node.declaration.declarations[0];declar.init=declar.init||t.identifier("undefined")}file.moduleFormatter.exportDeclaration(node,nodes,parent)}else{for(var i in node.specifiers){file.moduleFormatter.exportSpecifier(node.specifiers[i],node,nodes,parent)}}return nodes}},{"../../types":73}],48:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.Property=function(node){if(!node.shorthand)return;node.shorthand=false;node.key=t.removeComments(_.clone(node.key))}},{"../../types":73,lodash:123}],49:[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":73}],50:[function(require,module,exports){var t=require("../../types");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){for(var i in nodes){if(t.isSpreadElement(nodes[i])){return true}}return false};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};for(var i in props){var prop=props[i];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,scope){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.literal(null);node.arguments=[];var nodes;if(args.length===1&&args[0].argument.name==="arguments"){nodes=[args[0].argument]}else{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;var temp;if(t.isMemberExpression(callee)){contextLiteral=callee.object;if(t.isDynamic(contextLiteral)){temp=contextLiteral=scope.generateTemp(file);callee.object=t.assignmentExpression("=",temp,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":73}],51:[function(require,module,exports){var t=require("../../types");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=[];for(var i in quasi.quasis){var elem=quasi.quasis[i];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=[];var i;for(i in node.quasis){var elem=node.quasis[i];nodes.push(t.literal(elem.value.cooked));var expr=node.expressions.shift();if(expr)nodes.push(expr)}if(nodes.length>1){var last=nodes[nodes.length-1];if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());for(i in nodes){root=buildBinaryExpression(root,nodes[i])}return root}else{return nodes[0]}}},{"../../types":73}],52:[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(regex.flags.indexOf("u")<0)return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:123,"regexpu/rewrite-pattern":164}],53:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.experimental=true;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)){temp=value=scope.generateTemp(file)}}if(node.operator!=="="){value=t.binaryExpression(node.operator[0],util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object}),value)}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)){temp=scope.generateTemp(file)}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})};exports.PrivateDeclaration=function(node){return t.variableDeclaration("const",node.declarations.map(function(id){return t.variableDeclarator(id,t.newExpression(t.identifier("WeakMap"),[]))}))}},{"../../types":73,"../../util":75}],54:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.experimental=true;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});var aliasPossibles=[result.callee.object,result];for(var i in aliasPossibles){var call=aliasPossibles[i];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.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":73,"../../util":75}],55:[function(require,module,exports){exports.experimental=true;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":73}],56:[function(require,module,exports){var arrayComprehension=require("./es7-array-comprehension");var t=require("../../types");exports.experimental=true;exports.ComprehensionExpression=function(node){if(!node.generator)return;var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);container._aliasFunction=true;body.push(arrayComprehension._build(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])}},{"../../types":73,"./es7-array-comprehension":54}],57:[function(require,module,exports){var t=require("../../types");exports.experimental=true;exports.ObjectExpression=function(node){var hasSpread=false;var i;var prop;for(i in node.properties){prop=node.properties[i];if(t.isSpreadProperty(prop)){hasSpread=true;break}}if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};for(i in node.properties){prop=node.properties[i];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":73}],58:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var core=require("core-js/library");var t=require("../../types");var _=require("lodash");exports.optional=true;exports.ast={enter:function(ast,file){file._coreId=file.generateUidIdentifier("core");var specifiers=[t.importSpecifier(t.identifier("default"),file._coreId)];var declar=t.importDeclaration(specifiers,t.literal("core-js/library"));ast.program.body.unshift(declar)},exit:function(ast,file){traverse(ast,{enter:function(node,parent){var prop;if(t.isMemberExpression(node)&&t.isReferenced(node,parent)){var obj=node.object;prop=node.property;if(!t.isReferenced(obj,node))return;var coreHasObject=obj.name!=="_"&&_.has(core,obj.name);if(coreHasObject&&_.has(core[obj.name],prop.name)){this.stop();return t.memberExpression(file._coreId,node)}}else if(t.isCallExpression(node)){if(node.arguments.length)return;var callee=node.callee;if(!t.isMemberExpression(callee))return;if(!callee.computed)return;prop=callee.property;if(!t.isIdentifier(prop.object,{name:"Symbol"}))return;if(!t.isIdentifier(prop.property,{name:"iterator"}))return;return util.template("corejs-iterator",{CORE_ID:file._coreId,VALUE:callee.object})}}})}}},{"../../traverse":69,"../../types":73,"../../util":75,"core-js/library":116,lodash:123}],59:[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":73}],60:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.BindMemberExpression=function(node,parent,file,scope){var object=node.object;var prop=node.property;var temp;if(t.isDynamic(object)){temp=object=scope.generateTemp(file)}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}};exports.BindFunctionExpression=function(node,parent,file,scope){var buildCall=function(args){var param=file.generateUidIdentifier("val",scope);return t.functionExpression(null,[param],t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(param,node.callee),args))]))};if(_.find(node.arguments,t.isDynamic)){var temp=scope.generateTemp(file,"args");return t.sequenceExpression([t.assignmentExpression("=",temp,t.arrayExpression(node.arguments)),buildCall(node.arguments.map(function(node,i){return t.memberExpression(temp,t.literal(i),true)}))])}else{return buildCall(node.arguments)}}},{"../../types":73,lodash:123}],61:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");exports.Property=exports.MethodDefinition=function(node){if(node.kind!=="memo")return;node.kind="get";var value=node.value;t.ensureBlock(value);var key=node.key;if(t.isIdentifier(key)&&!node.computed){key=t.literal(key.name)}traverse(value,{enter:function(node){if(t.isFunction(node))return;if(t.isReturnStatement(node)&&node.argument){node.argument=t.memberExpression(util.template("object-getter-memoization",{KEY:key,VALUE:node.argument}),key,true)}}})}},{"../../traverse":69,"../../types":73,"../../util":75}],62:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");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])||tagName.indexOf("-")>=0)){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;var i;for(i in node.children){var child=node.children[i];if(t.isLiteral(child)){var lines=child.value.split(/\r\n|\n|\r/);for(i in lines){var line=lines[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))}}continue}else if(t.isXJSEmptyExpression(child)){continue}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;for(var i in props){prop=props[i];if(t.isIdentifier(prop.key,{name:"displayName"})){safe=false;break}}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":73,esutils:121}],63:[function(require,module,exports){var t=require("../../types");exports.BlockStatement=function(node,parent){if(t.isFunction(parent))return;node.body=node.body.map(function(node){if(t.isFunction(node)){node.type="FunctionExpression";var declar=t.variableDeclaration("let",[t.variableDeclarator(node.id,node)]);declar._blockHoist=true;return declar}else{return node}})}},{"../../types":73}],64:[function(require,module,exports){var esutils=require("esutils");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}else if(!node.computed&&t.isIdentifier(prop)&&esutils.keyword.isKeywordES6(prop.name,true)){node.property=t.literal(prop.name);node.computed=true}}},{"../../types":73,esutils:121}],65:[function(require,module,exports){var t=require("../../types");exports.ObjectExpression=function(node,parent,file){var keys=[];for(var i in node.properties){var prop=node.properties[i];if(prop.computed||prop.kind!=="init")continue;var key=prop.key;if(t.isIdentifier(key)){key=key.name}else if(t.isLiteral(key)){key=key.value}else{continue}if(keys.indexOf(key)>=0){throw file.errorWithNode(prop.key,"Duplicate property key")}else{keys.push(key)}}}},{"../../types":73}],66:[function(require,module,exports){var t=require("../../types");exports.ForInStatement=exports.ForOfStatement=function(node,parent,file){var left=node.left;if(t.isVariableDeclaration(left)){var declar=left.declarations[0];if(declar.init)throw file.errorWithNode(declar,"No assignments allowed in for-in/of head")}}},{"../../types":73}],67:[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(!node.computed&&t.isIdentifier(key)&&esutils.keyword.isKeywordES6(key.name,true)){node.key=t.literal(key.name)}}},{"../../types":73,esutils:121}],68:[function(require,module,exports){var t=require("../../types");exports.ast={exit: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":73}],69:[function(require,module,exports){module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function traverse(parent,opts,scope){if(!parent)return;if(_.isArray(parent)){_.each(parent,function(node){traverse(node,opts,scope)});return}var keys=t.VISITOR_KEYS[parent.type];if(!keys)return;opts=opts||{};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(opts.blacklist&&opts.blacklist.indexOf(node.type)>-1)return;var maybeReplace=function(result){if(result===false)return;if(result==null)return;var isArray=_.isArray(result);var inheritTo=result;if(isArray)inheritTo=result[0];if(inheritTo)t.inheritsComments(inheritTo,node);node=obj[key]=result;updated=true;if(isArray&&_.contains(t.STATEMENT_OR_BLOCK_KEYS,key)&&!t.isBlockStatement(obj)){t.ensureBlock(obj,key)}};var stopped=false;var removed=false;var context={stop:function(){stopped=true},remove:function(){this.stop();removed=true}};var ourScope=scope;if(t.isScope(node))ourScope=new Scope(node,scope);if(opts.enter){var result=opts.enter.call(context,node,parent,ourScope);maybeReplace(result);if(removed){obj[key]=null;updated=true}if(stopped)return}traverse(node,opts,ourScope);if(opts.exit){maybeReplace(opts.exit.call(context,node,parent,ourScope))}};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._declarations;delete node.extendedRange;delete node._scopeInfo;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,{enter: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,{blacklist:blacklistTypes,enter:function(node){if(node.type===type){has=true;this.stop()}}});return has}},{"../types":73,"./scope":70,lodash:123}],70:[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;var info=this.getInfo();this.references=info.references;this.declarations=info.declarations}var vars=require("jshint/src/vars");Scope.defaultDeclarations=_.flatten([vars.newEcmaIdentifiers,vars.node,vars.ecmaIdentifiers,vars.reservedVars].map(_.keys));Scope.add=function(node,references){if(!node)return;_.defaults(references,t.getIds(node,true))};Scope.prototype.generateTemp=function(file,name){var id=file.generateUidIdentifier(name||"temp",this);this.push({key:id.name,id:id});return id};Scope.prototype.getInfo=function(){var block=this.block;if(block._scopeInfo)return block._scopeInfo;var info=block._scopeInfo={};var references=info.references={};var declarations=info.declarations={};var add=function(node,reference){Scope.add(node,references);if(!reference)Scope.add(node,declarations)};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,{enter: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 this.stop();if(block.id&&node===block.id)return;if(t.isIdentifier(node)&&t.isReferenced(node,parent)&&!scope.has(node.name)){add(node,true)}if(t.isDeclaration(node)&&!t.isLet(node)){add(node)}}},this)}if(t.isFunction(block)){add(block.rest);_.each(block.params,function(param){add(param)})}return info};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,decl){return id&&(this.getOwn(id,decl)||this.parentGet(id,decl))};Scope.prototype.getOwn=function(id,decl){var refs=this.references;if(decl)refs=this.declarations;return _.has(refs,id)&&refs[id]};Scope.prototype.parentGet=function(id,decl){return this.parent&&this.parent.get(id,decl)};Scope.prototype.has=function(id,decl){return id&&(this.hasOwn(id,decl)||this.parentHas(id,decl))||_.contains(Scope.defaultDeclarations,id)};Scope.prototype.hasOwn=function(id,decl){return!!this.getOwn(id,decl)};Scope.prototype.parentHas=function(id,decl){return this.parent&&this.parent.has(id,decl)}},{"../types":73,"./index":69,"jshint/src/vars":122,lodash:123}],71:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While"],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","Loop"],ForInStatement:["Statement","For","Scope","Loop"],ForStatement:["Statement","For","Scope","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable"]}},{}],72:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrowFunctionExpression:["params","body"],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"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],Literal:["value"],LogicalExpression:["operator","left","right"],MemberExpression:["object","property","computed"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],WithStatement:["object","body"],YieldExpression:["argument","delegate"]}},{}],73:[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.STATEMENT_OR_BLOCK_KEYS=["consequent","body"];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");t.FLIPPED_ALIAS_KEYS={};_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=t.FLIPPED_ALIAS_KEYS[alias]=t.FLIPPED_ALIAS_KEYS[alias]||[];types.push(type)})});_.each(t.FLIPPED_ALIAS_KEYS,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;var is=t["is"+type]=function(node,opts){return node&&types.indexOf(node.type)>=0&&t.shallowEqual(node,opts)};addAssert(type,is)});t.isExpression=function(node){return!t.isStatement(node)};addAssert("Expression",t.isExpression);t.isFalsyExpression=function(node){if(t.isLiteral(node)){return!node.value}else if(t.isIdentifier(node)){return node.name==="undefined"}return false};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.isExpressionStatement(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&&!parent.computed)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,key){key=key||"body";node[key]=t.toBlock(node[key],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 arrKeys=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(arrKeys){for(var i in arrKeys){var key=arrKeys[i];search=search.concat(id[key]||[])}}}if(!map)ids=_.keys(ids);return ids};t.getIds.nodes={AssignmentExpression:"left",ImportSpecifier:"name",ExportSpecifier:"name",VariableDeclarator:"id",FunctionDeclaration:"id",ClassDeclaration:"id",MemeberExpression:"object",SpreadElement:"argument",Property:"value"};t.getIds.arrays={ExportDeclaration:["specifiers","declaration"],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){_.each(["leadingComments","trailingComments"],function(key){child[key]=_.uniq(_.compact([].concat(child[key],parent[key])))});return child};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};t.isSpecifierDefault=function(specifier){return t.isIdentifier(specifier.id)&&specifier.id.name==="default"}},{"./alias-keys":71,"./builder-keys":72,"./visitor-keys":74,esutils:121,lodash:123}],74:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindFunctionExpression:["callee","arguments"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ClassProperty:["key"],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"],PrivateDeclaration:["declarations"],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"]}},{}],75:[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);map.enumerable=t.literal(true);_.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,{enter:function(node){if(t.isIdentifier(node)&&_.has(nodes,node.name)){return nodes[node.name]}}})}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(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.normaliseAst=function(ast,comments,tokens){if(ast&&ast.type==="Program"){return t.file(ast,comments||[],tokens||[])}else{throw new Error("Not a valid ast?")}};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowImportExportEverywhere:true,allowReturnOutsideFunction: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=exports.normaliseAst(ast,comments,tokens);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+"/transformation/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":175,"./patch":24,"./traverse":69,"./types":73,"acorn-6to5":1,buffer:92,estraverse:117,fs:90,lodash:123,path:99,util:115}],76:[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("Printable").field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("Node").bases("Printable").field("type",isString);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")]).field("comments",or([or(def("Block"),def("Line"))],null),defaults["null"],true);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));def("Block").bases("Printable").build("loc","value").field("value",isString);def("Line").bases("Printable").build("loc","value").field("value",isString)},{"../lib/shared":87,"../lib/types":88}],77:[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":88,"./core":76}],78:[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("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("PropertyPattern").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).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"),def("Expression"))).field("value",def("Function")).field("computed",isBoolean,defaults["false"]);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("key").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);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"]).field("implements",[def("ClassImplements")],defaults.emptyArray);def("ClassImplements").bases("Node").build("id").field("id",def("Identifier")).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":87,"../lib/types":88,"./core":76}],79:[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":87,"../lib/types":88,"./core":76}],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;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("Type").bases("Node");def("AnyTypeAnnotation").bases("Type");def("VoidTypeAnnotation").bases("Type");def("NumberTypeAnnotation").bases("Type");def("StringTypeAnnotation").bases("Type");def("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",isString).field("raw",isString);def("BooleanTypeAnnotation").bases("Type");def("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",def("Type"));def("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",def("Type"));def("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[def("FunctionTypeParam")]).field("returnType",def("Type")).field("rest",or(def("FunctionTypeParam"),null)).field("typeParameters",or(def("TypeParameterDeclaration"),null));def("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",def("Identifier")).field("typeAnnotation",def("Type")).field("optional",isBoolean);def("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[def("ObjectTypeProperty")]).field("indexers",[def("ObjectTypeIndexer")],defaults.emptyArray).field("callProperties",[def("ObjectTypeCallProperty")],defaults.emptyArray); def("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",or(def("Literal"),def("Identifier"))).field("value",def("Type")).field("optional",isBoolean);def("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",def("Identifier")).field("key",def("Type")).field("value",def("Type"));def("ObjectTypeCallProperty").bases("Node").build("value").field("value",def("FunctionTypeAnnotation")).field("static",isBoolean,false);def("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("id",def("Identifier"));def("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("MemberTypeAnnotation").bases("Type").build("object","property").field("object",def("Identifier")).field("property",or(def("MemberTypeAnnotation"),def("GenericTypeAnnotation")));def("UnionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",def("Type"));def("Identifier").field("typeAnnotation",or(def("TypeAnnotation"),null),defaults["null"]);def("TypeParameterDeclaration").bases("Node").build("params").field("params",[def("Identifier")]);def("TypeParameterInstantiation").bases("Node").build("params").field("params",[def("Type")]);def("Function").field("returnType",or(def("TypeAnnotation"),null),defaults["null"]).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]);def("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",def("TypeAnnotation")).field("static",isBoolean,false);def("ClassImplements").field("typeParameters",or(def("TypeParameterInstantiation"),null),defaults["null"]);def("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]).field("body",def("ObjectTypeAnnotation")).field("extends",[def("InterfaceExtends")]);def("InterfaceExtends").bases("Node").build("id").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null)).field("right",def("Type"));def("TupleTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("DeclareVariable").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareFunction").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareClass").bases("InterfaceDeclaration").build("id");def("DeclareModule").bases("Statement").build("id","body").field("id",or(def("Identifier"),def("Literal"))).field("body",def("BlockStatement"))},{"../lib/shared":87,"../lib/types":88,"./core":76}],81:[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":87,"../lib/types":88,"./core":76}],82:[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":89,assert:91}],83:[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":85,"./scope":86,"./types":88,assert:91,util:115}],84:[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);this._visiting=false;this._changeReported=false}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;var recursiveVisitWarning=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");PVp.visit=function(path){assert.ok(!this._visiting,recursiveVisitWarning);this._visiting=true;this._changeReported=false;this.reset.apply(this,arguments);try{return this.visitWithoutReset(path)}finally{this._visiting=false}};PVp.reset=function(path){};PVp.visitWithoutReset=function(path){if(this instanceof this.Context){return this.visitor.visitWithoutReset(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.visitWithoutReset,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.visitWithoutReset(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};PVp.reportChanged=function(){this._changeReported=true};PVp.wasChangeReported=function(){return this._changeReported};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))};sharedContextProtoMethods.visit=function visit(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;PathVisitor.fromMethodsObject(newVisitor||this.visitor).visitWithoutReset(path)};sharedContextProtoMethods.reportChanged=function reportChanged(){this.visitor.reportChanged()};module.exports=PathVisitor},{"./node-path":83,"./types":88,assert:91}],85:[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":88,assert:91}],86:[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":83,"./types":88,assert:91}],87:[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":88}],88:[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:91}],89:[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":76,"./def/e4x":77,"./def/es6":78,"./def/es7":79,"./def/fb-harmony":80,"./def/mozilla":81,"./lib/equiv":82,"./lib/node-path":83,"./lib/path-visitor":84,"./lib/types":88}],90:[function(require,module,exports){},{}],91:[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/":115}],92:[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,2);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,unitSize){if(unitSize)length-=length%unitSize;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":93,ieee754:94,"is-array":95}],93:[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)},{}],94:[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}},{}],95:[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)}},{}],96:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(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(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];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(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(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"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(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};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(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;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}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(listeners)){this.removeListener(type,listeners)}else{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(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],97:[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}}},{}],98:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],99:[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:100}],100:[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")}},{}],101:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":102}],102:[function(require,module,exports){(function(process){module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);forEach(objectKeys(Writable.prototype),function(method){if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]});function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}}).call(this,require("_process"))},{"./_stream_readable":104,"./_stream_writable":106,_process:100,"core-util-is":107,inherits:97}],103:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":105,"core-util-is":107,inherits:97}],104:[function(require,module,exports){(function(process){module.exports=Readable;var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;if(!EE.listenerCount)EE.listenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("stream");var util=require("core-util-is");util.inherits=require("inherits");var StringDecoder;util.inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc};var MAX_HWM=8388608;function roundUpToNextPowerOf2(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;var ret;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){ret=null;if(state.length>0&&state.decoder){ret=fromList(n,state);state.length-=ret.length}if(state.length===0)endReadable(this);return ret}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)process.nextTick(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){if(readable!==src)return;cleanup()}function onend(){dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);function cleanup(){dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);if(!dest._writableState||dest._writableState.needDrain)ondrain()}function onerror(er){unpipe();dest.removeListener("error",onerror);if(EE.listenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){this.on("readable",pipeOnReadable);state.flowing=true;process.nextTick(function(){flow(src)})}return dest};function pipeOnDrain(src){return function(){var dest=this;var state=src._readableState;state.awaitDrain--;if(state.awaitDrain===0)flow(src)}}function flow(src){var state=src._readableState;var chunk;state.awaitDrain=0;function write(dest,i,list){var written=dest.write(chunk);if(false===written){state.awaitDrain++}}while(state.pipesCount&&null!==(chunk=src.read())){if(state.pipesCount===1)write(state.pipes,0,null);else forEach(state.pipes,write);src.emit("data",chunk);if(state.awaitDrain>0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&!this._readableState.flowing)emitDataEvents(this);if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){this.read(0)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.resume=function(){emitDataEvents(this);this.read(0);this.emit("resume")};Readable.prototype.pause=function(){emitDataEvents(this,true);this.emit("pause")};function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing){throw new Error("Cannot switch to old mode now.")}var paused=startPaused||false;var readable=false;stream.readable=true;stream.pipe=Stream.prototype.pipe;stream.on=stream.addListener=Stream.prototype.on;stream.on("readable",function(){readable=true;var c;while(!paused&&null!==(c=stream.read()))stream.emit("data",c);if(c===null){readable=false;stream._readableState.needReadable=true}});stream.pause=function(){paused=true;this.emit("pause")};stream.resume=function(){paused=false;if(readable)process.nextTick(function(){stream.emit("readable")});else this.read(0);this.emit("resume")};stream.emit("readable")}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(typeof stream[i]==="function"&&typeof this[i]==="undefined"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream"); if(!state.endEmitted&&state.calledRead){state.ended=true;process.nextTick(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{_process:100,buffer:92,"core-util-is":107,events:96,inherits:97,isarray:98,stream:112,"string_decoder/":113}],105:[function(require,module,exports){module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);var ts=this._transformState=new TransformState(options,this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var rs=stream._readableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":102,"core-util-is":107,inherits:97}],106:[function(require,module,exports){(function(process){module.exports=Writable;var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream=require("stream");util.inherits(Writable,Stream);function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb}function WritableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.objectMode=!!options.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function Writable(options){var Duplex=require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,state,cb){var er=new Error("write after end");stream.emit("error",er);process.nextTick(function(){cb(er)})}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);process.nextTick(function(){cb(er)});valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=function(){};if(state.ended)writeAfterEnd(this,state,cb);else if(validChunk(this,state,chunk,cb))ret=writeOrBuffer(this,state,chunk,encoding,cb);return ret};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing)state.buffer.push(new WriteReq(chunk,encoding,cb));else doWrite(stream,state,len,chunk,encoding,cb);return ret}function doWrite(stream,state,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){if(sync)process.nextTick(function(){cb(er)});else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(stream,state);if(!finished&&!state.bufferProcessing&&state.buffer.length)clearBuffer(stream,state);if(sync){process.nextTick(function(){afterWrite(stream,state,finished,cb)})}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);cb();if(finished)finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;for(var c=0;c<state.buffer.length;c++){var entry=state.buffer[c];var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,len,chunk,encoding,cb);if(state.writing){c++;break}}state.bufferProcessing=false;if(c<state.buffer.length)state.buffer=state.buffer.slice(c);else state.buffer.length=0}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(typeof chunk!=="undefined"&&chunk!==null)this.write(chunk,encoding);if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(stream,state){return state.ending&&state.length===0&&!state.finished&&!state.writing}function finishMaybe(stream,state){var need=needFinish(stream,state);if(need){state.finished=true;stream.emit("finish")}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true}}).call(this,require("_process"))},{"./_stream_duplex":102,_process:100,buffer:92,"core-util-is":107,inherits:97,stream:112}],107:[function(require,module,exports){(function(Buffer){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;function isBuffer(arg){return Buffer.isBuffer(arg)}exports.isBuffer=isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,require("buffer").Buffer)},{buffer:92}],108:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":103}],109:[function(require,module,exports){var Stream=require("stream");exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":102,"./lib/_stream_passthrough.js":103,"./lib/_stream_readable.js":104,"./lib/_stream_transform.js":105,"./lib/_stream_writable.js":106,stream:112}],110:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":105}],111:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":106}],112:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:96,inherits:97,"readable-stream/duplex.js":101,"readable-stream/passthrough.js":108,"readable-stream/readable.js":109,"readable-stream/transform.js":110,"readable-stream/writable.js":111}],113:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:92}],114:[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"}},{}],115:[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":114,_process:100,inherits:97}],116:[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,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)}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,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 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,that){var O=Object(assertDefined(this)),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 turn(mapfn,target){assertFunction(mapfn);var memo=target==undefined?[]:Object(target),O=ES5Object(this),length=toLength(O.length),index=0;for(;length>index;index++){if(mapfn(memo,O[index],index,this)===false)break}return memo}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}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);defineIterator(Base,NAME,createIter(DEFAULT),DEFAULT==VALUE?"values":"entries");DEFAULT&&$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:createIter(KEY+VALUE),keys:createIter(KEY),values:createIter(VALUE)})}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it);return SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){return assertObject((it[SYMBOL_ITERATOR]||Iterators[classof(it)]).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(NODE)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=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,endPosition){assertNotRegExp(searchString);var len=this.length,end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return String(this).slice(end-searchString.length,end)===searchString},includes:function(searchString,position){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 index=toLength(min(position,this.length));searchString+="";return String(this).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,mapfn,that){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),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);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(){$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(DICT){function Dict(iterable){var dict=create(null);if(iterable!=undefined){if(isIterable(iterable)){for(var iter=getIterator(iterable),step,value;!(step=iter.next()).done;){value=step.value;dict[value[0]]=value[1]}}else assign(dict,iterable)}return dict}Dict[PROTOTYPE]=null;function DictIterator(iterated,kind){set(this,ITER,{o:ES5Object(iterated),a:getKeys(iterated),i:0,k:kind})}createIterator(DictIterator,DICT,function(){var iter=this[ITER],O=iter.o,keys=iter.a,kind=iter.k,key;while(true){if(iter.i>=keys.length)return iterResult(1);if(has(O,key=keys[iter.i++]))break}if(kind==KEY)return iterResult(0,key);if(kind==VALUE)return iterResult(0,O[key]);return iterResult(0,[key,O[key]])});function createDictIter(kind){return function(it){return new DictIterator(it,kind)}}function createDictMethod(type){var isMap=type==1,isEvery=type==4;return function(object,callbackfn,that){var f=ctx(callbackfn,that,3),O=ES5Object(object),result=isMap||type==7||type==2?new(generic(this,Dict)):undefined,key,val,res;for(key in O)if(has(O,key)){val=O[key];res=f(val,key,object);if(type){if(isMap)result[key]=res;else if(res)switch(type){case 2:result[key]=val;break;case 3:return true;case 5:return val;case 6:return key;case 7:result[res[0]]=res[1]}else if(isEvery)return false}}return type==3||isEvery?isEvery:result}}function createDictReduce(isTurn){return function(object,mapfn,init){assertFunction(mapfn);var O=ES5Object(object),keys=getKeys(O),length=keys.length,i=0,memo,key,result;if(isTurn)memo=init==undefined?new(generic(this,Dict)):Object(init);else if(arguments.length<3){assert(length,REDUCE_ERROR);memo=O[keys[i++]]}else memo=Object(init);while(length>i)if(has(O,key=keys[i++])){result=mapfn(memo,O[key],key,object);if(isTurn){if(result===false)break}else memo=result}return memo}}var findKey=createDictMethod(6);function includes(object,el){return(el==el?keyOf(object,el):findKey(object,sameNaN))!==undefined}var dictMethods={keys:createDictIter(KEY),values:createDictIter(VALUE),entries:createDictIter(KEY+VALUE),forEach:createDictMethod(0),map:createDictMethod(1),filter:createDictMethod(2),some:createDictMethod(3),every:createDictMethod(4),find:createDictMethod(5),findKey:findKey,mapPairs:createDictMethod(7),reduce:createDictReduce(false),turn:createDictReduce(true),keyOf:keyOf,includes:includes,has:has,get:get,set:createDefiner(0),isDict:function(it){return isObject(it)&&getPrototypeOf(it)===Dict[PROTOTYPE]}};if(REFERENCE_GET)for(var key in dictMethods)!function(fn){function method(){for(var args=[this],i=0;i<arguments.length;)args.push(arguments[i++]);return invoke(fn,args)}fn[REFERENCE_GET]=function(){return method}}(dictMethods[key]);$define(GLOBAL+FORCED,{Dict:assignHidden(Dict,dictMethods)})}("Dict");!function(ENTRIES,FN){function $for(iterable,entries){if(!(this instanceof $for))return new $for(iterable,entries);this[ITER]=getIterator(iterable);this[ENTRIES]=!!entries}createIterator($for,"Wrapper",function(){return this[ITER].next()});var $forProto=$for[PROTOTYPE];setIterator($forProto,function(){return this[ITER]});function createChainIterator(next){function Iter(I,fn,that){this[ITER]=getIterator(I);this[ENTRIES]=I[ENTRIES];this[FN]=ctx(fn,that,I[ENTRIES]?2:1)}createIterator(Iter,"Chain",next,$forProto);setIterator(Iter[PROTOTYPE],returnThis);return Iter}var MapIter=createChainIterator(function(){var step=this[ITER].next();return step.done?step:iterResult(0,stepCall(this[FN],step.value,this[ENTRIES]))});var FilterIter=createChainIterator(function(){for(;;){var step=this[ITER].next();if(step.done||stepCall(this[FN],step.value,this[ENTRIES]))return step}});assignHidden($forProto,{of:function(fn,that){forOf(this,this[ENTRIES],fn,that)},array:function(fn,that){var result=[];forOf(fn!=undefined?this.map(fn,that):this,false,push,result);return result},filter:function(fn,that){return new FilterIter(this,fn,that)},map:function(fn,that){return new MapIter(this,fn,that)}});$for.isIterable=isIterable;$for.getIterator=getIterator;$define(GLOBAL+FORCED,{$for:$for})}("entries",safeSymbol("fn"));!function(_,toLocaleString){core._=path._=path._||{};$define(PROTO+FORCED,FUNCTION,{part:part,by:function(that){var fn=this,_=path._,holder=false,length=arguments.length,isThat=that===_,i=+!isThat,indent=i,it,args;if(isThat){it=fn;fn=call}else it=that;if(length<2)return ctx(fn,it,-1);args=Array(length-indent);while(length>i)if((args[i-indent]=arguments[i++])===_)holder=true;return partial(fn,args,length,holder,_,true,it)},only:function(numberArguments,that){var fn=assertFunction(this),n=toLength(numberArguments),isThat=arguments.length>1;return function(){var length=min(n,arguments.length),args=Array(length),i=0;while(length>i)args[i]=arguments[i++];return invoke(fn,args,isThat?that:this)}}});function tie(key){var that=this,bound={};return hidden(that,_,function(key){if(key===undefined||!(key in that))return toLocaleString.call(that);return has(bound,key)?bound[key]:bound[key]=ctx(that[key],that,-1)})[_](key)}hidden(path._,TO_STRING,function(){return _});hidden(ObjectProto,_,tie);DESC||hidden(ArrayProto,_,tie)}(DESC?uid("tie"):TO_LOCALE,ObjectProto[TO_LOCALE]);!function(){function define(target,mixin){var keys=ownKeys(ES5Object(mixin)),length=keys.length,i=0,key;while(length>i)defineProperty(target,key=keys[i++],getOwnDescriptor(mixin,key));return target}$define(STATIC+FORCED,OBJECT,{isObject:isObject,classof:classof,define:define,make:function(proto,mixin){return define(create(proto),mixin)}})}();$define(PROTO+FORCED,ARRAY,{turn:turn});!function(){function setArrayStatics(keys,length){$define(STATIC,ARRAY,turn.call(array(keys),function(memo,key){if(key in ArrayProto)memo[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")}();!function(){function NumberIterator(iterated){set(this,ITER,{l:toLength(iterated),i:0})}createIterator(NumberIterator,NUMBER,function(){var iter=this[ITER],i=iter.i++;return i<iter.l?iterResult(0,i):iterResult(1)});defineIterator(Number,NUMBER,function(){return new NumberIterator(this)});$define(PROTO+FORCED,NUMBER,{random:function(lim){var a=+this,b=lim==undefined?0:+lim,m=min(a,b);return random()*(max(a,b)-m)+m}});$define(PROTO+FORCED,NUMBER,turn.call(array("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,"+"acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc"),function(memo,key){var fn=Math[key];if(fn)memo[key]=function(){var args=[+this],i=0;while(arguments.length>i)args.push(arguments[i++]);return invoke(fn,args)}},{}))}();!function(){var escapeHTMLDict={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"},unescapeHTMLDict={},key;for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]]=key;$define(PROTO+FORCED,STRING,{escapeHTML:createReplacer(/[&<>"']/g,escapeHTMLDict),unescapeHTML:createReplacer(/&(?:amp|lt|gt|quot|apos);/g,unescapeHTMLDict)})}();!function(formatRegExp,flexioRegExp,locales,current,SECONDS,MINUTES,HOURS,MONTH,YEAR){function createFormat(prefix){return function(template,locale){var that=this,dict=locales[has(locales,locale)?locale:current];function get(unit){return that[prefix+unit]()}return String(template).replace(formatRegExp,function(part){switch(part){case"s":return get(SECONDS);case"ss":return lz(get(SECONDS));case"m":return get(MINUTES);case"mm":return lz(get(MINUTES));case"h":return get(HOURS);case"hh":return lz(get(HOURS));case"D":return get(DATE);case"DD":return lz(get(DATE));case"W":return dict[0][get("Day")];case"N":return get(MONTH)+1;case"NN":return lz(get(MONTH)+1);case"M":return dict[2][get(MONTH)];case"MM":return dict[1][get(MONTH)];case"Y":return get(YEAR);case"YY":return lz(get(YEAR)%100)}return part})}}function lz(num){return num>9?num:"0"+num}function addLocale(lang,locale){function split(index){return turn.call(array(locale.months),function(memo,it){memo.push(it.replace(flexioRegExp,"$"+index))})}locales[lang]=[array(locale.weekdays),split(1),split(2)];return core}$define(PROTO+FORCED,DATE,{format:createFormat("get"),formatUTC:createFormat("getUTC")});addLocale(current,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"});addLocale("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,"+"Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"});core.locale=function(locale){return has(locales,locale)?current=locale:current};core.addLocale=addLocale}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear")}(Function("return this"),false)},{}],117:[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})},{}],118:[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}})()},{}],119:[function(require,module,exports){(function(){"use strict";var Regex,NON_ASCII_WHITESPACES;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}NON_ASCII_WHITESPACES=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&NON_ASCII_WHITESPACES.indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch>=48&&ch<=57||ch===36||ch===95||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}})()},{}],120:[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":119}],121:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":118,"./code":119,"./keyword":120}],122:[function(require,module,exports){"use strict";exports.reservedVars={arguments:false,NaN:false};exports.ecmaIdentifiers={Array:false,Boolean:false,Date:false,decodeURI:false,decodeURIComponent:false,encodeURI:false,encodeURIComponent:false,Error:false,eval:false,EvalError:false,Function:false,hasOwnProperty:false,isFinite:false,isNaN:false,JSON:false,Map:false,Math:false,Number:false,Object:false,Proxy:false,Promise:false,parseInt:false,parseFloat:false,RangeError:false,ReferenceError:false,RegExp:false,Set:false,String:false,SyntaxError:false,TypeError:false,URIError:false,WeakMap:false,WeakSet:false};exports.newEcmaIdentifiers={Set:false,Map:false,WeakMap:false,WeakSet:false,Proxy:false,Promise:false,Reflect:false,Symbol:false,System:false};exports.browser={Audio:false,Blob:false,addEventListener:false,applicationCache:false,atob:false,blur:false,btoa:false,cancelAnimationFrame:false,CanvasGradient:false,CanvasPattern:false,CanvasRenderingContext2D:false,CSS:false,clearInterval:false,clearTimeout:false,close:false,closed:false,CustomEvent:false,DOMParser:false,defaultStatus:false,Document:false,document:false,Element:false,ElementTimeControl:false,Event:false,event:false,FileReader:false,FormData:false,focus:false,frames:false,getComputedStyle:false,HTMLElement:false,HTMLAnchorElement:false,HTMLBaseElement:false,HTMLBlockquoteElement:false,HTMLBodyElement:false,HTMLBRElement:false,HTMLButtonElement:false,HTMLCanvasElement:false,HTMLDirectoryElement:false,HTMLDivElement:false,HTMLDListElement:false,HTMLFieldSetElement:false,HTMLFontElement:false,HTMLFormElement:false,HTMLFrameElement:false,HTMLFrameSetElement:false,HTMLHeadElement:false,HTMLHeadingElement:false,HTMLHRElement:false,HTMLHtmlElement:false,HTMLIFrameElement:false,HTMLImageElement:false,HTMLInputElement:false,HTMLIsIndexElement:false,HTMLLabelElement:false,HTMLLayerElement:false,HTMLLegendElement:false,HTMLLIElement:false,HTMLLinkElement:false,HTMLMapElement:false,HTMLMenuElement:false,HTMLMetaElement:false,HTMLModElement:false,HTMLObjectElement:false,HTMLOListElement:false,HTMLOptGroupElement:false,HTMLOptionElement:false,HTMLParagraphElement:false,HTMLParamElement:false,HTMLPreElement:false,HTMLQuoteElement:false,HTMLScriptElement:false,HTMLSelectElement:false,HTMLStyleElement:false,HTMLTableCaptionElement:false,HTMLTableCellElement:false,HTMLTableColElement:false,HTMLTableElement:false,HTMLTableRowElement:false,HTMLTableSectionElement:false,HTMLTextAreaElement:false,HTMLTitleElement:false,HTMLUListElement:false,HTMLVideoElement:false,history:false,Image:false,Intl:false,length:false,localStorage:false,location:false,matchMedia:false,MessageChannel:false,MessageEvent:false,MessagePort:false,MouseEvent:false,moveBy:false,moveTo:false,MutationObserver:false,name:false,Node:false,NodeFilter:false,NodeList:false,navigator:false,onbeforeunload:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:false,openDatabase:false,opener:false,Option:false,parent:false,print:false,requestAnimationFrame:false,removeEventListener:false,resizeBy:false,resizeTo:false,screen:false,scroll:false,scrollBy:false,scrollTo:false,sessionStorage:false,setInterval:false,setTimeout:false,SharedWorker:false,status:false,SVGAElement:false,SVGAltGlyphDefElement:false,SVGAltGlyphElement:false,SVGAltGlyphItemElement:false,SVGAngle:false,SVGAnimateColorElement:false,SVGAnimateElement:false,SVGAnimateMotionElement:false,SVGAnimateTransformElement:false,SVGAnimatedAngle:false,SVGAnimatedBoolean:false,SVGAnimatedEnumeration:false,SVGAnimatedInteger:false,SVGAnimatedLength:false,SVGAnimatedLengthList:false,SVGAnimatedNumber:false,SVGAnimatedNumberList:false,SVGAnimatedPathData:false,SVGAnimatedPoints:false,SVGAnimatedPreserveAspectRatio:false,SVGAnimatedRect:false,SVGAnimatedString:false,SVGAnimatedTransformList:false,SVGAnimationElement:false,SVGCSSRule:false,SVGCircleElement:false,SVGClipPathElement:false,SVGColor:false,SVGColorProfileElement:false,SVGColorProfileRule:false,SVGComponentTransferFunctionElement:false,SVGCursorElement:false,SVGDefsElement:false,SVGDescElement:false,SVGDocument:false,SVGElement:false,SVGElementInstance:false,SVGElementInstanceList:false,SVGEllipseElement:false,SVGExternalResourcesRequired:false,SVGFEBlendElement:false,SVGFEColorMatrixElement:false,SVGFEComponentTransferElement:false,SVGFECompositeElement:false,SVGFEConvolveMatrixElement:false,SVGFEDiffuseLightingElement:false,SVGFEDisplacementMapElement:false,SVGFEDistantLightElement:false,SVGFEFloodElement:false,SVGFEFuncAElement:false,SVGFEFuncBElement:false,SVGFEFuncGElement:false,SVGFEFuncRElement:false,SVGFEGaussianBlurElement:false,SVGFEImageElement:false,SVGFEMergeElement:false,SVGFEMergeNodeElement:false,SVGFEMorphologyElement:false,SVGFEOffsetElement:false,SVGFEPointLightElement:false,SVGFESpecularLightingElement:false,SVGFESpotLightElement:false,SVGFETileElement:false,SVGFETurbulenceElement:false,SVGFilterElement:false,SVGFilterPrimitiveStandardAttributes:false,SVGFitToViewBox:false,SVGFontElement:false,SVGFontFaceElement:false,SVGFontFaceFormatElement:false,SVGFontFaceNameElement:false,SVGFontFaceSrcElement:false,SVGFontFaceUriElement:false,SVGForeignObjectElement:false,SVGGElement:false,SVGGlyphElement:false,SVGGlyphRefElement:false,SVGGradientElement:false,SVGHKernElement:false,SVGICCColor:false,SVGImageElement:false,SVGLangSpace:false,SVGLength:false,SVGLengthList:false,SVGLineElement:false,SVGLinearGradientElement:false,SVGLocatable:false,SVGMPathElement:false,SVGMarkerElement:false,SVGMaskElement:false,SVGMatrix:false,SVGMetadataElement:false,SVGMissingGlyphElement:false,SVGNumber:false,SVGNumberList:false,SVGPaint:false,SVGPathElement:false,SVGPathSeg:false,SVGPathSegArcAbs:false,SVGPathSegArcRel:false,SVGPathSegClosePath:false,SVGPathSegCurvetoCubicAbs:false,SVGPathSegCurvetoCubicRel:false,SVGPathSegCurvetoCubicSmoothAbs:false,SVGPathSegCurvetoCubicSmoothRel:false,SVGPathSegCurvetoQuadraticAbs:false,SVGPathSegCurvetoQuadraticRel:false,SVGPathSegCurvetoQuadraticSmoothAbs:false,SVGPathSegCurvetoQuadraticSmoothRel:false,SVGPathSegLinetoAbs:false,SVGPathSegLinetoHorizontalAbs:false,SVGPathSegLinetoHorizontalRel:false,SVGPathSegLinetoRel:false,SVGPathSegLinetoVerticalAbs:false,SVGPathSegLinetoVerticalRel:false,SVGPathSegList:false,SVGPathSegMovetoAbs:false,SVGPathSegMovetoRel:false,SVGPatternElement:false,SVGPoint:false,SVGPointList:false,SVGPolygonElement:false,SVGPolylineElement:false,SVGPreserveAspectRatio:false,SVGRadialGradientElement:false,SVGRect:false,SVGRectElement:false,SVGRenderingIntent:false,SVGSVGElement:false,SVGScriptElement:false,SVGSetElement:false,SVGStopElement:false,SVGStringList:false,SVGStylable:false,SVGStyleElement:false,SVGSwitchElement:false,SVGSymbolElement:false,SVGTRefElement:false,SVGTSpanElement:false,SVGTests:false,SVGTextContentElement:false,SVGTextElement:false,SVGTextPathElement:false,SVGTextPositioningElement:false,SVGTitleElement:false,SVGTransform:false,SVGTransformList:false,SVGTransformable:false,SVGURIReference:false,SVGUnitTypes:false,SVGUseElement:false,SVGVKernElement:false,SVGViewElement:false,SVGViewSpec:false,SVGZoomAndPan:false,TextDecoder:false,TextEncoder:false,TimeEvent:false,top:false,URL:false,WebGLActiveInfo:false,WebGLBuffer:false,WebGLContextEvent:false,WebGLFramebuffer:false,WebGLProgram:false,WebGLRenderbuffer:false,WebGLRenderingContext:false,WebGLShader:false,WebGLShaderPrecisionFormat:false,WebGLTexture:false,WebGLUniformLocation:false,WebSocket:false,window:false,Worker:false,XDomainRequest:false,XMLHttpRequest:false,XMLSerializer:false,XPathEvaluator:false,XPathException:false,XPathExpression:false,XPathNamespace:false,XPathNSResolver:false,XPathResult:false};exports.devel={alert:false,confirm:false,console:false,Debug:false,opera:false,prompt:false};exports.worker={importScripts:true,postMessage:true,self:true,FileReaderSync:true};exports.nonstandard={escape:false,unescape:false};exports.couch={require:false,respond:false,getRow:false,emit:false,send:false,start:false,sum:false,log:false,exports:false,module:false,provides:false};exports.node={__filename:false,__dirname:false,GLOBAL:false,global:false,module:false,require:false,Buffer:true,console:true,exports:true,process:true,setTimeout:true,clearTimeout:true,setInterval:true,clearInterval:true,setImmediate:true,clearImmediate:true};exports.browserify={__filename:false,__dirname:false,global:false,module:false,require:false,Buffer:true,exports:true,process:true};exports.phantom={phantom:true,require:true,WebPage:true,console:true,exports:true};exports.qunit={asyncTest:false,deepEqual:false,equal:false,expect:false,module:false,notDeepEqual:false,notEqual:false,notPropEqual:false,notStrictEqual:false,ok:false,propEqual:false,QUnit:false,raises:false,start:false,stop:false,strictEqual:false,test:false,"throws":false};exports.rhino={defineClass:false,deserialize:false,gc:false,help:false,importClass:false,importPackage:false,java:false,load:false,loadClass:false,Packages:false,print:false,quit:false,readFile:false,readUrl:false,runCommand:false,seal:false,serialize:false,spawn:false,sync:false,toint32:false,version:false};exports.shelljs={target:false,echo:false,exit:false,cd:false,pwd:false,ls:false,find:false,cp:false,rm:false,mv:false,mkdir:false,test:false,cat:false,sed:false,grep:false,which:false,dirs:false,pushd:false,popd:false,env:false,exec:false,chmod:false,config:false,error:false,tempdir:false};exports.typed={ArrayBuffer:false,ArrayBufferView:false,DataView:false,Float32Array:false,Float64Array:false,Int16Array:false,Int32Array:false,Int8Array:false,Uint16Array:false,Uint32Array:false,Uint8Array:false,Uint8ClampedArray:false};exports.wsh={ActiveXObject:true,Enumerator:true,GetObject:true,ScriptEngine:true,ScriptEngineBuildVersion:true,ScriptEngineMajorVersion:true,ScriptEngineMinorVersion:true,VBArray:true,WSH:true,WScript:true,XDomainRequest:true};exports.dojo={dojo:false,dijit:false,dojox:false,define:false,require:false};exports.jquery={$:false,jQuery:false};exports.mootools={$:false,$$:false,Asset:false,Browser:false,Chain:false,Class:false,Color:false,Cookie:false,Core:false,Document:false,DomReady:false,DOMEvent:false,DOMReady:false,Drag:false,Element:false,Elements:false,Event:false,Events:false,Fx:false,Group:false,Hash:false,HtmlTable:false,IFrame:false,IframeShim:false,InputValidator:false,instanceOf:false,Keyboard:false,Locale:false,Mask:false,MooTools:false,Native:false,Options:false,OverText:false,Request:false,Scroller:false,Slick:false,Slider:false,Sortables:false,Spinner:false,Swiff:false,Tips:false,Type:false,typeOf:false,URI:false,Window:false};exports.prototypejs={$:false,$$:false,$A:false,$F:false,$H:false,$R:false,$break:false,$continue:false,$w:false,Abstract:false,Ajax:false,Class:false,Enumerable:false,Element:false,Event:false,Field:false,Form:false,Hash:false,Insertion:false,ObjectRange:false,PeriodicalExecuter:false,Position:false,Prototype:false,Selector:false,Template:false,Toggle:false,Try:false,Autocompleter:false,Builder:false,Control:false,Draggable:false,Draggables:false,Droppables:false,Effect:false,Sortable:false,SortableObserver:false,Sound:false,Scriptaculous:false};exports.yui={YUI:false,Y:false,YUI_config:false};exports.mocha={describe:false,it:false,before:false,after:false,beforeEach:false,afterEach:false,suite:false,test:false,setup:false,teardown:false};exports.jasmine={jasmine:false,describe:false,it:false,xit:false,beforeEach:false,afterEach:false,setFixtures:false,loadFixtures:false,spyOn:false,expect:false,runs:false,waitsFor:false,waits:false}},{}],123:[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:{})},{}],124:[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)},{}],125:[function(require,module,exports){var assert=require("assert");var types=require("recast").types;var isArray=types.builtInTypes.array;var b=types.builders;var n=types.namedTypes;var leap=require("./leap");var meta=require("./meta");var util=require("./util");var runtimeKeysMethod=util.runtimeProperty("keys");var hasOwn=Object.prototype.hasOwnProperty;function Emitter(contextId){assert.ok(this instanceof Emitter);n.Identifier.assert(contextId);Object.defineProperties(this,{contextId:{value:contextId},listing:{value:[]},marked:{value:[true]},finalLoc:{value:loc()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new leap.LeapManager(this)}})}var Ep=Emitter.prototype;exports.Emitter=Emitter;function loc(){return b.literal(-1)}Ep.mark=function(loc){n.Literal.assert(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};Ep.emit=function(node){if(n.Expression.check(node))node=b.expressionStatement(node);n.Statement.assert(node);this.listing.push(node)};Ep.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Ep.assign=function(lhs,rhs){return b.expressionStatement(b.assignmentExpression("=",lhs,rhs))};Ep.contextProperty=function(name,computed){return b.memberExpression(this.contextId,computed?b.literal(name):b.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Ep.isVolatileContextProperty=function(expr){if(n.MemberExpression.check(expr)){if(expr.computed){return true}if(n.Identifier.check(expr.object)&&n.Identifier.check(expr.property)&&expr.object.name===this.contextId.name&&hasOwn.call(volatileContextPropertyNames,expr.property.name)){return true}}return false};Ep.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Ep.setReturnValue=function(valuePath){n.Expression.assert(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Ep.clearPendingException=function(tryLoc,assignee){n.Literal.assert(tryLoc);var catchCall=b.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Ep.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(b.breakStatement())};Ep.jumpIf=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);this.emit(b.ifStatement(test,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};Ep.jumpIfNot=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);var negatedTest;if(n.UnaryExpression.check(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=b.unaryExpression("!",test)}this.emit(b.ifStatement(negatedTest,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};var nextTempId=0;Ep.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Ep.getContextFunction=function(id){return b.functionExpression(id||null,[this.contextId],b.blockStatement([this.getDispatchLoop()]),false,false)};Ep.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(b.switchCase(b.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(b.switchCase(this.finalLoc,[]),b.switchCase(b.literal("end"),[b.returnStatement(b.callExpression(this.contextProperty("stop"),[]))]));return b.whileStatement(b.literal(1),b.switchStatement(b.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return n.BreakStatement.check(stmt)||n.ContinueStatement.check(stmt)||n.ReturnStatement.check(stmt)||n.ThrowStatement.check(stmt)}Ep.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return b.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 b.arrayExpression(triple)}))};Ep.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.assert(node);if(n.Statement.check(node))return self.explodeStatement(path);if(n.Expression.check(node))return self.explodeExpression(path,ignoreResult);if(n.Declaration.check(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))}Ep.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;n.Statement.assert(stmt);if(labelId){n.Identifier.assert(labelId)}else{labelId=null}if(n.BlockStatement.check(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}switch(stmt.type){case"ExpressionStatement":self.explodeExpression(path.get("expression"),true);break;case"LabeledStatement":self.explodeStatement(path.get("body"),stmt.label);break;case"WhileStatement":var before=loc();var after=loc();self.mark(before);self.jumpIfNot(self.explodeExpression(path.get("test")),after);self.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(before);self.mark(after);break;case"DoWhileStatement":var first=loc();var test=loc();var after=loc();self.mark(first);self.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){self.explode(path.get("body"))});self.mark(test);self.jumpIf(self.explodeExpression(path.get("test")),first);self.mark(after);break;case"ForStatement":var head=loc();var update=loc();var after=loc();if(stmt.init){self.explode(path.get("init"),true)}self.mark(head);if(stmt.test){self.jumpIfNot(self.explodeExpression(path.get("test")),after)}else{}self.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){self.explodeStatement(path.get("body"))});self.mark(update);if(stmt.update){self.explode(path.get("update"),true)}self.jump(head);self.mark(after);break;case"ForInStatement":n.Identifier.assert(stmt.left);var head=loc();var after=loc();var keyIterNextFn=self.makeTempVar();self.emitAssign(keyIterNextFn,b.callExpression(runtimeKeysMethod,[self.explodeExpression(path.get("right"))]));self.mark(head);var keyInfoTmpVar=self.makeTempVar();self.jumpIf(b.memberExpression(b.assignmentExpression("=",keyInfoTmpVar,b.callExpression(keyIterNextFn,[])),b.identifier("done"),false),after);self.emitAssign(stmt.left,b.memberExpression(keyInfoTmpVar,b.identifier("value"),false));self.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(head);self.mark(after);break;case"BreakStatement":self.emitAbruptCompletion({type:"break",target:self.leapManager.getBreakLoc(stmt.label)});break;case"ContinueStatement":self.emitAbruptCompletion({type:"continue",target:self.leapManager.getContinueLoc(stmt.label)});break;case"SwitchStatement":var disc=self.emitAssign(self.makeTempVar(),self.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];n.SwitchCase.assert(c);if(c.test){condition=b.conditionalExpression(b.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}self.jump(self.explodeExpression(new types.NodePath(condition,path,"discriminant")));self.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var c=casePath.value; var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});self.mark(after);if(defaultLoc.value===-1){self.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}break;case"IfStatement":var elseLoc=stmt.alternate&&loc();var after=loc();self.jumpIfNot(self.explodeExpression(path.get("test")),elseLoc||after);self.explodeStatement(path.get("consequent"));if(elseLoc){self.jump(after);self.mark(elseLoc);self.explodeStatement(path.get("alternate"))}self.mark(after);break;case"ReturnStatement":self.emitAbruptCompletion({type:"return",value:self.explodeExpression(path.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var after=loc();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(self.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);self.tryEntries.push(tryEntry);self.updateContextPrevLoc(tryEntry.firstLoc);self.leapManager.withEntry(tryEntry,function(){self.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){self.jump(finallyLoc)}else{self.jump(after)}self.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=self.makeTempVar();self.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;n.CatchClause.assert(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(util.isReference(path,catchParamName)&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)},visitFunction:function(path){if(path.scope.declares(catchParamName)){return false}this.traverse(path)}});self.leapManager.withEntry(catchEntry,function(){self.explodeStatement(bodyPath)})}if(finallyLoc){self.updateContextPrevLoc(self.mark(finallyLoc));self.leapManager.withEntry(finallyEntry,function(){self.explodeStatement(path.get("finalizer"))});self.emit(b.callExpression(self.contextProperty("finish"),[finallyEntry.firstLoc]))}});self.mark(after);break;case"ThrowStatement":self.emit(b.throwStatement(self.explodeExpression(path.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Ep.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=[b.literal(record.type)];if(record.type==="break"||record.type==="continue"){n.Literal.assert(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){n.Expression.assert(record.value);abruptArgs[1]=record.value}}this.emit(b.returnStatement(b.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!hasOwn.call(record,"target")}if(type==="break"||type==="continue"){return!hasOwn.call(record,"value")&&n.Literal.check(record.target)}if(type==="return"||type==="throw"){return hasOwn.call(record,"value")&&!hasOwn.call(record,"target")}return false}Ep.getUnmarkedCurrentLoc=function(){return b.literal(this.listing.length)};Ep.updateContextPrevLoc=function(loc){if(loc){n.Literal.assert(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)};Ep.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){n.Expression.assert(expr)}else{return expr}var self=this;var result;function finish(expr){n.Expression.assert(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}switch(expr.type){case"MemberExpression":return finish(b.memberExpression(self.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed));case"CallExpression":var oldCalleePath=path.get("callee");var newCallee=self.explodeExpression(oldCalleePath);if(!n.MemberExpression.check(oldCalleePath.node)&&n.MemberExpression.check(newCallee)){newCallee=b.sequenceExpression([b.literal(0),newCallee])}return finish(b.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"NewExpression":return finish(b.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"ObjectExpression":return finish(b.objectExpression(path.get("properties").map(function(propPath){return b.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})));case"ArrayExpression":return finish(b.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})));case"SequenceExpression":var lastIndex=expr.expressions.length-1;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result;case"LogicalExpression":var after=loc();if(!ignoreResult){result=self.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){self.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");self.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);self.mark(after);return result;case"ConditionalExpression":var elseLoc=loc();var after=loc();var test=self.explodeExpression(path.get("test"));self.jumpIfNot(test,elseLoc);if(!ignoreResult){result=self.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);self.jump(after);self.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);self.mark(after);return result;case"UnaryExpression":return finish(b.unaryExpression(expr.operator,self.explodeExpression(path.get("argument")),!!expr.prefix));case"BinaryExpression":return finish(b.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))));case"AssignmentExpression":return finish(b.assignmentExpression(expr.operator,self.explodeExpression(path.get("left")),self.explodeExpression(path.get("right"))));case"UpdateExpression":return finish(b.updateExpression(expr.operator,self.explodeExpression(path.get("argument")),expr.prefix));case"YieldExpression":var after=loc();var arg=expr.argument&&self.explodeExpression(path.get("argument"));if(arg&&expr.delegate){var result=self.makeTempVar();self.emit(b.returnStatement(b.callExpression(self.contextProperty("delegateYield"),[arg,b.literal(result.property.name),after])));self.mark(after);return result}self.emitAssign(self.contextProperty("next"),after);self.emit(b.returnStatement(arg||null));self.mark(after);return self.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"./leap":127,"./meta":128,"./util":129,assert:91,recast:156}],126:[function(require,module,exports){var assert=require("assert");var types=require("recast").types;var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);n.Function.assert(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){n.VariableDeclaration.assert(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(b.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 b.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return b.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(n.VariableDeclaration.check(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(n.VariableDeclaration.check(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 parentNode=path.parent.node;var assignment=b.expressionStatement(b.assignmentExpression("=",node.id,b.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(n.BlockStatement.check(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(path){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(n.Identifier.check(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!hasOwn.call(paramNames,name)){declarations.push(b.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return b.variableDeclaration("var",declarations)}},{assert:91,recast:156}],127:[function(require,module,exports){var assert=require("assert");var types=require("recast").types;var n=types.namedTypes;var b=types.builders;var inherits=require("util").inherits;var hasOwn=Object.prototype.hasOwnProperty;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);n.Literal.assert(returnLoc);Object.defineProperties(this,{returnLoc:{value:returnLoc}})}inherits(FunctionEntry,Entry);exports.FunctionEntry=FunctionEntry;function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Literal.assert(continueLoc);if(label){n.Identifier.assert(label)}else{label=null}Object.defineProperties(this,{breakLoc:{value:breakLoc},continueLoc:{value:continueLoc},label:{value:label}})}inherits(LoopEntry,Entry);exports.LoopEntry=LoopEntry;function SwitchEntry(breakLoc){Entry.call(this);n.Literal.assert(breakLoc);Object.defineProperties(this,{breakLoc:{value:breakLoc}})}inherits(SwitchEntry,Entry);exports.SwitchEntry=SwitchEntry;function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);n.Literal.assert(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);Object.defineProperties(this,{firstLoc:{value:firstLoc},catchEntry:{value:catchEntry},finallyEntry:{value:finallyEntry}})}inherits(TryEntry,Entry);exports.TryEntry=TryEntry;function CatchEntry(firstLoc,paramId){Entry.call(this);n.Literal.assert(firstLoc);n.Identifier.assert(paramId);Object.defineProperties(this,{firstLoc:{value:firstLoc},paramId:{value:paramId}})}inherits(CatchEntry,Entry);exports.CatchEntry=CatchEntry;function FinallyEntry(firstLoc){Entry.call(this);n.Literal.assert(firstLoc);Object.defineProperties(this,{firstLoc:{value:firstLoc}})}inherits(FinallyEntry,Entry);exports.FinallyEntry=FinallyEntry;function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);Object.defineProperties(this,{emitter:{value:emitter},entryStack:{value:[new FunctionEntry(emitter.finalLoc)]}})}var LMp=LeapManager.prototype;exports.LeapManager=LeapManager;LMp.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)}};LMp._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};LMp.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LMp.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"./emit":125,assert:91,recast:156,util:115}],128:[function(require,module,exports){var assert=require("assert");var m=require("private").makeAccessor();var types=require("recast").types;var isArray=types.builtInTypes.array;var n=types.namedTypes;var hasOwn=Object.prototype.hasOwnProperty;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.assert(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.assert(node);var meta=m(node);if(hasOwn.call(meta,propertyName))return meta[propertyName];if(hasOwn.call(opaqueTypes,node.type))return meta[propertyName]=false;if(hasOwn.call(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(hasOwn.call(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:91,"private":124,recast:156}],129:[function(require,module,exports){var assert=require("assert");var types=require("recast").types;var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.defaults=function(obj){var len=arguments.length;var extension;for(var i=1;i<len;++i){if(extension=arguments[i]){for(var key in extension){if(hasOwn.call(extension,key)&&!hasOwn.call(obj,key)){obj[key]=extension[key]}}}}return obj};exports.runtimeProperty=function(name){return b.memberExpression(b.identifier("regeneratorRuntime"),b.identifier(name),false)};exports.isReference=function(path,name){var node=path.value;if(!n.Identifier.check(node)){return false}if(name&&node.name!==name){return false}var parent=path.parent.value;switch(parent.type){case"VariableDeclarator":return path.name==="init";case"MemberExpression":return path.name==="object"||parent.computed&&path.name==="property";case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":if(path.name==="id"){return false}if(parent.params===path.parentPath&&parent.params[path.name]===node){return false}return true;case"ClassDeclaration":case"ClassExpression":return path.name!=="id";case"CatchClause":return path.name!=="param";case"Property":case"MethodDefinition":return path.name!=="key";case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return false;default:return true}}},{assert:91,recast:156}],130:[function(require,module,exports){var assert=require("assert");var fs=require("fs");var recast=require("recast");var types=recast.types;var n=types.namedTypes;var b=types.builders;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var NodePath=types.NodePath;var hoist=require("./hoist").hoist;var Emitter=require("./emit").Emitter;var runtimeProperty=require("./util").runtimeProperty;var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");var runtimeValuesMethod=runtimeProperty("values");var runtimeAsyncMethod=runtimeProperty("async");exports.transform=function transform(node,options){options=options||{};node=recast.visit(node,visitor);if(options.includeRuntime===true||options.includeRuntime==="if used"&&visitor.wasChangeReported()){injectRuntime(n.File.check(node)?node.program:node)}options.madeChanges=visitor.wasChangeReported();return node};function injectRuntime(program){n.Program.assert(program);var runtimePath=require("..").runtime.path;var runtime=fs.readFileSync(runtimePath,"utf8");var runtimeBody=recast.parse(runtime,{sourceFileName:runtimePath}).program.body;var body=program.body;body.unshift.apply(body,runtimeBody)}var visitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){this.traverse(path);var node=path.value;if(!node.generator&&!node.async){return}this.reportChanged();node.generator=false;if(node.expression){node.expression=false;node.body=b.blockStatement([b.returnStatement(node.body)])}if(node.async){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=path.scope.parent.declareTemporary("callee$"));var innerFnId=b.identifier(node.id.name+"$");var contextId=path.scope.declareTemporary("context$");var argsId=path.scope.declareTemporary("args$");var shouldAliasArguments=renameArguments(path,argsId);var vars=hoist(path);if(shouldAliasArguments){vars=vars||b.variableDeclaration("var",[]);vars.declarations.push(b.variableDeclarator(argsId,b.identifier("arguments")))}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?b.literal(null):outerFnId,b.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=b.callExpression(node.async?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(b.returnStatement(wrapCall));node.body=b.blockStatement(outerBody);if(node.async){node.async=false;return}if(n.FunctionDeclaration.check(node)){var pp=path.parent;while(pp&&!(n.BlockStatement.check(pp.value)||n.Program.check(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=b.variableDeclaration("var",[b.variableDeclarator(node.id,b.callExpression(runtimeMarkMethod,[node]))]);if(node.comments){varDecl.comments=node.comments;node.comments=null}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{n.FunctionExpression.assert(node);return b.callExpression(runtimeMarkMethod,[node])}},visitForOfStatement:function(path){this.traverse(path);var node=path.value;var tempIterId=path.scope.declareTemporary("t$");var tempIterDecl=b.variableDeclarator(tempIterId,b.callExpression(runtimeValuesMethod,[node.right]));var tempInfoId=path.scope.declareTemporary("t$");var tempInfoDecl=b.variableDeclarator(tempInfoId,null);var init=node.left;var loopId;if(n.VariableDeclaration.check(init)){loopId=init.declarations[0].id;init.declarations.push(tempIterDecl,tempInfoDecl)}else{loopId=init;init=b.variableDeclaration("var",[tempIterDecl,tempInfoDecl])}n.Identifier.assert(loopId);var loopIdAssignExprStmt=b.expressionStatement(b.assignmentExpression("=",loopId,b.memberExpression(tempInfoId,b.identifier("value"),false)));if(n.BlockStatement.check(node.body)){node.body.body.unshift(loopIdAssignExprStmt)}else{node.body=b.blockStatement([loopIdAssignExprStmt,node.body])}return b.forStatement(init,b.unaryExpression("!",b.memberExpression(b.assignmentExpression("=",tempInfoId,b.callExpression(b.memberExpression(tempIterId,b.identifier("next"),false),[])),b.identifier("done"),false)),null,node.body)}});function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;n.Statement.assert(value);if(n.ExpressionStatement.check(value)&&n.Literal.check(value.expression)&&value.expression.value==="use strict"){return true}if(n.VariableDeclaration.check(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(n.CallExpression.check(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}function renameArguments(funcPath,argsId){assert.ok(funcPath instanceof types.NodePath);var func=funcPath.value;var didReplaceArguments=false;var hasImplicitArguments=false;recast.visit(funcPath,{visitFunction:function(path){if(path.value===func){hasImplicitArguments=!path.scope.lookup("arguments");this.traverse(path)}else{return false}},visitIdentifier:function(path){if(path.value.name==="arguments"){var isMemberProperty=n.MemberExpression.check(path.parent.node)&&path.name==="property"&&!path.parent.node.computed;if(!isMemberProperty){path.replace(argsId);didReplaceArguments=true;return false}}this.traverse(path)}});return didReplaceArguments&&hasImplicitArguments}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){return false},visitAwaitExpression:function(path){return b.yieldExpression(path.value.argument,false)}})},{"..":131,"./emit":125,"./hoist":126,"./util":129,assert:91,fs:90,recast:156}],131:[function(require,module,exports){(function(__dirname){var assert=require("assert");var path=require("path");var fs=require("fs");var through=require("through");var transform=require("./lib/visit").transform;var utils=require("./lib/util");var recast=require("recast");var types=recast.types;var genOrAsyncFunExp=/\bfunction\s*\*|\basync\b/;var blockBindingExp=/\b(let|const)\s+/;function exports(file,options){var data=[];return through(write,end);function write(buf){data.push(buf)}function end(){this.queue(compile(data.join(""),options).code);this.queue(null)}}module.exports=exports;function runtime(){require("./runtime")}exports.runtime=runtime;runtime.path=path.join(__dirname,"runtime.js");function compile(source,options){options=normalizeOptions(options);if(!genOrAsyncFunExp.test(source)){return{code:(options.includeRuntime===true?fs.readFileSync(runtime.path,"utf-8")+"\n":"")+source}}var recastOptions=getRecastOptions(options);var ast=recast.parse(source,recastOptions);var path=new types.NodePath(ast);var programPath=path.get("program");if(shouldVarify(source,options)){varifyAst(programPath.node)}transform(programPath,options);return recast.print(path,recastOptions)}function normalizeOptions(options){options=utils.defaults(options||{},{includeRuntime:false,supportBlockBinding:true});if(!options.esprima){options.esprima=require("esprima-fb")}assert.ok(/harmony/.test(options.esprima.version),"Bad esprima version: "+options.esprima.version);return options}function getRecastOptions(options){var recastOptions={range:true};function copy(name){if(name in options){recastOptions[name]=options[name]}}copy("esprima");copy("sourceFileName");copy("sourceMapName");copy("inputSourceMap");copy("sourceRoot");return recastOptions}function shouldVarify(source,options){var supportBlockBinding=!!options.supportBlockBinding;if(supportBlockBinding){if(!blockBindingExp.test(source)){supportBlockBinding=false}}return supportBlockBinding}function varify(source,options){var recastOptions=getRecastOptions(normalizeOptions(options));var ast=recast.parse(source,recastOptions);varifyAst(ast.program);return recast.print(ast,recastOptions).code}function varifyAst(ast){types.namedTypes.Program.assert(ast);var defsResult=require("defs")(ast,{ast:true,disallowUnknownReferences:false,disallowDuplicated:false,disallowVars:false,loopClosures:"iife"});if(defsResult.errors){throw new Error(defsResult.errors.join("\n"))}return ast}exports.varify=varify;exports.compile=compile;exports.transform=transform}).call(this,"/node_modules/regenerator")},{"./lib/util":129,"./lib/visit":130,"./runtime":158,assert:91,defs:132,"esprima-fb":146,fs:90,path:99,recast:156,through:157}],132:[function(require,module,exports){"use strict";var assert=require("assert");var is=require("simple-is");var fmt=require("simple-fmt");var stringmap=require("stringmap");var stringset=require("stringset");var alter=require("alter");var traverse=require("ast-traverse");var breakable=require("breakable");var Scope=require("./scope");var error=require("./error");var getline=error.getline;var options=require("./options");var Stats=require("./stats");var jshint_vars=require("./jshint_globals/vars.js");function isConstLet(kind){return is.someof(kind,["const","let"])}function isVarConstLet(kind){return is.someof(kind,["var","const","let"])}function isNonFunctionBlock(node){return node.type==="BlockStatement"&&is.noneof(node.$parent.type,["FunctionDeclaration","FunctionExpression"])}function isForWithConstLet(node){return node.type==="ForStatement"&&node.init&&node.init.type==="VariableDeclaration"&&isConstLet(node.init.kind)}function isForInOfWithConstLet(node){return isForInOf(node)&&node.left.type==="VariableDeclaration"&&isConstLet(node.left.kind)}function isForInOf(node){return is.someof(node.type,["ForInStatement","ForOfStatement"])}function isFunction(node){return is.someof(node.type,["FunctionDeclaration","FunctionExpression"])}function isLoop(node){return is.someof(node.type,["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"])}function isReference(node){var parent=node.$parent;return node.$refToScope||node.type==="Identifier"&&!(parent.type==="VariableDeclarator"&&parent.id===node)&&!(parent.type==="MemberExpression"&&parent.computed===false&&parent.property===node)&&!(parent.type==="Property"&&parent.key===node)&&!(parent.type==="LabeledStatement"&&parent.label===node)&&!(parent.type==="CatchClause"&&parent.param===node)&&!(isFunction(parent)&&parent.id===node)&&!(isFunction(parent)&&is.someof(node,parent.params))&&true}function isLvalue(node){return isReference(node)&&(node.$parent.type==="AssignmentExpression"&&node.$parent.left===node||node.$parent.type==="UpdateExpression"&&node.$parent.argument===node)}function createScopes(node,parent){assert(!node.$scope);node.$parent=parent;node.$scope=node.$parent?node.$parent.$scope:null;if(node.type==="Program"){node.$scope=new Scope({kind:"hoist",node:node,parent:null})}else if(isFunction(node)){node.$scope=new Scope({kind:"hoist",node:node,parent:node.$parent.$scope});if(node.id){assert(node.id.type==="Identifier");if(node.type==="FunctionDeclaration"){node.$parent.$scope.add(node.id.name,"fun",node.id,null)}else if(node.type==="FunctionExpression"){node.$scope.add(node.id.name,"fun",node.id,null)}else{assert(false)}}node.params.forEach(function(param){node.$scope.add(param.name,"param",param,null)})}else if(node.type==="VariableDeclaration"){assert(isVarConstLet(node.kind));node.declarations.forEach(function(declarator){assert(declarator.type==="VariableDeclarator");var name=declarator.id.name;if(options.disallowVars&&node.kind==="var"){error(getline(declarator),"var {0} is not allowed (use let or const)",name)}node.$scope.add(name,node.kind,declarator.id,declarator.range[1])})}else if(isForWithConstLet(node)||isForInOfWithConstLet(node)){node.$scope=new Scope({kind:"block",node:node,parent:node.$parent.$scope})}else if(isNonFunctionBlock(node)){node.$scope=new Scope({kind:"block",node:node,parent:node.$parent.$scope})}else if(node.type==="CatchClause"){var identifier=node.param;node.$scope=new Scope({kind:"catch-block",node:node,parent:node.$parent.$scope});node.$scope.add(identifier.name,"caught",identifier,null);node.$scope.closestHoistScope().markPropagates(identifier.name)}}function createTopScope(programScope,environments,globals){function inject(obj){for(var name in obj){var writeable=obj[name];var kind=writeable?"var":"const";if(topScope.hasOwn(name)){topScope.remove(name)}topScope.add(name,kind,{loc:{start:{line:-1}}},-1)}}var topScope=new Scope({kind:"hoist",node:{},parent:null});var complementary={undefined:false,Infinity:false,console:false};inject(complementary);inject(jshint_vars.reservedVars);inject(jshint_vars.ecmaIdentifiers);if(environments){environments.forEach(function(env){if(!jshint_vars[env]){error(-1,'environment "{0}" not found',env)}else{inject(jshint_vars[env])}})}if(globals){inject(globals)}programScope.parent=topScope;topScope.children.push(programScope);return topScope}function setupReferences(ast,allIdentifiers,opts){var analyze=is.own(opts,"analyze")?opts.analyze:true;function visit(node){if(!isReference(node)){return}allIdentifiers.add(node.name);var scope=node.$scope.lookup(node.name);if(analyze&&!scope&&options.disallowUnknownReferences){error(getline(node),"reference to unknown global variable {0}",node.name)}if(analyze&&scope&&is.someof(scope.getKind(node.name),["const","let"])){var allowedFromPos=scope.getFromPos(node.name);var referencedAtPos=node.range[0];assert(is.finitenumber(allowedFromPos));assert(is.finitenumber(referencedAtPos));if(referencedAtPos<allowedFromPos){if(!node.$scope.hasFunctionScopeBetween(scope)){error(getline(node),"{0} is referenced before its declaration",node.name)}}}node.$refToScope=scope}traverse(ast,{pre:visit})}function varify(ast,stats,allIdentifiers,changes){function unique(name){assert(allIdentifiers.has(name));for(var cnt=0;;cnt++){var genName=name+"$"+String(cnt);if(!allIdentifiers.has(genName)){return genName}}}function renameDeclarations(node){if(node.type==="VariableDeclaration"&&isConstLet(node.kind)){var hoistScope=node.$scope.closestHoistScope();var origScope=node.$scope;changes.push({start:node.range[0],end:node.range[0]+node.kind.length,str:"var"});node.declarations.forEach(function(declarator){assert(declarator.type==="VariableDeclarator");var name=declarator.id.name;stats.declarator(node.kind);var rename=origScope!==hoistScope&&(hoistScope.hasOwn(name)||hoistScope.doesPropagate(name));var newName=rename?unique(name):name;origScope.remove(name);hoistScope.add(newName,"var",declarator.id,declarator.range[1]);origScope.moves=origScope.moves||stringmap();origScope.moves.set(name,{name:newName,scope:hoistScope});allIdentifiers.add(newName);if(newName!==name){stats.rename(name,newName,getline(declarator));declarator.id.originalName=name;declarator.id.name=newName;changes.push({start:declarator.id.range[0],end:declarator.id.range[1],str:newName})}});node.kind="var"}}function renameReferences(node){if(!node.$refToScope){return}var move=node.$refToScope.moves&&node.$refToScope.moves.get(node.name);if(!move){return}node.$refToScope=move.scope;if(node.name!==move.name){node.originalName=node.name;node.name=move.name;if(node.alterop){var existingOp=null;for(var i=0;i<changes.length;i++){var op=changes[i];if(op.node===node){existingOp=op;break}}assert(existingOp);existingOp.str=move.name}else{changes.push({start:node.range[0],end:node.range[1],str:move.name})}}}traverse(ast,{pre:renameDeclarations});traverse(ast,{pre:renameReferences});ast.$scope.traverse({pre:function(scope){delete scope.moves}})}function detectLoopClosures(ast){traverse(ast,{pre:visit});function detectIifyBodyBlockers(body,node){return breakable(function(brk){traverse(body,{pre:function(n){if(isFunction(n)){return false}var err=true;var msg="loop-variable {0} is captured by a loop-closure that can't be transformed due to use of {1} at line {2}";if(n.type==="BreakStatement"){error(getline(node),msg,node.name,"break",getline(n))}else if(n.type==="ContinueStatement"){error(getline(node),msg,node.name,"continue",getline(n)) }else if(n.type==="ReturnStatement"){error(getline(node),msg,node.name,"return",getline(n))}else if(n.type==="YieldExpression"){error(getline(node),msg,node.name,"yield",getline(n))}else if(n.type==="Identifier"&&n.name==="arguments"){error(getline(node),msg,node.name,"arguments",getline(n))}else if(n.type==="VariableDeclaration"&&n.kind==="var"){error(getline(node),msg,node.name,"var",getline(n))}else{err=false}if(err){brk(true)}}});return false})}function visit(node){var loopNode=null;if(isReference(node)&&node.$refToScope&&isConstLet(node.$refToScope.getKind(node.name))){for(var n=node.$refToScope.node;;){if(isFunction(n)){return}else if(isLoop(n)){loopNode=n;break}n=n.$parent;if(!n){return}}assert(isLoop(loopNode));var defScope=node.$refToScope;var generateIIFE=options.loopClosures==="iife";for(var s=node.$scope;s;s=s.parent){if(s===defScope){return}else if(isFunction(s.node)){if(!generateIIFE){var msg='loop-variable {0} is captured by a loop-closure. Tried "loopClosures": "iife" in defs-config.json?';return error(getline(node),msg,node.name)}if(loopNode.type==="ForStatement"&&defScope.node===loopNode){var declarationNode=defScope.getNode(node.name);return error(getline(declarationNode),"Not yet specced ES6 feature. {0} is declared in for-loop header and then captured in loop closure",declarationNode.name)}if(detectIifyBodyBlockers(loopNode.body,node)){return}loopNode.$iify=true}}}}}function transformLoopClosures(root,ops,options){function insertOp(pos,str,node){var op={start:pos,end:pos,str:str};if(node){op.node=node}ops.push(op)}traverse(root,{pre:function(node){if(!node.$iify){return}var hasBlock=node.body.type==="BlockStatement";var insertHead=hasBlock?node.body.range[0]+1:node.body.range[0];var insertFoot=hasBlock?node.body.range[1]-1:node.body.range[1];var forInName=isForInOf(node)&&node.left.declarations[0].id.name;var iifeHead=fmt("(function({0}){",forInName?forInName:"");var iifeTail=fmt("}).call(this{0});",forInName?", "+forInName:"");var iifeFragment=options.parse(iifeHead+iifeTail);var iifeExpressionStatement=iifeFragment.body[0];var iifeBlockStatement=iifeExpressionStatement.expression.callee.object.body;if(hasBlock){var forBlockStatement=node.body;var tmp=forBlockStatement.body;forBlockStatement.body=[iifeExpressionStatement];iifeBlockStatement.body=tmp}else{var tmp$0=node.body;node.body=iifeExpressionStatement;iifeBlockStatement.body[0]=tmp$0}insertOp(insertHead,iifeHead);if(forInName){insertOp(insertFoot,"}).call(this, ");var args=iifeExpressionStatement.expression.arguments;var iifeArgumentIdentifier=args[1];iifeArgumentIdentifier.alterop=true;insertOp(insertFoot,forInName,iifeArgumentIdentifier);insertOp(insertFoot,");")}else{insertOp(insertFoot,iifeTail)}}})}function detectConstAssignment(ast){traverse(ast,{pre:function(node){if(isLvalue(node)){var scope=node.$scope.lookup(node.name);if(scope&&scope.getKind(node.name)==="const"){error(getline(node),"can't assign to const variable {0}",node.name)}}}})}function detectConstantLets(ast){traverse(ast,{pre:function(node){if(isLvalue(node)){var scope=node.$scope.lookup(node.name);if(scope){scope.markWrite(node.name)}}}});ast.$scope.detectUnmodifiedLets()}function setupScopeAndReferences(root,opts){traverse(root,{pre:createScopes});var topScope=createTopScope(root.$scope,options.environments,options.globals);var allIdentifiers=stringset();topScope.traverse({pre:function(scope){allIdentifiers.addMany(scope.decls.keys())}});setupReferences(root,allIdentifiers,opts);return allIdentifiers}function cleanupTree(root){traverse(root,{pre:function(node){for(var prop in node){if(prop[0]==="$"){delete node[prop]}}}})}function run(src,config){for(var key in config){options[key]=config[key]}var parsed;if(is.object(src)){if(!options.ast){return{errors:["Can't produce string output when input is an AST. "+"Did you forget to set options.ast = true?"]}}parsed=src}else if(is.string(src)){try{parsed=options.parse(src,{loc:true,range:true})}catch(e){return{errors:[fmt("line {0} column {1}: Error during input file parsing\n{2}\n{3}",e.lineNumber,e.column,src.split("\n")[e.lineNumber-1],fmt.repeat(" ",e.column-1)+"^")]}}}else{return{errors:["Input was neither an AST object nor a string."]}}var ast=parsed;error.reset();var allIdentifiers=setupScopeAndReferences(ast,{});detectLoopClosures(ast);detectConstAssignment(ast);var changes=[];transformLoopClosures(ast,changes,options);if(error.errors.length>=1){return{errors:error.errors}}if(changes.length>0){cleanupTree(ast);allIdentifiers=setupScopeAndReferences(ast,{analyze:false})}assert(error.errors.length===0);var stats=new Stats;varify(ast,stats,allIdentifiers,changes);if(options.ast){cleanupTree(ast);return{stats:stats,ast:ast}}else{var transformedSrc=alter(src,changes);return{stats:stats,src:transformedSrc}}}module.exports=run},{"./error":133,"./jshint_globals/vars.js":134,"./options":135,"./scope":136,"./stats":137,alter:138,assert:91,"ast-traverse":140,breakable:141,"simple-fmt":142,"simple-is":143,stringmap:144,stringset:145}],133:[function(require,module,exports){"use strict";var fmt=require("simple-fmt");var assert=require("assert");function error(line,var_args){assert(arguments.length>=2);var msg=arguments.length===2?String(var_args):fmt.apply(fmt,Array.prototype.slice.call(arguments,1));error.errors.push(line===-1?msg:fmt("line {0}: {1}",line,msg))}error.reset=function(){error.errors=[]};error.getline=function(node){if(node&&node.loc&&node.loc.start){return node.loc.start.line}return-1};error.reset();module.exports=error},{assert:91,"simple-fmt":142}],134:[function(require,module,exports){"use strict";exports.reservedVars={arguments:false,NaN:false};exports.ecmaIdentifiers={Array:false,Boolean:false,Date:false,decodeURI:false,decodeURIComponent:false,encodeURI:false,encodeURIComponent:false,Error:false,eval:false,EvalError:false,Function:false,hasOwnProperty:false,isFinite:false,isNaN:false,JSON:false,Math:false,Map:false,Number:false,Object:false,parseInt:false,parseFloat:false,RangeError:false,ReferenceError:false,RegExp:false,Set:false,String:false,SyntaxError:false,TypeError:false,URIError:false,WeakMap:false};exports.browser={ArrayBuffer:false,ArrayBufferView:false,Audio:false,Blob:false,addEventListener:false,applicationCache:false,atob:false,blur:false,btoa:false,clearInterval:false,clearTimeout:false,close:false,closed:false,DataView:false,DOMParser:false,defaultStatus:false,document:false,Element:false,event:false,FileReader:false,Float32Array:false,Float64Array:false,FormData:false,focus:false,frames:false,getComputedStyle:false,HTMLElement:false,HTMLAnchorElement:false,HTMLBaseElement:false,HTMLBlockquoteElement:false,HTMLBodyElement:false,HTMLBRElement:false,HTMLButtonElement:false,HTMLCanvasElement:false,HTMLDirectoryElement:false,HTMLDivElement:false,HTMLDListElement:false,HTMLFieldSetElement:false,HTMLFontElement:false,HTMLFormElement:false,HTMLFrameElement:false,HTMLFrameSetElement:false,HTMLHeadElement:false,HTMLHeadingElement:false,HTMLHRElement:false,HTMLHtmlElement:false,HTMLIFrameElement:false,HTMLImageElement:false,HTMLInputElement:false,HTMLIsIndexElement:false,HTMLLabelElement:false,HTMLLayerElement:false,HTMLLegendElement:false,HTMLLIElement:false,HTMLLinkElement:false,HTMLMapElement:false,HTMLMenuElement:false,HTMLMetaElement:false,HTMLModElement:false,HTMLObjectElement:false,HTMLOListElement:false,HTMLOptGroupElement:false,HTMLOptionElement:false,HTMLParagraphElement:false,HTMLParamElement:false,HTMLPreElement:false,HTMLQuoteElement:false,HTMLScriptElement:false,HTMLSelectElement:false,HTMLStyleElement:false,HTMLTableCaptionElement:false,HTMLTableCellElement:false,HTMLTableColElement:false,HTMLTableElement:false,HTMLTableRowElement:false,HTMLTableSectionElement:false,HTMLTextAreaElement:false,HTMLTitleElement:false,HTMLUListElement:false,HTMLVideoElement:false,history:false,Int16Array:false,Int32Array:false,Int8Array:false,Image:false,length:false,localStorage:false,location:false,MessageChannel:false,MessageEvent:false,MessagePort:false,moveBy:false,moveTo:false,MutationObserver:false,name:false,Node:false,NodeFilter:false,navigator:false,onbeforeunload:true,onblur:true,onerror:true,onfocus:true,onload:true,onresize:true,onunload:true,open:false,openDatabase:false,opener:false,Option:false,parent:false,print:false,removeEventListener:false,resizeBy:false,resizeTo:false,screen:false,scroll:false,scrollBy:false,scrollTo:false,sessionStorage:false,setInterval:false,setTimeout:false,SharedWorker:false,status:false,top:false,Uint16Array:false,Uint32Array:false,Uint8Array:false,Uint8ClampedArray:false,WebSocket:false,window:false,Worker:false,XMLHttpRequest:false,XMLSerializer:false,XPathEvaluator:false,XPathException:false,XPathExpression:false,XPathNamespace:false,XPathNSResolver:false,XPathResult:false};exports.devel={alert:false,confirm:false,console:false,Debug:false,opera:false,prompt:false};exports.worker={importScripts:true,postMessage:true,self:true};exports.nonstandard={escape:false,unescape:false};exports.couch={require:false,respond:false,getRow:false,emit:false,send:false,start:false,sum:false,log:false,exports:false,module:false,provides:false};exports.node={__filename:false,__dirname:false,Buffer:false,DataView:false,console:false,exports:true,GLOBAL:false,global:false,module:false,process:false,require:false,setTimeout:false,clearTimeout:false,setInterval:false,clearInterval:false};exports.phantom={phantom:true,require:true,WebPage:true};exports.rhino={defineClass:false,deserialize:false,gc:false,help:false,importPackage:false,java:false,load:false,loadClass:false,print:false,quit:false,readFile:false,readUrl:false,runCommand:false,seal:false,serialize:false,spawn:false,sync:false,toint32:false,version:false};exports.wsh={ActiveXObject:true,Enumerator:true,GetObject:true,ScriptEngine:true,ScriptEngineBuildVersion:true,ScriptEngineMajorVersion:true,ScriptEngineMinorVersion:true,VBArray:true,WSH:true,WScript:true,XDomainRequest:true};exports.dojo={dojo:false,dijit:false,dojox:false,define:false,require:false};exports.jquery={$:false,jQuery:false};exports.mootools={$:false,$$:false,Asset:false,Browser:false,Chain:false,Class:false,Color:false,Cookie:false,Core:false,Document:false,DomReady:false,DOMEvent:false,DOMReady:false,Drag:false,Element:false,Elements:false,Event:false,Events:false,Fx:false,Group:false,Hash:false,HtmlTable:false,Iframe:false,IframeShim:false,InputValidator:false,instanceOf:false,Keyboard:false,Locale:false,Mask:false,MooTools:false,Native:false,Options:false,OverText:false,Request:false,Scroller:false,Slick:false,Slider:false,Sortables:false,Spinner:false,Swiff:false,Tips:false,Type:false,typeOf:false,URI:false,Window:false};exports.prototypejs={$:false,$$:false,$A:false,$F:false,$H:false,$R:false,$break:false,$continue:false,$w:false,Abstract:false,Ajax:false,Class:false,Enumerable:false,Element:false,Event:false,Field:false,Form:false,Hash:false,Insertion:false,ObjectRange:false,PeriodicalExecuter:false,Position:false,Prototype:false,Selector:false,Template:false,Toggle:false,Try:false,Autocompleter:false,Builder:false,Control:false,Draggable:false,Draggables:false,Droppables:false,Effect:false,Sortable:false,SortableObserver:false,Sound:false,Scriptaculous:false};exports.yui={YUI:false,Y:false,YUI_config:false}},{}],135:[function(require,module,exports){module.exports={disallowVars:false,disallowDuplicated:true,disallowUnknownReferences:true,parse:require("esprima-fb").parse}},{"esprima-fb":146}],136:[function(require,module,exports){"use strict";var assert=require("assert");var stringmap=require("stringmap");var stringset=require("stringset");var is=require("simple-is");var fmt=require("simple-fmt");var error=require("./error");var getline=error.getline;var options=require("./options");function Scope(args){assert(is.someof(args.kind,["hoist","block","catch-block"]));assert(is.object(args.node));assert(args.parent===null||is.object(args.parent));this.kind=args.kind;this.node=args.node;this.parent=args.parent;this.children=[];this.decls=stringmap();this.written=stringset();this.propagates=this.kind==="hoist"?stringset():null;if(this.parent){this.parent.children.push(this)}}Scope.prototype.print=function(indent){indent=indent||0;var scope=this;var names=this.decls.keys().map(function(name){return fmt("{0} [{1}]",name,scope.decls.get(name).kind)}).join(", ");var propagates=this.propagates?this.propagates.items().join(", "):"";console.log(fmt("{0}{1}: {2}. propagates: {3}",fmt.repeat(" ",indent),this.node.type,names,propagates));this.children.forEach(function(c){c.print(indent+2)})};Scope.prototype.add=function(name,kind,node,referableFromPos){assert(is.someof(kind,["fun","param","var","caught","const","let"]));function isConstLet(kind){return is.someof(kind,["const","let"])}var scope=this;if(is.someof(kind,["fun","param","var"])){while(scope.kind!=="hoist"){if(scope.decls.has(name)&&isConstLet(scope.decls.get(name).kind)){return error(getline(node),"{0} is already declared",name)}scope=scope.parent}}if(scope.decls.has(name)&&(options.disallowDuplicated||isConstLet(scope.decls.get(name).kind)||isConstLet(kind))){return error(getline(node),"{0} is already declared",name)}var declaration={kind:kind,node:node};if(referableFromPos){assert(is.someof(kind,["var","const","let"]));declaration.from=referableFromPos}scope.decls.set(name,declaration)};Scope.prototype.getKind=function(name){assert(is.string(name));var decl=this.decls.get(name);return decl?decl.kind:null};Scope.prototype.getNode=function(name){assert(is.string(name));var decl=this.decls.get(name);return decl?decl.node:null};Scope.prototype.getFromPos=function(name){assert(is.string(name));var decl=this.decls.get(name);return decl?decl.from:null};Scope.prototype.hasOwn=function(name){return this.decls.has(name)};Scope.prototype.remove=function(name){return this.decls.remove(name)};Scope.prototype.doesPropagate=function(name){return this.propagates.has(name)};Scope.prototype.markPropagates=function(name){this.propagates.add(name)};Scope.prototype.closestHoistScope=function(){var scope=this;while(scope.kind!=="hoist"){scope=scope.parent}return scope};Scope.prototype.hasFunctionScopeBetween=function(outer){function isFunction(node){return is.someof(node.type,["FunctionDeclaration","FunctionExpression"])}for(var scope=this;scope;scope=scope.parent){if(scope===outer){return false}if(isFunction(scope.node)){return true}}throw new Error("wasn't inner scope of outer")};Scope.prototype.lookup=function(name){for(var scope=this;scope;scope=scope.parent){if(scope.decls.has(name)){return scope}else if(scope.kind==="hoist"){scope.propagates.add(name)}}return null};Scope.prototype.markWrite=function(name){assert(is.string(name));this.written.add(name)};Scope.prototype.detectUnmodifiedLets=function(){var outmost=this;function detect(scope){if(scope!==outmost){scope.decls.keys().forEach(function(name){if(scope.getKind(name)==="let"&&!scope.written.has(name)){return error(getline(scope.getNode(name)),"{0} is declared as let but never modified so could be const",name)}})}scope.children.forEach(function(childScope){detect(childScope)})}detect(this)};Scope.prototype.traverse=function(options){options=options||{};var pre=options.pre;var post=options.post;function visit(scope){if(pre){pre(scope)}scope.children.forEach(function(childScope){visit(childScope)});if(post){post(scope)}}visit(this)};module.exports=Scope},{"./error":133,"./options":135,assert:91,"simple-fmt":142,"simple-is":143,stringmap:144,stringset:145}],137:[function(require,module,exports){var fmt=require("simple-fmt");var is=require("simple-is");var assert=require("assert");function Stats(){this.lets=0;this.consts=0;this.renames=[]}Stats.prototype.declarator=function(kind){assert(is.someof(kind,["const","let"]));if(kind==="const"){this.consts++}else{this.lets++}};Stats.prototype.rename=function(oldName,newName,line){this.renames.push({oldName:oldName,newName:newName,line:line})};Stats.prototype.toString=function(){var renames=this.renames.map(function(r){return r}).sort(function(a,b){return a.line-b.line});var renameStr=renames.map(function(rename){return fmt("\nline {0}: {1} => {2}",rename.line,rename.oldName,rename.newName)}).join("");var sum=this.consts+this.lets;var constlets=sum===0?"can't calculate const coverage (0 consts, 0 lets)":fmt("{0}% const coverage ({1} consts, {2} lets)",Math.floor(100*this.consts/sum),this.consts,this.lets);return constlets+renameStr+"\n"};module.exports=Stats},{assert:91,"simple-fmt":142,"simple-is":143}],138:[function(require,module,exports){var assert=require("assert");var stableSort=require("stable");function alter(str,fragments){"use strict";var isArray=Array.isArray||function(v){return Object.prototype.toString.call(v)==="[object Array]"};assert(typeof str==="string");assert(isArray(fragments));var sortedFragments=stableSort(fragments,function(a,b){return a.start-b.start});var outs=[];var pos=0;for(var i=0;i<sortedFragments.length;i++){var frag=sortedFragments[i];assert(pos<=frag.start);assert(frag.start<=frag.end);outs.push(str.slice(pos,frag.start));outs.push(frag.str);pos=frag.end}if(pos<str.length){outs.push(str.slice(pos))}return outs.join("")}if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=alter}},{assert:91,stable:139}],139:[function(require,module,exports){(function(){var stable=function(arr,comp){return exec(arr.slice(),comp)};stable.inplace=function(arr,comp){var result=exec(arr,comp);if(result!==arr){pass(result,null,arr.length,arr)}return arr};function exec(arr,comp){if(typeof comp!=="function"){comp=function(a,b){return String(a).localeCompare(b)}}var len=arr.length;if(len<=1){return arr}var buffer=new Array(len);for(var chk=1;chk<len;chk*=2){pass(arr,comp,chk,buffer);var tmp=arr;arr=buffer;buffer=tmp}return arr}var pass=function(arr,comp,chk,result){var len=arr.length;var i=0;var dbl=chk*2;var l,r,e;var li,ri;for(l=0;l<len;l+=dbl){r=l+chk;e=r+chk;if(r>len)r=len;if(e>len)e=len;li=l;ri=r;while(true){if(li<r&&ri<e){if(comp(arr[li],arr[ri])<=0){result[i++]=arr[li++]}else{result[i++]=arr[ri++]}}else if(li<r){result[i++]=arr[li++]}else if(ri<e){result[i++]=arr[ri++]}else{break}}}};if(typeof module!=="undefined"){module.exports=stable}else{window.stable=stable}})()},{}],140:[function(require,module,exports){function traverse(root,options){"use strict";options=options||{};var pre=options.pre;var post=options.post;var skipProperty=options.skipProperty;function visit(node,parent,prop,idx){if(!node||typeof node.type!=="string"){return}var res=undefined;if(pre){res=pre(node,parent,prop,idx)}if(res!==false){for(var prop in node){if(skipProperty?skipProperty(prop,node):prop[0]==="$"){continue}var child=node[prop];if(Array.isArray(child)){for(var i=0;i<child.length;i++){visit(child[i],node,prop,i)}}else{visit(child,node,prop)}}}if(post){post(node,parent,prop,idx)}}visit(root,null)}if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=traverse}},{}],141:[function(require,module,exports){var breakable=function(){"use strict";function Val(val,brk){this.val=val;this.brk=brk}function make_brk(){return function brk(val){throw new Val(val,brk)}}function breakable(fn){var brk=make_brk();try{return fn(brk)}catch(e){if(e instanceof Val&&e.brk===brk){return e.val}throw e}}return breakable}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=breakable}},{}],142:[function(require,module,exports){var fmt=function(){"use strict";function fmt(str,var_args){var args=Array.prototype.slice.call(arguments,1);return str.replace(/\{(\d+)\}/g,function(s,match){return match in args?args[match]:s})}function obj(str,obj){return str.replace(/\{([_$a-zA-Z0-9][_$a-zA-Z0-9]*)\}/g,function(s,match){return match in obj?obj[match]:s})}function repeat(str,n){return new Array(n+1).join(str)}fmt.fmt=fmt;fmt.obj=obj;fmt.repeat=repeat;return fmt}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=fmt}},{}],143:[function(require,module,exports){var is=function(){"use strict";var hasOwnProperty=Object.prototype.hasOwnProperty;var toString=Object.prototype.toString;var _undefined=void 0;return{nan:function(v){return v!==v},"boolean":function(v){return typeof v==="boolean"},number:function(v){return typeof v==="number"},string:function(v){return typeof v==="string"},fn:function(v){return typeof v==="function"},object:function(v){return v!==null&&typeof v==="object"},primitive:function(v){var t=typeof v;return v===null||v===_undefined||t==="boolean"||t==="number"||t==="string"},array:Array.isArray||function(v){return toString.call(v)==="[object Array]"},finitenumber:function(v){return typeof v==="number"&&isFinite(v)},someof:function(v,values){return values.indexOf(v)>=0},noneof:function(v,values){return values.indexOf(v)===-1},own:function(obj,prop){return hasOwnProperty.call(obj,prop)}}}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=is}},{}],144:[function(require,module,exports){var StringMap=function(){"use strict";var hasOwnProperty=Object.prototype.hasOwnProperty;var create=function(){function hasOwnEnumerableProps(obj){for(var prop in obj){if(hasOwnProperty.call(obj,prop)){return true}}return false}function hasOwnPollutedProps(obj){return hasOwnProperty.call(obj,"__count__")||hasOwnProperty.call(obj,"__parent__")}var useObjectCreate=false;if(typeof Object.create==="function"){if(!hasOwnEnumerableProps(Object.create(null))){useObjectCreate=true}}if(useObjectCreate===false){if(hasOwnEnumerableProps({})){throw new Error("StringMap environment error 0, please file a bug at https://github.com/olov/stringmap/issues")}}var o=useObjectCreate?Object.create(null):{};var useProtoClear=false;if(hasOwnPollutedProps(o)){o.__proto__=null;if(hasOwnEnumerableProps(o)||hasOwnPollutedProps(o)){throw new Error("StringMap environment error 1, please file a bug at https://github.com/olov/stringmap/issues")}useProtoClear=true}return function(){var o=useObjectCreate?Object.create(null):{};if(useProtoClear){o.__proto__=null}return o}}();function stringmap(optional_object){if(!(this instanceof stringmap)){return new stringmap(optional_object)}this.obj=create();this.hasProto=false;this.proto=undefined;if(optional_object){this.setMany(optional_object)}}stringmap.prototype.has=function(key){if(typeof key!=="string"){throw new Error("StringMap expected string key")}return key==="__proto__"?this.hasProto:hasOwnProperty.call(this.obj,key)};stringmap.prototype.get=function(key){if(typeof key!=="string"){throw new Error("StringMap expected string key")}return key==="__proto__"?this.proto:hasOwnProperty.call(this.obj,key)?this.obj[key]:undefined};stringmap.prototype.set=function(key,value){if(typeof key!=="string"){throw new Error("StringMap expected string key")}if(key==="__proto__"){this.hasProto=true;this.proto=value}else{this.obj[key]=value}};stringmap.prototype.remove=function(key){if(typeof key!=="string"){throw new Error("StringMap expected string key")}var didExist=this.has(key);if(key==="__proto__"){this.hasProto=false;this.proto=undefined}else{delete this.obj[key]}return didExist};stringmap.prototype["delete"]=stringmap.prototype.remove;stringmap.prototype.isEmpty=function(){for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){return false}}return!this.hasProto};stringmap.prototype.size=function(){var len=0;for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){++len}}return this.hasProto?len+1:len};stringmap.prototype.keys=function(){var keys=[];for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){keys.push(key)}}if(this.hasProto){keys.push("__proto__")}return keys};stringmap.prototype.values=function(){var values=[];for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){values.push(this.obj[key])}}if(this.hasProto){values.push(this.proto)}return values};stringmap.prototype.items=function(){var items=[];for(var key in this.obj){if(hasOwnProperty.call(this.obj,key)){items.push([key,this.obj[key]])}}if(this.hasProto){items.push(["__proto__",this.proto])}return items};stringmap.prototype.setMany=function(object){if(object===null||typeof object!=="object"&&typeof object!=="function"){throw new Error("StringMap expected Object")}for(var key in object){if(hasOwnProperty.call(object,key)){this.set(key,object[key])}}return this};stringmap.prototype.merge=function(other){var keys=other.keys();for(var i=0;i<keys.length;i++){var key=keys[i];this.set(key,other.get(key))}return this};stringmap.prototype.map=function(fn){var keys=this.keys();for(var i=0;i<keys.length;i++){var key=keys[i];keys[i]=fn(this.get(key),key)}return keys};stringmap.prototype.forEach=function(fn){var keys=this.keys();for(var i=0;i<keys.length;i++){var key=keys[i];fn(this.get(key),key)}};stringmap.prototype.clone=function(){var other=stringmap();return other.merge(this)};stringmap.prototype.toString=function(){var self=this;return"{"+this.keys().map(function(key){return JSON.stringify(key)+":"+JSON.stringify(self.get(key))}).join(",")+"}"};return stringmap}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=StringMap}},{}],145:[function(require,module,exports){var StringSet=function(){"use strict";var hasOwnProperty=Object.prototype.hasOwnProperty;var create=function(){function hasOwnEnumerableProps(obj){for(var prop in obj){if(hasOwnProperty.call(obj,prop)){return true}}return false}function hasOwnPollutedProps(obj){return hasOwnProperty.call(obj,"__count__")||hasOwnProperty.call(obj,"__parent__")}var useObjectCreate=false;if(typeof Object.create==="function"){if(!hasOwnEnumerableProps(Object.create(null))){useObjectCreate=true}}if(useObjectCreate===false){if(hasOwnEnumerableProps({})){throw new Error("StringSet environment error 0, please file a bug at https://github.com/olov/stringset/issues")}}var o=useObjectCreate?Object.create(null):{};var useProtoClear=false;if(hasOwnPollutedProps(o)){o.__proto__=null;if(hasOwnEnumerableProps(o)||hasOwnPollutedProps(o)){throw new Error("StringSet environment error 1, please file a bug at https://github.com/olov/stringset/issues")}useProtoClear=true}return function(){var o=useObjectCreate?Object.create(null):{};if(useProtoClear){o.__proto__=null}return o}}();function stringset(optional_array){if(!(this instanceof stringset)){return new stringset(optional_array)}this.obj=create();this.hasProto=false;if(optional_array){this.addMany(optional_array)}}stringset.prototype.has=function(item){if(typeof item!=="string"){throw new Error("StringSet expected string item")}return item==="__proto__"?this.hasProto:hasOwnProperty.call(this.obj,item)};stringset.prototype.add=function(item){if(typeof item!=="string"){throw new Error("StringSet expected string item")}if(item==="__proto__"){this.hasProto=true}else{this.obj[item]=true}};stringset.prototype.remove=function(item){if(typeof item!=="string"){throw new Error("StringSet expected string item")}var didExist=this.has(item);if(item==="__proto__"){this.hasProto=false}else{delete this.obj[item]}return didExist};stringset.prototype["delete"]=stringset.prototype.remove;stringset.prototype.isEmpty=function(){for(var item in this.obj){if(hasOwnProperty.call(this.obj,item)){return false}}return!this.hasProto};stringset.prototype.size=function(){var len=0;for(var item in this.obj){if(hasOwnProperty.call(this.obj,item)){++len}}return this.hasProto?len+1:len};stringset.prototype.items=function(){var items=[];for(var item in this.obj){if(hasOwnProperty.call(this.obj,item)){items.push(item)}}if(this.hasProto){items.push("__proto__")}return items};stringset.prototype.addMany=function(items){if(!Array.isArray(items)){throw new Error("StringSet expected array")}for(var i=0;i<items.length;i++){this.add(items[i])}return this};stringset.prototype.merge=function(other){this.addMany(other.items());return this};stringset.prototype.clone=function(){var other=stringset();return other.merge(this)};stringset.prototype.toString=function(){return"{"+this.items().map(JSON.stringify).join(",")+"}"};return stringset}();if(typeof module!=="undefined"&&typeof module.exports!=="undefined"){module.exports=StringSet}},{}],146:[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.esprima={})}})(this,function(exports){"use strict";var Token,TokenName,FnExprTokens,Syntax,PropertyKind,Messages,Regex,SyntaxTreeDelegate,XHTMLEntities,ClassPropertyType,source,strict,index,lineNumber,lineStart,length,delegate,lookahead,state,extra;Token={BooleanLiteral:1,EOF:2,Identifier:3,Keyword:4,NullLiteral:5,NumericLiteral:6,Punctuator:7,StringLiteral:8,RegularExpression:9,Template:10,XJSIdentifier:11,XJSText:12};TokenName={};TokenName[Token.BooleanLiteral]="Boolean";TokenName[Token.EOF]="<end>";TokenName[Token.Identifier]="Identifier";TokenName[Token.Keyword]="Keyword";TokenName[Token.NullLiteral]="Null";TokenName[Token.NumericLiteral]="Numeric";TokenName[Token.Punctuator]="Punctuator";TokenName[Token.StringLiteral]="String";TokenName[Token.XJSIdentifier]="XJSIdentifier";TokenName[Token.XJSText]="XJSText";TokenName[Token.RegularExpression]="RegularExpression";FnExprTokens=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="];Syntax={AnyTypeAnnotation:"AnyTypeAnnotation",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrayTypeAnnotation:"ArrayTypeAnnotation",ArrowFunctionExpression:"ArrowFunctionExpression",AssignmentExpression:"AssignmentExpression",BinaryExpression:"BinaryExpression",BlockStatement:"BlockStatement",BooleanTypeAnnotation:"BooleanTypeAnnotation",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ClassImplements:"ClassImplements",ClassProperty:"ClassProperty",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DeclareClass:"DeclareClass",DeclareFunction:"DeclareFunction",DeclareModule:"DeclareModule",DeclareVariable:"DeclareVariable",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportDeclaration:"ExportDeclaration",ExportBatchSpecifier:"ExportBatchSpecifier",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",ForStatement:"ForStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",FunctionTypeAnnotation:"FunctionTypeAnnotation",FunctionTypeParam:"FunctionTypeParam",GenericTypeAnnotation:"GenericTypeAnnotation",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",InterfaceDeclaration:"InterfaceDeclaration",InterfaceExtends:"InterfaceExtends",IntersectionTypeAnnotation:"IntersectionTypeAnnotation",LabeledStatement:"LabeledStatement",Literal:"Literal",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",NullableTypeAnnotation:"NullableTypeAnnotation",NumberTypeAnnotation:"NumberTypeAnnotation",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",ObjectTypeAnnotation:"ObjectTypeAnnotation",ObjectTypeCallProperty:"ObjectTypeCallProperty",ObjectTypeIndexer:"ObjectTypeIndexer",ObjectTypeProperty:"ObjectTypeProperty",Program:"Program",Property:"Property",QualifiedTypeIdentifier:"QualifiedTypeIdentifier",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SpreadProperty:"SpreadProperty",StringLiteralTypeAnnotation:"StringLiteralTypeAnnotation",StringTypeAnnotation:"StringTypeAnnotation",SwitchCase:"SwitchCase",SwitchStatement:"SwitchStatement",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TupleTypeAnnotation:"TupleTypeAnnotation",TryStatement:"TryStatement",TypeAlias:"TypeAlias",TypeAnnotation:"TypeAnnotation",TypeofTypeAnnotation:"TypeofTypeAnnotation",TypeParameterDeclaration:"TypeParameterDeclaration",TypeParameterInstantiation:"TypeParameterInstantiation",UnaryExpression:"UnaryExpression",UnionTypeAnnotation:"UnionTypeAnnotation",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",VoidTypeAnnotation:"VoidTypeAnnotation",WhileStatement:"WhileStatement",WithStatement:"WithStatement",XJSIdentifier:"XJSIdentifier",XJSNamespacedName:"XJSNamespacedName",XJSMemberExpression:"XJSMemberExpression",XJSEmptyExpression:"XJSEmptyExpression",XJSExpressionContainer:"XJSExpressionContainer",XJSElement:"XJSElement",XJSClosingElement:"XJSClosingElement",XJSOpeningElement:"XJSOpeningElement",XJSAttribute:"XJSAttribute",XJSSpreadAttribute:"XJSSpreadAttribute",XJSText:"XJSText",YieldExpression:"YieldExpression",AwaitExpression:"AwaitExpression"}; PropertyKind={Data:1,Get:2,Set:4};ClassPropertyType={"static":"static",prototype:"prototype"};Messages={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedTemplate:"Unexpected quasi %0",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInFormalsList:"Invalid left-hand side in formals list",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalDuplicateClassProperty:"Illegal duplicate property in class definition",IllegalReturn:"Illegal return statement",IllegalSpread:"Illegal spread element",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",ParameterAfterRestParameter:"Rest parameter must be final parameter of an argument list",DefaultRestParameter:"Rest parameter can not have a default value",ElementAfterSpreadElement:"Spread must be the final element of an element list",PropertyAfterSpreadProperty:"A rest property must be the final property of an object literal",ObjectPatternAsRestParameter:"Invalid rest parameter",ObjectPatternAsSpread:"Invalid spread argument",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode",MissingFromClause:"Missing from clause",NoAsAfterImportNamespace:"Missing as after import *",InvalidModuleSpecifier:"Invalid module specifier",NoUnintializedConst:"Const must be initialized",ComprehensionRequiresBlock:"Comprehension must have at least one block",ComprehensionError:"Comprehension Error",EachNotAllowed:"Each is not supported",InvalidXJSAttributeValue:"XJS value should be either an expression or a quoted XJS text",ExpectedXJSClosingTag:"Expected corresponding XJS closing tag for %0",AdjacentXJSElements:"Adjacent XJS elements must be wrapped in an enclosing tag",ConfusedAboutFunctionType:"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType"};Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),LeadingZeros:new RegExp("^0+(?!$)")};function assert(condition,message){if(!condition){throw new Error("ASSERT: "+message)}}function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return"0123456789abcdefABCDEF".indexOf(ch)>=0}function isOctalDigit(ch){return"01234567".indexOf(ch)>=0}function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&" ᠎              ".indexOf(String.fromCharCode(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))}function isFutureReservedWord(id){switch(id){case"class":case"enum":case"export":case"extends":case"import":case"super":return true;default:return false}}function isStrictModeReservedWord(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return true;default:return false}}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isKeyword(id){if(strict&&isStrictModeReservedWord(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"||id==="let";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function skipComment(){var ch,blockComment,lineComment;blockComment=false;lineComment=false;while(index<length){ch=source.charCodeAt(index);if(lineComment){++index;if(isLineTerminator(ch)){lineComment=false;if(ch===13&&source.charCodeAt(index)===10){++index}++lineNumber;lineStart=index}}else if(blockComment){if(isLineTerminator(ch)){if(ch===13){++index}if(ch!==13||source.charCodeAt(index)===10){++lineNumber;++index;lineStart=index;if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}}else{ch=source.charCodeAt(index++);if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(ch===42){ch=source.charCodeAt(index);if(ch===47){++index;blockComment=false}}}}else if(ch===47){ch=source.charCodeAt(index+1);if(ch===47){index+=2;lineComment=true}else if(ch===42){index+=2;blockComment=true;if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}else{break}}else if(isWhiteSpace(ch)){++index}else if(isLineTerminator(ch)){++index;if(ch===13&&source.charCodeAt(index)===10){++index}++lineNumber;lineStart=index}else{break}}}function scanHexEscape(prefix){var i,len,ch,code=0;len=prefix==="u"?4:2;for(i=0;i<len;++i){if(index<length&&isHexDigit(source[index])){ch=source[index++];code=code*16+"0123456789abcdef".indexOf(ch.toLowerCase())}else{return""}}return String.fromCharCode(code)}function scanUnicodeCodePointEscape(){var ch,code,cu1,cu2;ch=source[index];code=0;if(ch==="}"){throwError({},Messages.UnexpectedToken,"ILLEGAL")}while(index<length){ch=source[index++];if(!isHexDigit(ch)){break}code=code*16+"0123456789abcdef".indexOf(ch.toLowerCase())}if(code>1114111||ch!=="}"){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(code<=65535){return String.fromCharCode(code)}cu1=(code-65536>>10)+55296;cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function getEscapedIdentifier(){var ch,id;ch=source.charCodeAt(index++);id=String.fromCharCode(ch);if(ch===92){if(source.charCodeAt(index)!==117){throwError({},Messages.UnexpectedToken,"ILLEGAL")}++index;ch=scanHexEscape("u");if(!ch||ch==="\\"||!isIdentifierStart(ch.charCodeAt(0))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}id=ch}while(index<length){ch=source.charCodeAt(index);if(!isIdentifierPart(ch)){break}++index;id+=String.fromCharCode(ch);if(ch===92){id=id.substr(0,id.length-1);if(source.charCodeAt(index)!==117){throwError({},Messages.UnexpectedToken,"ILLEGAL")}++index;ch=scanHexEscape("u");if(!ch||ch==="\\"||!isIdentifierPart(ch.charCodeAt(0))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}id+=ch}}return id}function getIdentifier(){var start,ch;start=index++;while(index<length){ch=source.charCodeAt(index);if(ch===92){index=start;return getEscapedIdentifier()}if(isIdentifierPart(ch)){++index}else{break}}return source.slice(start,index)}function scanIdentifier(){var start,id,type;start=index;id=source.charCodeAt(index)===92?getEscapedIdentifier():getIdentifier();if(id.length===1){type=Token.Identifier}else if(isKeyword(id)){type=Token.Keyword}else if(id==="null"){type=Token.NullLiteral}else if(id==="true"||id==="false"){type=Token.BooleanLiteral}else{type=Token.Identifier}return{type:type,value:id,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanPunctuator(){var start=index,code=source.charCodeAt(index),code2,ch1=source[index],ch2,ch3,ch4;switch(code){case 40:case 41:case 59:case 44:case 123:case 125:case 91:case 93:case 58:case 63:case 126:++index;if(extra.tokenize){if(code===40){extra.openParenToken=extra.tokens.length}else if(code===123){extra.openCurlyToken=extra.tokens.length}}return{type:Token.Punctuator,value:String.fromCharCode(code),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]};default:code2=source.charCodeAt(index+1);if(code2===61){switch(code){case 37:case 38:case 42:case 43:case 45:case 47:case 60:case 62:case 94:case 124:index+=2;return{type:Token.Punctuator,value:String.fromCharCode(code)+String.fromCharCode(code2),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]};case 33:case 61:index+=2;if(source.charCodeAt(index)===61){++index}return{type:Token.Punctuator,value:source.slice(start,index),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]};default:break}}break}ch2=source[index+1];ch3=source[index+2];ch4=source[index+3];if(ch1===">"&&ch2===">"&&ch3===">"){if(ch4==="="){index+=4;return{type:Token.Punctuator,value:">>>=",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}}if(ch1===">"&&ch2===">"&&ch3===">"){index+=3;return{type:Token.Punctuator,value:">>>",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1==="<"&&ch2==="<"&&ch3==="="){index+=3;return{type:Token.Punctuator,value:"<<=",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1===">"&&ch2===">"&&ch3==="="){index+=3;return{type:Token.Punctuator,value:">>=",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1==="."&&ch2==="."&&ch3==="."){index+=3;return{type:Token.Punctuator,value:"...",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1===ch2&&"+-<>&|".indexOf(ch1)>=0&&!state.inType){index+=2;return{type:Token.Punctuator,value:ch1+ch2,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1==="="&&ch2===">"){index+=2;return{type:Token.Punctuator,value:"=>",lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if("<>=!+-*%&|^/".indexOf(ch1)>=0){++index;return{type:Token.Punctuator,value:ch1,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch1==="."){++index;return{type:Token.Punctuator,value:ch1,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}throwError({},Messages.UnexpectedToken,"ILLEGAL")}function scanHexLiteral(start){var number="";while(index<length){if(!isHexDigit(source[index])){break}number+=source[index++]}if(number.length===0){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(isIdentifierStart(source.charCodeAt(index))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.NumericLiteral,value:parseInt("0x"+number,16),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanOctalLiteral(prefix,start){var number,octal;if(isOctalDigit(prefix)){octal=true;number="0"+source[index++]}else{octal=false;++index;number=""}while(index<length){if(!isOctalDigit(source[index])){break}number+=source[index++]}if(!octal&&number.length===0){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(isIdentifierStart(source.charCodeAt(index))||isDecimalDigit(source.charCodeAt(index))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.NumericLiteral,value:parseInt(number,8),octal:octal,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanNumericLiteral(){var number,start,ch,octal;ch=source[index];assert(isDecimalDigit(ch.charCodeAt(0))||ch===".","Numeric literal must start with a decimal digit or a decimal point");start=index;number="";if(ch!=="."){number=source[index++];ch=source[index];if(number==="0"){if(ch==="x"||ch==="X"){++index;return scanHexLiteral(start)}if(ch==="b"||ch==="B"){++index;number="";while(index<length){ch=source[index];if(ch!=="0"&&ch!=="1"){break}number+=source[index++]}if(number.length===0){throwError({},Messages.UnexpectedToken,"ILLEGAL")}if(index<length){ch=source.charCodeAt(index);if(isIdentifierStart(ch)||isDecimalDigit(ch)){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}return{type:Token.NumericLiteral,value:parseInt(number,2),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}if(ch==="o"||ch==="O"||isOctalDigit(ch)){return scanOctalLiteral(ch,start)}if(ch&&isDecimalDigit(ch.charCodeAt(0))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++]}ch=source[index]}if(ch==="."){number+=source[index++];while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++]}ch=source[index]}if(ch==="e"||ch==="E"){number+=source[index++];ch=source[index];if(ch==="+"||ch==="-"){number+=source[index++]}if(isDecimalDigit(source.charCodeAt(index))){while(isDecimalDigit(source.charCodeAt(index))){number+=source[index++]}}else{throwError({},Messages.UnexpectedToken,"ILLEGAL")}}if(isIdentifierStart(source.charCodeAt(index))){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.NumericLiteral,value:parseFloat(number),lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanStringLiteral(){var str="",quote,start,ch,code,unescaped,restore,octal=false;quote=source[index];assert(quote==="'"||quote==='"',"String literal must starts with a quote");start=index;++index;while(index<length){ch=source[index++];if(ch===quote){quote="";break}else if(ch==="\\"){ch=source[index++];if(!ch||!isLineTerminator(ch.charCodeAt(0))){switch(ch){case"n":str+="\n";break;case"r":str+="\r";break;case"t":str+=" ";break;case"u":case"x":if(source[index]==="{"){++index;str+=scanUnicodeCodePointEscape()}else{restore=index;unescaped=scanHexEscape(ch);if(unescaped){str+=unescaped}else{index=restore;str+=ch}}break;case"b":str+="\b";break;case"f":str+="\f";break;case"v":str+=" ";break;default:if(isOctalDigit(ch)){code="01234567".indexOf(ch);if(code!==0){octal=true}if(index<length&&isOctalDigit(source[index])){octal=true;code=code*8+"01234567".indexOf(source[index++]);if("0123".indexOf(ch)>=0&&index<length&&isOctalDigit(source[index])){code=code*8+"01234567".indexOf(source[index++])}}str+=String.fromCharCode(code)}else{str+=ch}break}}else{++lineNumber;if(ch==="\r"&&source[index]==="\n"){++index}lineStart=index}}else if(isLineTerminator(ch.charCodeAt(0))){break}else{str+=ch}}if(quote!==""){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.StringLiteral,value:str,octal:octal,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanTemplate(){var cooked="",ch,start,terminated,tail,restore,unescaped,code,octal;terminated=false;tail=false;start=index;++index;while(index<length){ch=source[index++];if(ch==="`"){tail=true;terminated=true;break}else if(ch==="$"){if(source[index]==="{"){++index;terminated=true;break}cooked+=ch}else if(ch==="\\"){ch=source[index++];if(!isLineTerminator(ch.charCodeAt(0))){switch(ch){case"n":cooked+="\n";break;case"r":cooked+="\r";break;case"t":cooked+=" ";break;case"u":case"x":if(source[index]==="{"){++index;cooked+=scanUnicodeCodePointEscape()}else{restore=index;unescaped=scanHexEscape(ch);if(unescaped){cooked+=unescaped}else{index=restore;cooked+=ch}}break;case"b":cooked+="\b";break;case"f":cooked+="\f";break;case"v":cooked+=" ";break;default:if(isOctalDigit(ch)){code="01234567".indexOf(ch);if(code!==0){octal=true}if(index<length&&isOctalDigit(source[index])){octal=true;code=code*8+"01234567".indexOf(source[index++]);if("0123".indexOf(ch)>=0&&index<length&&isOctalDigit(source[index])){code=code*8+"01234567".indexOf(source[index++])}}cooked+=String.fromCharCode(code)}else{cooked+=ch}break}}else{++lineNumber;if(ch==="\r"&&source[index]==="\n"){++index}lineStart=index}}else if(isLineTerminator(ch.charCodeAt(0))){++lineNumber;if(ch==="\r"&&source[index]==="\n"){++index}lineStart=index;cooked+="\n"}else{cooked+=ch}}if(!terminated){throwError({},Messages.UnexpectedToken,"ILLEGAL")}return{type:Token.Template,value:{cooked:cooked,raw:source.slice(start+1,index-(tail?1:2))},tail:tail,octal:octal,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanTemplateElement(option){var startsWith,template;lookahead=null;skipComment();startsWith=option.head?"`":"}";if(source[index]!==startsWith){throwError({},Messages.UnexpectedToken,"ILLEGAL")}template=scanTemplate();peek();return template}function scanRegExp(){var str,ch,start,pattern,flags,value,classMarker=false,restore,terminated=false,tmp;lookahead=null;skipComment();start=index;ch=source[index];assert(ch==="/","Regular expression literal must start with a slash");str=source[index++];while(index<length){ch=source[index++];str+=ch;if(classMarker){if(ch==="]"){classMarker=false}}else{if(ch==="\\"){ch=source[index++];if(isLineTerminator(ch.charCodeAt(0))){throwError({},Messages.UnterminatedRegExp)}str+=ch}else if(ch==="/"){terminated=true;break}else if(ch==="["){classMarker=true}else if(isLineTerminator(ch.charCodeAt(0))){throwError({},Messages.UnterminatedRegExp)}}}if(!terminated){throwError({},Messages.UnterminatedRegExp)}pattern=str.substr(1,str.length-2);flags="";while(index<length){ch=source[index];if(!isIdentifierPart(ch.charCodeAt(0))){break}++index;if(ch==="\\"&&index<length){ch=source[index];if(ch==="u"){++index;restore=index;ch=scanHexEscape("u");if(ch){flags+=ch;for(str+="\\u";restore<index;++restore){str+=source[restore]}}else{index=restore;flags+="u";str+="\\u"}}else{str+="\\"}}else{flags+=ch;str+=ch}}tmp=pattern;if(flags.indexOf("u")>=0){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}try{value=new RegExp(tmp)}catch(e){throwError({},Messages.InvalidRegExp)}try{value=new RegExp(pattern,flags)}catch(exception){value=null}peek();if(extra.tokenize){return{type:Token.RegularExpression,value:value,regex:{pattern:pattern,flags:flags},lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}return{literal:str,value:value,regex:{pattern:pattern,flags:flags},range:[start,index]}}function isIdentifierName(token){return token.type===Token.Identifier||token.type===Token.Keyword||token.type===Token.BooleanLiteral||token.type===Token.NullLiteral}function advanceSlash(){var prevToken,checkToken;prevToken=extra.tokens[extra.tokens.length-1];if(!prevToken){return scanRegExp()}if(prevToken.type==="Punctuator"){if(prevToken.value===")"){checkToken=extra.tokens[extra.openParenToken-1];if(checkToken&&checkToken.type==="Keyword"&&(checkToken.value==="if"||checkToken.value==="while"||checkToken.value==="for"||checkToken.value==="with")){return scanRegExp()}return scanPunctuator()}if(prevToken.value==="}"){if(extra.tokens[extra.openCurlyToken-3]&&extra.tokens[extra.openCurlyToken-3].type==="Keyword"){checkToken=extra.tokens[extra.openCurlyToken-4];if(!checkToken){return scanPunctuator()}}else if(extra.tokens[extra.openCurlyToken-4]&&extra.tokens[extra.openCurlyToken-4].type==="Keyword"){checkToken=extra.tokens[extra.openCurlyToken-5];if(!checkToken){return scanRegExp()}}else{return scanPunctuator()}if(FnExprTokens.indexOf(checkToken.value)>=0){return scanPunctuator()}return scanRegExp()}return scanRegExp()}if(prevToken.type==="Keyword"){return scanRegExp()}return scanPunctuator()}function advance(){var ch;if(!state.inXJSChild){skipComment()}if(index>=length){return{type:Token.EOF,lineNumber:lineNumber,lineStart:lineStart,range:[index,index]}}if(state.inXJSChild){return advanceXJSChild()}ch=source.charCodeAt(index);if(ch===40||ch===41||ch===58){return scanPunctuator()}if(ch===39||ch===34){if(state.inXJSTag){return scanXJSStringLiteral()}return scanStringLiteral()}if(state.inXJSTag&&isXJSIdentifierStart(ch)){return scanXJSIdentifier()}if(ch===96){return scanTemplate()}if(isIdentifierStart(ch)){return scanIdentifier()}if(ch===46){if(isDecimalDigit(source.charCodeAt(index+1))){return scanNumericLiteral()}return scanPunctuator()}if(isDecimalDigit(ch)){return scanNumericLiteral()}if(extra.tokenize&&ch===47){return advanceSlash()}return scanPunctuator()}function lex(){var token;token=lookahead;index=token.range[1];lineNumber=token.lineNumber;lineStart=token.lineStart;lookahead=advance();index=token.range[1];lineNumber=token.lineNumber;lineStart=token.lineStart;return token}function peek(){var pos,line,start;pos=index;line=lineNumber;start=lineStart;lookahead=advance();index=pos;lineNumber=line;lineStart=start}function lookahead2(){var adv,pos,line,start,result;adv=typeof extra.advance==="function"?extra.advance:advance;pos=index;line=lineNumber;start=lineStart;if(lookahead===null){lookahead=adv()}index=lookahead.range[1];lineNumber=lookahead.lineNumber;lineStart=lookahead.lineStart;result=adv();index=pos;lineNumber=line;lineStart=start;return result}function rewind(token){index=token.range[0];lineNumber=token.lineNumber;lineStart=token.lineStart;lookahead=token}function markerCreate(){if(!extra.loc&&!extra.range){return undefined}skipComment();return{offset:index,line:lineNumber,col:index-lineStart}}function markerCreatePreserveWhitespace(){if(!extra.loc&&!extra.range){return undefined}return{offset:index,line:lineNumber,col:index-lineStart}}function processComment(node){var lastChild,trailingComments,bottomRight=extra.bottomRightStack,last=bottomRight[bottomRight.length-1];if(node.type===Syntax.Program){if(node.body.length>0){return}}if(extra.trailingComments.length>0){if(extra.trailingComments[0].range[0]>=node.range[1]){trailingComments=extra.trailingComments;extra.trailingComments=[]}else{extra.trailingComments.length=0}}else{if(last&&last.trailingComments&&last.trailingComments[0].range[0]>=node.range[1]){trailingComments=last.trailingComments;delete last.trailingComments}}if(last){while(last&&last.range[0]>=node.range[0]){lastChild=last;last=bottomRight.pop()}}if(lastChild){if(lastChild.leadingComments&&lastChild.leadingComments[lastChild.leadingComments.length-1].range[1]<=node.range[0]){node.leadingComments=lastChild.leadingComments;delete lastChild.leadingComments}}else if(extra.leadingComments.length>0&&extra.leadingComments[extra.leadingComments.length-1].range[1]<=node.range[0]){node.leadingComments=extra.leadingComments;extra.leadingComments=[]}if(trailingComments){node.trailingComments=trailingComments}bottomRight.push(node)}function markerApply(marker,node){if(extra.range){node.range=[marker.offset,index]}if(extra.loc){node.loc={start:{line:marker.line,column:marker.col},end:{line:lineNumber,column:index-lineStart}};node=delegate.postProcess(node)}if(extra.attachComment){processComment(node)}return node}SyntaxTreeDelegate={name:"SyntaxTree",postProcess:function(node){return node},createArrayExpression:function(elements){return{type:Syntax.ArrayExpression,elements:elements}},createAssignmentExpression:function(operator,left,right){return{type:Syntax.AssignmentExpression,operator:operator,left:left,right:right}},createBinaryExpression:function(operator,left,right){var type=operator==="||"||operator==="&&"?Syntax.LogicalExpression:Syntax.BinaryExpression;return{type:type,operator:operator,left:left,right:right}},createBlockStatement:function(body){return{type:Syntax.BlockStatement,body:body}},createBreakStatement:function(label){return{type:Syntax.BreakStatement,label:label}},createCallExpression:function(callee,args){return{type:Syntax.CallExpression,callee:callee,arguments:args}},createCatchClause:function(param,body){return{type:Syntax.CatchClause,param:param,body:body}},createConditionalExpression:function(test,consequent,alternate){return{type:Syntax.ConditionalExpression,test:test,consequent:consequent,alternate:alternate}},createContinueStatement:function(label){return{type:Syntax.ContinueStatement,label:label}},createDebuggerStatement:function(){return{type:Syntax.DebuggerStatement}},createDoWhileStatement:function(body,test){return{type:Syntax.DoWhileStatement,body:body,test:test}},createEmptyStatement:function(){return{type:Syntax.EmptyStatement}},createExpressionStatement:function(expression){return{type:Syntax.ExpressionStatement,expression:expression}},createForStatement:function(init,test,update,body){return{type:Syntax.ForStatement,init:init,test:test,update:update,body:body}},createForInStatement:function(left,right,body){return{type:Syntax.ForInStatement,left:left,right:right,body:body,each:false}},createForOfStatement:function(left,right,body){return{type:Syntax.ForOfStatement,left:left,right:right,body:body}},createFunctionDeclaration:function(id,params,defaults,body,rest,generator,expression,isAsync,returnType,typeParameters){var funDecl={type:Syntax.FunctionDeclaration,id:id,params:params,defaults:defaults,body:body,rest:rest,generator:generator,expression:expression,returnType:returnType,typeParameters:typeParameters};if(isAsync){funDecl.async=true}return funDecl},createFunctionExpression:function(id,params,defaults,body,rest,generator,expression,isAsync,returnType,typeParameters){var funExpr={type:Syntax.FunctionExpression,id:id,params:params,defaults:defaults,body:body,rest:rest,generator:generator,expression:expression,returnType:returnType,typeParameters:typeParameters};if(isAsync){funExpr.async=true}return funExpr},createIdentifier:function(name){return{type:Syntax.Identifier,name:name,typeAnnotation:undefined,optional:undefined}},createTypeAnnotation:function(typeAnnotation){return{type:Syntax.TypeAnnotation,typeAnnotation:typeAnnotation}},createFunctionTypeAnnotation:function(params,returnType,rest,typeParameters){return{type:Syntax.FunctionTypeAnnotation,params:params,returnType:returnType,rest:rest,typeParameters:typeParameters}},createFunctionTypeParam:function(name,typeAnnotation,optional){return{type:Syntax.FunctionTypeParam,name:name,typeAnnotation:typeAnnotation,optional:optional}},createNullableTypeAnnotation:function(typeAnnotation){return{type:Syntax.NullableTypeAnnotation,typeAnnotation:typeAnnotation}},createArrayTypeAnnotation:function(elementType){return{type:Syntax.ArrayTypeAnnotation,elementType:elementType}},createGenericTypeAnnotation:function(id,typeParameters){return{type:Syntax.GenericTypeAnnotation,id:id,typeParameters:typeParameters}},createQualifiedTypeIdentifier:function(qualification,id){return{type:Syntax.QualifiedTypeIdentifier,qualification:qualification,id:id}},createTypeParameterDeclaration:function(params){return{type:Syntax.TypeParameterDeclaration,params:params}},createTypeParameterInstantiation:function(params){return{type:Syntax.TypeParameterInstantiation,params:params}},createAnyTypeAnnotation:function(){return{type:Syntax.AnyTypeAnnotation}},createBooleanTypeAnnotation:function(){return{type:Syntax.BooleanTypeAnnotation}},createNumberTypeAnnotation:function(){return{type:Syntax.NumberTypeAnnotation}},createStringTypeAnnotation:function(){return{type:Syntax.StringTypeAnnotation}},createStringLiteralTypeAnnotation:function(token){return{type:Syntax.StringLiteralTypeAnnotation,value:token.value,raw:source.slice(token.range[0],token.range[1])}},createVoidTypeAnnotation:function(){return{type:Syntax.VoidTypeAnnotation}},createTypeofTypeAnnotation:function(argument){return{type:Syntax.TypeofTypeAnnotation,argument:argument}},createTupleTypeAnnotation:function(types){return{type:Syntax.TupleTypeAnnotation,types:types}},createObjectTypeAnnotation:function(properties,indexers,callProperties){return{type:Syntax.ObjectTypeAnnotation,properties:properties,indexers:indexers,callProperties:callProperties}},createObjectTypeIndexer:function(id,key,value,isStatic){return{type:Syntax.ObjectTypeIndexer,id:id,key:key,value:value,"static":isStatic}},createObjectTypeCallProperty:function(value,isStatic){return{type:Syntax.ObjectTypeCallProperty,value:value,"static":isStatic}},createObjectTypeProperty:function(key,value,optional,isStatic){return{type:Syntax.ObjectTypeProperty,key:key,value:value,optional:optional,"static":isStatic}},createUnionTypeAnnotation:function(types){return{type:Syntax.UnionTypeAnnotation,types:types}},createIntersectionTypeAnnotation:function(types){return{type:Syntax.IntersectionTypeAnnotation,types:types}},createTypeAlias:function(id,typeParameters,right){return{type:Syntax.TypeAlias,id:id,typeParameters:typeParameters,right:right}},createInterface:function(id,typeParameters,body,extended){return{type:Syntax.InterfaceDeclaration,id:id,typeParameters:typeParameters,body:body,"extends":extended}},createInterfaceExtends:function(id,typeParameters){return{type:Syntax.InterfaceExtends,id:id,typeParameters:typeParameters}},createDeclareFunction:function(id){return{type:Syntax.DeclareFunction,id:id}},createDeclareVariable:function(id){return{type:Syntax.DeclareVariable,id:id}},createDeclareModule:function(id,body){return{type:Syntax.DeclareModule,id:id,body:body}},createXJSAttribute:function(name,value){return{type:Syntax.XJSAttribute,name:name,value:value||null}},createXJSSpreadAttribute:function(argument){return{type:Syntax.XJSSpreadAttribute,argument:argument}},createXJSIdentifier:function(name){return{type:Syntax.XJSIdentifier,name:name} },createXJSNamespacedName:function(namespace,name){return{type:Syntax.XJSNamespacedName,namespace:namespace,name:name}},createXJSMemberExpression:function(object,property){return{type:Syntax.XJSMemberExpression,object:object,property:property}},createXJSElement:function(openingElement,closingElement,children){return{type:Syntax.XJSElement,openingElement:openingElement,closingElement:closingElement,children:children}},createXJSEmptyExpression:function(){return{type:Syntax.XJSEmptyExpression}},createXJSExpressionContainer:function(expression){return{type:Syntax.XJSExpressionContainer,expression:expression}},createXJSOpeningElement:function(name,attributes,selfClosing){return{type:Syntax.XJSOpeningElement,name:name,selfClosing:selfClosing,attributes:attributes}},createXJSClosingElement:function(name){return{type:Syntax.XJSClosingElement,name:name}},createIfStatement:function(test,consequent,alternate){return{type:Syntax.IfStatement,test:test,consequent:consequent,alternate:alternate}},createLabeledStatement:function(label,body){return{type:Syntax.LabeledStatement,label:label,body:body}},createLiteral:function(token){var object={type:Syntax.Literal,value:token.value,raw:source.slice(token.range[0],token.range[1])};if(token.regex){object.regex=token.regex}return object},createMemberExpression:function(accessor,object,property){return{type:Syntax.MemberExpression,computed:accessor==="[",object:object,property:property}},createNewExpression:function(callee,args){return{type:Syntax.NewExpression,callee:callee,arguments:args}},createObjectExpression:function(properties){return{type:Syntax.ObjectExpression,properties:properties}},createPostfixExpression:function(operator,argument){return{type:Syntax.UpdateExpression,operator:operator,argument:argument,prefix:false}},createProgram:function(body){return{type:Syntax.Program,body:body}},createProperty:function(kind,key,value,method,shorthand,computed){return{type:Syntax.Property,key:key,value:value,kind:kind,method:method,shorthand:shorthand,computed:computed}},createReturnStatement:function(argument){return{type:Syntax.ReturnStatement,argument:argument}},createSequenceExpression:function(expressions){return{type:Syntax.SequenceExpression,expressions:expressions}},createSwitchCase:function(test,consequent){return{type:Syntax.SwitchCase,test:test,consequent:consequent}},createSwitchStatement:function(discriminant,cases){return{type:Syntax.SwitchStatement,discriminant:discriminant,cases:cases}},createThisExpression:function(){return{type:Syntax.ThisExpression}},createThrowStatement:function(argument){return{type:Syntax.ThrowStatement,argument:argument}},createTryStatement:function(block,guardedHandlers,handlers,finalizer){return{type:Syntax.TryStatement,block:block,guardedHandlers:guardedHandlers,handlers:handlers,finalizer:finalizer}},createUnaryExpression:function(operator,argument){if(operator==="++"||operator==="--"){return{type:Syntax.UpdateExpression,operator:operator,argument:argument,prefix:true}}return{type:Syntax.UnaryExpression,operator:operator,argument:argument,prefix:true}},createVariableDeclaration:function(declarations,kind){return{type:Syntax.VariableDeclaration,declarations:declarations,kind:kind}},createVariableDeclarator:function(id,init){return{type:Syntax.VariableDeclarator,id:id,init:init}},createWhileStatement:function(test,body){return{type:Syntax.WhileStatement,test:test,body:body}},createWithStatement:function(object,body){return{type:Syntax.WithStatement,object:object,body:body}},createTemplateElement:function(value,tail){return{type:Syntax.TemplateElement,value:value,tail:tail}},createTemplateLiteral:function(quasis,expressions){return{type:Syntax.TemplateLiteral,quasis:quasis,expressions:expressions}},createSpreadElement:function(argument){return{type:Syntax.SpreadElement,argument:argument}},createSpreadProperty:function(argument){return{type:Syntax.SpreadProperty,argument:argument}},createTaggedTemplateExpression:function(tag,quasi){return{type:Syntax.TaggedTemplateExpression,tag:tag,quasi:quasi}},createArrowFunctionExpression:function(params,defaults,body,rest,expression,isAsync){var arrowExpr={type:Syntax.ArrowFunctionExpression,id:null,params:params,defaults:defaults,body:body,rest:rest,generator:false,expression:expression};if(isAsync){arrowExpr.async=true}return arrowExpr},createMethodDefinition:function(propertyType,kind,key,value){return{type:Syntax.MethodDefinition,key:key,value:value,kind:kind,"static":propertyType===ClassPropertyType.static}},createClassProperty:function(key,typeAnnotation,computed,isStatic){return{type:Syntax.ClassProperty,key:key,typeAnnotation:typeAnnotation,computed:computed,"static":isStatic}},createClassBody:function(body){return{type:Syntax.ClassBody,body:body}},createClassImplements:function(id,typeParameters){return{type:Syntax.ClassImplements,id:id,typeParameters:typeParameters}},createClassExpression:function(id,superClass,body,typeParameters,superTypeParameters,implemented){return{type:Syntax.ClassExpression,id:id,superClass:superClass,body:body,typeParameters:typeParameters,superTypeParameters:superTypeParameters,"implements":implemented}},createClassDeclaration:function(id,superClass,body,typeParameters,superTypeParameters,implemented){return{type:Syntax.ClassDeclaration,id:id,superClass:superClass,body:body,typeParameters:typeParameters,superTypeParameters:superTypeParameters,"implements":implemented}},createModuleSpecifier:function(token){return{type:Syntax.ModuleSpecifier,value:token.value,raw:source.slice(token.range[0],token.range[1])}},createExportSpecifier:function(id,name){return{type:Syntax.ExportSpecifier,id:id,name:name}},createExportBatchSpecifier:function(){return{type:Syntax.ExportBatchSpecifier}},createImportDefaultSpecifier:function(id){return{type:Syntax.ImportDefaultSpecifier,id:id}},createImportNamespaceSpecifier:function(id){return{type:Syntax.ImportNamespaceSpecifier,id:id}},createExportDeclaration:function(isDefault,declaration,specifiers,source){return{type:Syntax.ExportDeclaration,"default":!!isDefault,declaration:declaration,specifiers:specifiers,source:source}},createImportSpecifier:function(id,name){return{type:Syntax.ImportSpecifier,id:id,name:name}},createImportDeclaration:function(specifiers,source){return{type:Syntax.ImportDeclaration,specifiers:specifiers,source:source}},createYieldExpression:function(argument,delegate){return{type:Syntax.YieldExpression,argument:argument,delegate:delegate}},createAwaitExpression:function(argument){return{type:Syntax.AwaitExpression,argument:argument}},createComprehensionExpression:function(filter,blocks,body){return{type:Syntax.ComprehensionExpression,filter:filter,blocks:blocks,body:body}}};function peekLineTerminator(){var pos,line,start,found;pos=index;line=lineNumber;start=lineStart;skipComment();found=lineNumber!==line;index=pos;lineNumber=line;lineStart=start;return found}function throwError(token,messageFormat){var error,args=Array.prototype.slice.call(arguments,2),msg=messageFormat.replace(/%(\d)/g,function(whole,index){assert(index<args.length,"Message reference must be in range");return args[index]});if(typeof token.lineNumber==="number"){error=new Error("Line "+token.lineNumber+": "+msg);error.index=token.range[0];error.lineNumber=token.lineNumber;error.column=token.range[0]-lineStart+1}else{error=new Error("Line "+lineNumber+": "+msg);error.index=index;error.lineNumber=lineNumber;error.column=index-lineStart+1}error.description=msg;throw error}function throwErrorTolerant(){try{throwError.apply(null,arguments)}catch(e){if(extra.errors){extra.errors.push(e)}else{throw e}}}function throwUnexpected(token){if(token.type===Token.EOF){throwError(token,Messages.UnexpectedEOS)}if(token.type===Token.NumericLiteral){throwError(token,Messages.UnexpectedNumber)}if(token.type===Token.StringLiteral||token.type===Token.XJSText){throwError(token,Messages.UnexpectedString)}if(token.type===Token.Identifier){throwError(token,Messages.UnexpectedIdentifier)}if(token.type===Token.Keyword){if(isFutureReservedWord(token.value)){throwError(token,Messages.UnexpectedReserved)}else if(strict&&isStrictModeReservedWord(token.value)){throwErrorTolerant(token,Messages.StrictReservedWord);return}throwError(token,Messages.UnexpectedToken,token.value)}if(token.type===Token.Template){throwError(token,Messages.UnexpectedTemplate,token.value.raw)}throwError(token,Messages.UnexpectedToken,token.value)}function expect(value){var token=lex();if(token.type!==Token.Punctuator||token.value!==value){throwUnexpected(token)}}function expectKeyword(keyword,contextual){var token=lex();if(token.type!==(contextual?Token.Identifier:Token.Keyword)||token.value!==keyword){throwUnexpected(token)}}function expectContextualKeyword(keyword){return expectKeyword(keyword,true)}function match(value){return lookahead.type===Token.Punctuator&&lookahead.value===value}function matchKeyword(keyword,contextual){var expectedType=contextual?Token.Identifier:Token.Keyword;return lookahead.type===expectedType&&lookahead.value===keyword}function matchContextualKeyword(keyword){return matchKeyword(keyword,true)}function matchAssign(){var op;if(lookahead.type!==Token.Punctuator){return false}op=lookahead.value;return op==="="||op==="*="||op==="/="||op==="%="||op==="+="||op==="-="||op==="<<="||op===">>="||op===">>>="||op==="&="||op==="^="||op==="|="}function matchYield(){return state.yieldAllowed&&matchKeyword("yield",!strict)}function matchAsync(){var backtrackToken=lookahead,matches=false;if(matchContextualKeyword("async")){lex();matches=!peekLineTerminator();rewind(backtrackToken)}return matches}function matchAwait(){return state.awaitAllowed&&matchContextualKeyword("await")}function consumeSemicolon(){var line,oldIndex=index,oldLineNumber=lineNumber,oldLineStart=lineStart,oldLookahead=lookahead;if(source.charCodeAt(index)===59){lex();return}line=lineNumber;skipComment();if(lineNumber!==line){index=oldIndex;lineNumber=oldLineNumber;lineStart=oldLineStart;lookahead=oldLookahead;return}if(match(";")){lex();return}if(lookahead.type!==Token.EOF&&!match("}")){throwUnexpected(lookahead)}}function isLeftHandSide(expr){return expr.type===Syntax.Identifier||expr.type===Syntax.MemberExpression}function isAssignableLeftHandSide(expr){return isLeftHandSide(expr)||expr.type===Syntax.ObjectPattern||expr.type===Syntax.ArrayPattern}function parseArrayInitialiser(){var elements=[],blocks=[],filter=null,tmp,possiblecomprehension=true,body,marker=markerCreate();expect("[");while(!match("]")){if(lookahead.value==="for"&&lookahead.type===Token.Keyword){if(!possiblecomprehension){throwError({},Messages.ComprehensionError)}matchKeyword("for");tmp=parseForStatement({ignoreBody:true});tmp.of=tmp.type===Syntax.ForOfStatement;tmp.type=Syntax.ComprehensionBlock;if(tmp.left.kind){throwError({},Messages.ComprehensionError)}blocks.push(tmp)}else if(lookahead.value==="if"&&lookahead.type===Token.Keyword){if(!possiblecomprehension){throwError({},Messages.ComprehensionError)}expectKeyword("if");expect("(");filter=parseExpression();expect(")")}else if(lookahead.value===","&&lookahead.type===Token.Punctuator){possiblecomprehension=false;lex();elements.push(null)}else{tmp=parseSpreadOrAssignmentExpression();elements.push(tmp);if(tmp&&tmp.type===Syntax.SpreadElement){if(!match("]")){throwError({},Messages.ElementAfterSpreadElement)}}else if(!(match("]")||matchKeyword("for")||matchKeyword("if"))){expect(",");possiblecomprehension=false}}}expect("]");if(filter&&!blocks.length){throwError({},Messages.ComprehensionRequiresBlock)}if(blocks.length){if(elements.length!==1){throwError({},Messages.ComprehensionError)}return markerApply(marker,delegate.createComprehensionExpression(filter,blocks,elements[0]))}return markerApply(marker,delegate.createArrayExpression(elements))}function parsePropertyFunction(options){var previousStrict,previousYieldAllowed,previousAwaitAllowed,params,defaults,body,marker=markerCreate();previousStrict=strict;previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=options.generator;previousAwaitAllowed=state.awaitAllowed;state.awaitAllowed=options.async;params=options.params||[];defaults=options.defaults||[];body=parseConciseBody();if(options.name&&strict&&isRestrictedWord(params[0].name)){throwErrorTolerant(options.name,Messages.StrictParamName)}strict=previousStrict;state.yieldAllowed=previousYieldAllowed;state.awaitAllowed=previousAwaitAllowed;return markerApply(marker,delegate.createFunctionExpression(null,params,defaults,body,options.rest||null,options.generator,body.type!==Syntax.BlockStatement,options.async,options.returnType,options.typeParameters))}function parsePropertyMethodFunction(options){var previousStrict,tmp,method;previousStrict=strict;strict=true;tmp=parseParams();if(tmp.stricted){throwErrorTolerant(tmp.stricted,tmp.message)}method=parsePropertyFunction({params:tmp.params,defaults:tmp.defaults,rest:tmp.rest,generator:options.generator,async:options.async,returnType:tmp.returnType,typeParameters:options.typeParameters});strict=previousStrict;return method}function parseObjectPropertyKey(){var marker=markerCreate(),token=lex(),propertyKey,result;if(token.type===Token.StringLiteral||token.type===Token.NumericLiteral){if(strict&&token.octal){throwErrorTolerant(token,Messages.StrictOctalLiteral)}return markerApply(marker,delegate.createLiteral(token))}if(token.type===Token.Punctuator&&token.value==="["){marker=markerCreate();propertyKey=parseAssignmentExpression();result=markerApply(marker,propertyKey);expect("]");return result}return markerApply(marker,delegate.createIdentifier(token.value))}function parseObjectProperty(){var token,key,id,value,param,expr,computed,marker=markerCreate(),returnType;token=lookahead;computed=token.value==="[";if(token.type===Token.Identifier||computed||matchAsync()){id=parseObjectPropertyKey();if(match(":")){lex();return markerApply(marker,delegate.createProperty("init",id,parseAssignmentExpression(),false,false,computed))}if(match("(")){return markerApply(marker,delegate.createProperty("init",id,parsePropertyMethodFunction({generator:false,async:false}),true,false,computed))}if(token.value==="get"){computed=lookahead.value==="[";key=parseObjectPropertyKey();expect("(");expect(")");if(match(":")){returnType=parseTypeAnnotation()}return markerApply(marker,delegate.createProperty("get",key,parsePropertyFunction({generator:false,async:false,returnType:returnType}),false,false,computed))}if(token.value==="set"){computed=lookahead.value==="[";key=parseObjectPropertyKey();expect("(");token=lookahead;param=[parseTypeAnnotatableIdentifier()];expect(")");if(match(":")){returnType=parseTypeAnnotation()}return markerApply(marker,delegate.createProperty("set",key,parsePropertyFunction({params:param,generator:false,async:false,name:token,returnType:returnType}),false,false,computed))}if(token.value==="async"){computed=lookahead.value==="[";key=parseObjectPropertyKey();return markerApply(marker,delegate.createProperty("init",key,parsePropertyMethodFunction({generator:false,async:true}),true,false,computed))}if(computed){throwUnexpected(lookahead)}return markerApply(marker,delegate.createProperty("init",id,id,false,true,false))}if(token.type===Token.EOF||token.type===Token.Punctuator){if(!match("*")){throwUnexpected(token)}lex();computed=lookahead.type===Token.Punctuator&&lookahead.value==="[";id=parseObjectPropertyKey();if(!match("(")){throwUnexpected(lex())}return markerApply(marker,delegate.createProperty("init",id,parsePropertyMethodFunction({generator:true}),true,false,computed))}key=parseObjectPropertyKey();if(match(":")){lex();return markerApply(marker,delegate.createProperty("init",key,parseAssignmentExpression(),false,false,false))}if(match("(")){return markerApply(marker,delegate.createProperty("init",key,parsePropertyMethodFunction({generator:false}),true,false,false))}throwUnexpected(lex())}function parseObjectSpreadProperty(){var marker=markerCreate();expect("...");return markerApply(marker,delegate.createSpreadProperty(parseAssignmentExpression()))}function parseObjectInitialiser(){var properties=[],property,name,key,kind,map={},toString=String,marker=markerCreate();expect("{");while(!match("}")){if(match("...")){property=parseObjectSpreadProperty()}else{property=parseObjectProperty();if(property.key.type===Syntax.Identifier){name=property.key.name}else{name=toString(property.key.value)}kind=property.kind==="init"?PropertyKind.Data:property.kind==="get"?PropertyKind.Get:PropertyKind.Set;key="$"+name;if(Object.prototype.hasOwnProperty.call(map,key)){if(map[key]===PropertyKind.Data){if(strict&&kind===PropertyKind.Data){throwErrorTolerant({},Messages.StrictDuplicateProperty)}else if(kind!==PropertyKind.Data){throwErrorTolerant({},Messages.AccessorDataProperty)}}else{if(kind===PropertyKind.Data){throwErrorTolerant({},Messages.AccessorDataProperty)}else if(map[key]&kind){throwErrorTolerant({},Messages.AccessorGetSet)}}map[key]|=kind}else{map[key]=kind}}properties.push(property);if(!match("}")){expect(",")}}expect("}");return markerApply(marker,delegate.createObjectExpression(properties))}function parseTemplateElement(option){var marker=markerCreate(),token=scanTemplateElement(option);if(strict&&token.octal){throwError(token,Messages.StrictOctalLiteral)}return markerApply(marker,delegate.createTemplateElement({raw:token.value.raw,cooked:token.value.cooked},token.tail))}function parseTemplateLiteral(){var quasi,quasis,expressions,marker=markerCreate();quasi=parseTemplateElement({head:true});quasis=[quasi];expressions=[];while(!quasi.tail){expressions.push(parseExpression());quasi=parseTemplateElement({head:false});quasis.push(quasi)}return markerApply(marker,delegate.createTemplateLiteral(quasis,expressions))}function parseGroupExpression(){var expr;expect("(");++state.parenthesizedCount;expr=parseExpression();expect(")");return expr}function matchAsyncFuncExprOrDecl(){var token;if(matchAsync()){token=lookahead2();if(token.type===Token.Keyword&&token.value==="function"){return true}}return false}function parsePrimaryExpression(){var marker,type,token,expr;type=lookahead.type;if(type===Token.Identifier){marker=markerCreate();return markerApply(marker,delegate.createIdentifier(lex().value))}if(type===Token.StringLiteral||type===Token.NumericLiteral){if(strict&&lookahead.octal){throwErrorTolerant(lookahead,Messages.StrictOctalLiteral)}marker=markerCreate();return markerApply(marker,delegate.createLiteral(lex()))}if(type===Token.Keyword){if(matchKeyword("this")){marker=markerCreate();lex();return markerApply(marker,delegate.createThisExpression())}if(matchKeyword("function")){return parseFunctionExpression()}if(matchKeyword("class")){return parseClassExpression()}if(matchKeyword("super")){marker=markerCreate();lex();return markerApply(marker,delegate.createIdentifier("super"))}}if(type===Token.BooleanLiteral){marker=markerCreate();token=lex();token.value=token.value==="true";return markerApply(marker,delegate.createLiteral(token))}if(type===Token.NullLiteral){marker=markerCreate();token=lex();token.value=null;return markerApply(marker,delegate.createLiteral(token))}if(match("[")){return parseArrayInitialiser()}if(match("{")){return parseObjectInitialiser()}if(match("(")){return parseGroupExpression()}if(match("/")||match("/=")){marker=markerCreate();return markerApply(marker,delegate.createLiteral(scanRegExp()))}if(type===Token.Template){return parseTemplateLiteral()}if(match("<")){return parseXJSElement()}throwUnexpected(lex())}function parseArguments(){var args=[],arg;expect("(");if(!match(")")){while(index<length){arg=parseSpreadOrAssignmentExpression();args.push(arg);if(match(")")){break}else if(arg.type===Syntax.SpreadElement){throwError({},Messages.ElementAfterSpreadElement)}expect(",")}}expect(")");return args}function parseSpreadOrAssignmentExpression(){if(match("...")){var marker=markerCreate();lex();return markerApply(marker,delegate.createSpreadElement(parseAssignmentExpression()))}return parseAssignmentExpression()}function parseNonComputedProperty(){var marker=markerCreate(),token=lex();if(!isIdentifierName(token)){throwUnexpected(token)}return markerApply(marker,delegate.createIdentifier(token.value))}function parseNonComputedMember(){expect(".");return parseNonComputedProperty()}function parseComputedMember(){var expr;expect("[");expr=parseExpression();expect("]");return expr}function parseNewExpression(){var callee,args,marker=markerCreate();expectKeyword("new");callee=parseLeftHandSideExpression();args=match("(")?parseArguments():[];return markerApply(marker,delegate.createNewExpression(callee,args))}function parseLeftHandSideExpressionAllowCall(){var expr,args,marker=markerCreate();expr=matchKeyword("new")?parseNewExpression():parsePrimaryExpression();while(match(".")||match("[")||match("(")||lookahead.type===Token.Template){if(match("(")){args=parseArguments();expr=markerApply(marker,delegate.createCallExpression(expr,args))}else if(match("[")){expr=markerApply(marker,delegate.createMemberExpression("[",expr,parseComputedMember()))}else if(match(".")){expr=markerApply(marker,delegate.createMemberExpression(".",expr,parseNonComputedMember()))}else{expr=markerApply(marker,delegate.createTaggedTemplateExpression(expr,parseTemplateLiteral()))}}return expr}function parseLeftHandSideExpression(){var expr,marker=markerCreate();expr=matchKeyword("new")?parseNewExpression():parsePrimaryExpression();while(match(".")||match("[")||lookahead.type===Token.Template){if(match("[")){expr=markerApply(marker,delegate.createMemberExpression("[",expr,parseComputedMember()))}else if(match(".")){expr=markerApply(marker,delegate.createMemberExpression(".",expr,parseNonComputedMember()))}else{expr=markerApply(marker,delegate.createTaggedTemplateExpression(expr,parseTemplateLiteral()))}}return expr}function parsePostfixExpression(){var marker=markerCreate(),expr=parseLeftHandSideExpressionAllowCall(),token;if(lookahead.type!==Token.Punctuator){return expr}if((match("++")||match("--"))&&!peekLineTerminator()){if(strict&&expr.type===Syntax.Identifier&&isRestrictedWord(expr.name)){throwErrorTolerant({},Messages.StrictLHSPostfix)}if(!isLeftHandSide(expr)){throwError({},Messages.InvalidLHSInAssignment)}token=lex();expr=markerApply(marker,delegate.createPostfixExpression(token.value,expr))}return expr}function parseUnaryExpression(){var marker,token,expr;if(lookahead.type!==Token.Punctuator&&lookahead.type!==Token.Keyword){return parsePostfixExpression()}if(match("++")||match("--")){marker=markerCreate();token=lex();expr=parseUnaryExpression();if(strict&&expr.type===Syntax.Identifier&&isRestrictedWord(expr.name)){throwErrorTolerant({},Messages.StrictLHSPrefix)}if(!isLeftHandSide(expr)){throwError({},Messages.InvalidLHSInAssignment)}return markerApply(marker,delegate.createUnaryExpression(token.value,expr))}if(match("+")||match("-")||match("~")||match("!")){marker=markerCreate();token=lex();expr=parseUnaryExpression();return markerApply(marker,delegate.createUnaryExpression(token.value,expr))}if(matchKeyword("delete")||matchKeyword("void")||matchKeyword("typeof")){marker=markerCreate();token=lex();expr=parseUnaryExpression();expr=markerApply(marker,delegate.createUnaryExpression(token.value,expr));if(strict&&expr.operator==="delete"&&expr.argument.type===Syntax.Identifier){throwErrorTolerant({},Messages.StrictDelete)}return expr}return parsePostfixExpression()}function binaryPrecedence(token,allowIn){var prec=0;if(token.type!==Token.Punctuator&&token.type!==Token.Keyword){return 0}switch(token.value){case"||":prec=1;break;case"&&":prec=2;break;case"|":prec=3;break;case"^":prec=4;break;case"&":prec=5;break;case"==":case"!=":case"===":case"!==":prec=6;break;case"<":case">":case"<=":case">=":case"instanceof":prec=7;break;case"in":prec=allowIn?7:0;break;case"<<":case">>":case">>>":prec=8;break;case"+":case"-":prec=9;break;case"*":case"/":case"%":prec=11;break;default:break}return prec}function parseBinaryExpression(){var expr,token,prec,previousAllowIn,stack,right,operator,left,i,marker,markers;previousAllowIn=state.allowIn;state.allowIn=true;marker=markerCreate();left=parseUnaryExpression();token=lookahead;prec=binaryPrecedence(token,previousAllowIn);if(prec===0){return left}token.prec=prec;lex();markers=[marker,markerCreate()];right=parseUnaryExpression();stack=[left,token,right];while((prec=binaryPrecedence(lookahead,previousAllowIn))>0){while(stack.length>2&&prec<=stack[stack.length-2].prec){right=stack.pop();operator=stack.pop().value;left=stack.pop();expr=delegate.createBinaryExpression(operator,left,right);markers.pop();marker=markers.pop();markerApply(marker,expr);stack.push(expr);markers.push(marker)}token=lex();token.prec=prec;stack.push(token);markers.push(markerCreate());expr=parseUnaryExpression();stack.push(expr)}state.allowIn=previousAllowIn;i=stack.length-1;expr=stack[i];markers.pop();while(i>1){expr=delegate.createBinaryExpression(stack[i-1].value,stack[i-2],expr);i-=2;marker=markers.pop();markerApply(marker,expr)}return expr}function parseConditionalExpression(){var expr,previousAllowIn,consequent,alternate,marker=markerCreate();expr=parseBinaryExpression();if(match("?")){lex();previousAllowIn=state.allowIn;state.allowIn=true;consequent=parseAssignmentExpression();state.allowIn=previousAllowIn;expect(":");alternate=parseAssignmentExpression();expr=markerApply(marker,delegate.createConditionalExpression(expr,consequent,alternate))}return expr}function reinterpretAsAssignmentBindingPattern(expr){var i,len,property,element;if(expr.type===Syntax.ObjectExpression){expr.type=Syntax.ObjectPattern;for(i=0,len=expr.properties.length;i<len;i+=1){property=expr.properties[i];if(property.type===Syntax.SpreadProperty){if(i<len-1){throwError({},Messages.PropertyAfterSpreadProperty)}reinterpretAsAssignmentBindingPattern(property.argument)}else{if(property.kind!=="init"){throwError({},Messages.InvalidLHSInAssignment)}reinterpretAsAssignmentBindingPattern(property.value)}}}else if(expr.type===Syntax.ArrayExpression){expr.type=Syntax.ArrayPattern;for(i=0,len=expr.elements.length;i<len;i+=1){element=expr.elements[i];if(element){reinterpretAsAssignmentBindingPattern(element)}}}else if(expr.type===Syntax.Identifier){if(isRestrictedWord(expr.name)){throwError({},Messages.InvalidLHSInAssignment)}}else if(expr.type===Syntax.SpreadElement){reinterpretAsAssignmentBindingPattern(expr.argument);if(expr.argument.type===Syntax.ObjectPattern){throwError({},Messages.ObjectPatternAsSpread)}}else{if(expr.type!==Syntax.MemberExpression&&expr.type!==Syntax.CallExpression&&expr.type!==Syntax.NewExpression){throwError({},Messages.InvalidLHSInAssignment)}}}function reinterpretAsDestructuredParameter(options,expr){var i,len,property,element;if(expr.type===Syntax.ObjectExpression){expr.type=Syntax.ObjectPattern;for(i=0,len=expr.properties.length;i<len;i+=1){property=expr.properties[i];if(property.type===Syntax.SpreadProperty){if(i<len-1){throwError({},Messages.PropertyAfterSpreadProperty)}reinterpretAsDestructuredParameter(options,property.argument)}else{if(property.kind!=="init"){throwError({},Messages.InvalidLHSInFormalsList)}reinterpretAsDestructuredParameter(options,property.value)}}}else if(expr.type===Syntax.ArrayExpression){expr.type=Syntax.ArrayPattern;for(i=0,len=expr.elements.length;i<len;i+=1){element=expr.elements[i];if(element){reinterpretAsDestructuredParameter(options,element)}}}else if(expr.type===Syntax.Identifier){validateParam(options,expr,expr.name)}else{if(expr.type!==Syntax.MemberExpression){throwError({},Messages.InvalidLHSInFormalsList)}}}function reinterpretAsCoverFormalsList(expressions){var i,len,param,params,defaults,defaultCount,options,rest;params=[];defaults=[];defaultCount=0;rest=null;options={paramSet:{}};for(i=0,len=expressions.length;i<len;i+=1){param=expressions[i];if(param.type===Syntax.Identifier){params.push(param);defaults.push(null);validateParam(options,param,param.name)}else if(param.type===Syntax.ObjectExpression||param.type===Syntax.ArrayExpression){reinterpretAsDestructuredParameter(options,param);params.push(param);defaults.push(null)}else if(param.type===Syntax.SpreadElement){assert(i===len-1,"It is guaranteed that SpreadElement is last element by parseExpression");reinterpretAsDestructuredParameter(options,param.argument);rest=param.argument}else if(param.type===Syntax.AssignmentExpression){params.push(param.left);defaults.push(param.right);++defaultCount;validateParam(options,param.left,param.left.name)}else{return null}}if(options.message===Messages.StrictParamDupe){throwError(strict?options.stricted:options.firstRestricted,options.message)}if(defaultCount===0){defaults=[]}return{params:params,defaults:defaults,rest:rest,stricted:options.stricted,firstRestricted:options.firstRestricted,message:options.message}}function parseArrowFunctionExpression(options,marker){var previousStrict,previousYieldAllowed,previousAwaitAllowed,body;expect("=>");previousStrict=strict;previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=false;previousAwaitAllowed=state.awaitAllowed;state.awaitAllowed=!!options.async;body=parseConciseBody();if(strict&&options.firstRestricted){throwError(options.firstRestricted,options.message)}if(strict&&options.stricted){throwErrorTolerant(options.stricted,options.message)}strict=previousStrict;state.yieldAllowed=previousYieldAllowed;state.awaitAllowed=previousAwaitAllowed;return markerApply(marker,delegate.createArrowFunctionExpression(options.params,options.defaults,body,options.rest,body.type!==Syntax.BlockStatement,!!options.async))}function parseAssignmentExpression(){var marker,expr,token,params,oldParenthesizedCount,backtrackToken=lookahead,possiblyAsync=false;if(matchYield()){return parseYieldExpression()}if(matchAwait()){return parseAwaitExpression()}oldParenthesizedCount=state.parenthesizedCount;marker=markerCreate();if(matchAsyncFuncExprOrDecl()){return parseFunctionExpression()}if(matchAsync()){possiblyAsync=true;lex()}if(match("(")){token=lookahead2();if(token.type===Token.Punctuator&&token.value===")"||token.value==="..."){params=parseParams();if(!match("=>")){throwUnexpected(lex())}params.async=possiblyAsync;return parseArrowFunctionExpression(params,marker)}}token=lookahead;if(possiblyAsync&&!match("(")&&token.type!==Token.Identifier){possiblyAsync=false;rewind(backtrackToken)}expr=parseConditionalExpression();if(match("=>")&&(state.parenthesizedCount===oldParenthesizedCount||state.parenthesizedCount===oldParenthesizedCount+1)){if(expr.type===Syntax.Identifier){params=reinterpretAsCoverFormalsList([expr])}else if(expr.type===Syntax.SequenceExpression){params=reinterpretAsCoverFormalsList(expr.expressions)}if(params){params.async=possiblyAsync;return parseArrowFunctionExpression(params,marker)}}if(possiblyAsync){possiblyAsync=false;rewind(backtrackToken);expr=parseConditionalExpression()}if(matchAssign()){if(strict&&expr.type===Syntax.Identifier&&isRestrictedWord(expr.name)){throwErrorTolerant(token,Messages.StrictLHSAssignment)}if(match("=")&&(expr.type===Syntax.ObjectExpression||expr.type===Syntax.ArrayExpression)){reinterpretAsAssignmentBindingPattern(expr)}else if(!isLeftHandSide(expr)){throwError({},Messages.InvalidLHSInAssignment)}expr=markerApply(marker,delegate.createAssignmentExpression(lex().value,expr,parseAssignmentExpression()))}return expr}function parseExpression(){var marker,expr,expressions,sequence,coverFormalsList,spreadFound,oldParenthesizedCount;oldParenthesizedCount=state.parenthesizedCount;marker=markerCreate();expr=parseAssignmentExpression();expressions=[expr];if(match(",")){while(index<length){if(!match(",")){break}lex();expr=parseSpreadOrAssignmentExpression();expressions.push(expr);if(expr.type===Syntax.SpreadElement){spreadFound=true;if(!match(")")){throwError({},Messages.ElementAfterSpreadElement)}break}}sequence=markerApply(marker,delegate.createSequenceExpression(expressions))}if(match("=>")){if(state.parenthesizedCount===oldParenthesizedCount||state.parenthesizedCount===oldParenthesizedCount+1){expr=expr.type===Syntax.SequenceExpression?expr.expressions:expressions;coverFormalsList=reinterpretAsCoverFormalsList(expr); if(coverFormalsList){return parseArrowFunctionExpression(coverFormalsList,marker)}}throwUnexpected(lex())}if(spreadFound&&lookahead2().value!=="=>"){throwError({},Messages.IllegalSpread)}return sequence||expr}function parseStatementList(){var list=[],statement;while(index<length){if(match("}")){break}statement=parseSourceElement();if(typeof statement==="undefined"){break}list.push(statement)}return list}function parseBlock(){var block,marker=markerCreate();expect("{");block=parseStatementList();expect("}");return markerApply(marker,delegate.createBlockStatement(block))}function parseTypeParameterDeclaration(){var marker=markerCreate(),paramTypes=[];expect("<");while(!match(">")){paramTypes.push(parseVariableIdentifier());if(!match(">")){expect(",")}}expect(">");return markerApply(marker,delegate.createTypeParameterDeclaration(paramTypes))}function parseTypeParameterInstantiation(){var marker=markerCreate(),oldInType=state.inType,paramTypes=[];state.inType=true;expect("<");while(!match(">")){paramTypes.push(parseType());if(!match(">")){expect(",")}}expect(">");state.inType=oldInType;return markerApply(marker,delegate.createTypeParameterInstantiation(paramTypes))}function parseObjectTypeIndexer(marker,isStatic){var id,key,value;expect("[");id=parseObjectPropertyKey();expect(":");key=parseType();expect("]");expect(":");value=parseType();return markerApply(marker,delegate.createObjectTypeIndexer(id,key,value,isStatic))}function parseObjectTypeMethodish(marker){var params=[],rest=null,returnType,typeParameters=null;if(match("<")){typeParameters=parseTypeParameterDeclaration()}expect("(");while(lookahead.type===Token.Identifier){params.push(parseFunctionTypeParam());if(!match(")")){expect(",")}}if(match("...")){lex();rest=parseFunctionTypeParam()}expect(")");expect(":");returnType=parseType();return markerApply(marker,delegate.createFunctionTypeAnnotation(params,returnType,rest,typeParameters))}function parseObjectTypeMethod(marker,isStatic,key){var optional=false,value;value=parseObjectTypeMethodish(marker);return markerApply(marker,delegate.createObjectTypeProperty(key,value,optional,isStatic))}function parseObjectTypeCallProperty(marker,isStatic){var valueMarker=markerCreate();return markerApply(marker,delegate.createObjectTypeCallProperty(parseObjectTypeMethodish(valueMarker),isStatic))}function parseObjectType(allowStatic){var callProperties=[],indexers=[],marker,optional=false,properties=[],property,propertyKey,propertyTypeAnnotation,token,isStatic;expect("{");while(!match("}")){marker=markerCreate();if(allowStatic&&matchContextualKeyword("static")){token=lex();isStatic=true}if(match("[")){indexers.push(parseObjectTypeIndexer(marker,isStatic))}else if(match("(")||match("<")){callProperties.push(parseObjectTypeCallProperty(marker,allowStatic))}else{if(isStatic&&match(":")){propertyKey=markerApply(marker,delegate.createIdentifier(token));throwErrorTolerant(token,Messages.StrictReservedWord)}else{propertyKey=parseObjectPropertyKey()}if(match("<")||match("(")){properties.push(parseObjectTypeMethod(marker,isStatic,propertyKey))}else{if(match("?")){lex();optional=true}expect(":");propertyTypeAnnotation=parseType();properties.push(markerApply(marker,delegate.createObjectTypeProperty(propertyKey,propertyTypeAnnotation,optional,isStatic)))}}if(match(";")){lex()}else if(!match("}")){throwUnexpected(lookahead)}}expect("}");return delegate.createObjectTypeAnnotation(properties,indexers,callProperties)}function parseGenericType(){var marker=markerCreate(),returnType=null,typeParameters=null,typeIdentifier,typeIdentifierMarker=markerCreate;typeIdentifier=parseVariableIdentifier();while(match(".")){expect(".");typeIdentifier=markerApply(marker,delegate.createQualifiedTypeIdentifier(typeIdentifier,parseVariableIdentifier()))}if(match("<")){typeParameters=parseTypeParameterInstantiation()}return markerApply(marker,delegate.createGenericTypeAnnotation(typeIdentifier,typeParameters))}function parseVoidType(){var marker=markerCreate();expectKeyword("void");return markerApply(marker,delegate.createVoidTypeAnnotation())}function parseTypeofType(){var argument,marker=markerCreate();expectKeyword("typeof");argument=parsePrimaryType();return markerApply(marker,delegate.createTypeofTypeAnnotation(argument))}function parseTupleType(){var marker=markerCreate(),types=[];expect("[");while(index<length&&!match("]")){types.push(parseType());if(match("]")){break}expect(",")}expect("]");return markerApply(marker,delegate.createTupleTypeAnnotation(types))}function parseFunctionTypeParam(){var marker=markerCreate(),name,optional=false,typeAnnotation;name=parseVariableIdentifier();if(match("?")){lex();optional=true}expect(":");typeAnnotation=parseType();return markerApply(marker,delegate.createFunctionTypeParam(name,typeAnnotation,optional))}function parseFunctionTypeParams(){var ret={params:[],rest:null};while(lookahead.type===Token.Identifier){ret.params.push(parseFunctionTypeParam());if(!match(")")){expect(",")}}if(match("...")){lex();ret.rest=parseFunctionTypeParam()}return ret}function parsePrimaryType(){var typeIdentifier=null,params=null,returnType=null,marker=markerCreate(),rest=null,tmp,typeParameters,token,type,isGroupedType=false;switch(lookahead.type){case Token.Identifier:switch(lookahead.value){case"any":lex();return markerApply(marker,delegate.createAnyTypeAnnotation());case"bool":case"boolean":lex();return markerApply(marker,delegate.createBooleanTypeAnnotation());case"number":lex();return markerApply(marker,delegate.createNumberTypeAnnotation());case"string":lex();return markerApply(marker,delegate.createStringTypeAnnotation())}return markerApply(marker,parseGenericType());case Token.Punctuator:switch(lookahead.value){case"{":return markerApply(marker,parseObjectType());case"[":return parseTupleType();case"<":typeParameters=parseTypeParameterDeclaration();expect("(");tmp=parseFunctionTypeParams();params=tmp.params;rest=tmp.rest;expect(")");expect("=>");returnType=parseType();return markerApply(marker,delegate.createFunctionTypeAnnotation(params,returnType,rest,typeParameters));case"(":lex();if(!match(")")&&!match("...")){if(lookahead.type===Token.Identifier){token=lookahead2();isGroupedType=token.value!=="?"&&token.value!==":"}else{isGroupedType=true}}if(isGroupedType){type=parseType();expect(")");if(match("=>")){throwError({},Messages.ConfusedAboutFunctionType)}return type}tmp=parseFunctionTypeParams();params=tmp.params;rest=tmp.rest;expect(")");expect("=>");returnType=parseType();return markerApply(marker,delegate.createFunctionTypeAnnotation(params,returnType,rest,null))}break;case Token.Keyword:switch(lookahead.value){case"void":return markerApply(marker,parseVoidType());case"typeof":return markerApply(marker,parseTypeofType())}break;case Token.StringLiteral:token=lex();if(token.octal){throwError(token,Messages.StrictOctalLiteral)}return markerApply(marker,delegate.createStringLiteralTypeAnnotation(token))}throwUnexpected(lookahead)}function parsePostfixType(){var marker=markerCreate(),t=parsePrimaryType();if(match("[")){expect("[");expect("]");return markerApply(marker,delegate.createArrayTypeAnnotation(t))}return t}function parsePrefixType(){var marker=markerCreate();if(match("?")){lex();return markerApply(marker,delegate.createNullableTypeAnnotation(parsePrefixType()))}return parsePostfixType()}function parseIntersectionType(){var marker=markerCreate(),type,types;type=parsePrefixType();types=[type];while(match("&")){lex();types.push(parsePrefixType())}return types.length===1?type:markerApply(marker,delegate.createIntersectionTypeAnnotation(types))}function parseUnionType(){var marker=markerCreate(),type,types;type=parseIntersectionType();types=[type];while(match("|")){lex();types.push(parseIntersectionType())}return types.length===1?type:markerApply(marker,delegate.createUnionTypeAnnotation(types))}function parseType(){var oldInType=state.inType,type;state.inType=true;type=parseUnionType();state.inType=oldInType;return type}function parseTypeAnnotation(){var marker=markerCreate(),type;expect(":");type=parseType();return markerApply(marker,delegate.createTypeAnnotation(type))}function parseVariableIdentifier(){var marker=markerCreate(),token=lex();if(token.type!==Token.Identifier){throwUnexpected(token)}return markerApply(marker,delegate.createIdentifier(token.value))}function parseTypeAnnotatableIdentifier(requireTypeAnnotation,canBeOptionalParam){var marker=markerCreate(),ident=parseVariableIdentifier(),isOptionalParam=false;if(canBeOptionalParam&&match("?")){expect("?");isOptionalParam=true}if(requireTypeAnnotation||match(":")){ident.typeAnnotation=parseTypeAnnotation();ident=markerApply(marker,ident)}if(isOptionalParam){ident.optional=true;ident=markerApply(marker,ident)}return ident}function parseVariableDeclaration(kind){var id,marker=markerCreate(),init=null,typeAnnotationMarker=markerCreate();if(match("{")){id=parseObjectInitialiser();reinterpretAsAssignmentBindingPattern(id);if(match(":")){id.typeAnnotation=parseTypeAnnotation();markerApply(typeAnnotationMarker,id)}}else if(match("[")){id=parseArrayInitialiser();reinterpretAsAssignmentBindingPattern(id);if(match(":")){id.typeAnnotation=parseTypeAnnotation();markerApply(typeAnnotationMarker,id)}}else{id=state.allowKeyword?parseNonComputedProperty():parseTypeAnnotatableIdentifier();if(strict&&isRestrictedWord(id.name)){throwErrorTolerant({},Messages.StrictVarName)}}if(kind==="const"){if(!match("=")){throwError({},Messages.NoUnintializedConst)}expect("=");init=parseAssignmentExpression()}else if(match("=")){lex();init=parseAssignmentExpression()}return markerApply(marker,delegate.createVariableDeclarator(id,init))}function parseVariableDeclarationList(kind){var list=[];do{list.push(parseVariableDeclaration(kind));if(!match(",")){break}lex()}while(index<length);return list}function parseVariableStatement(){var declarations,marker=markerCreate();expectKeyword("var");declarations=parseVariableDeclarationList();consumeSemicolon();return markerApply(marker,delegate.createVariableDeclaration(declarations,"var"))}function parseConstLetDeclaration(kind){var declarations,marker=markerCreate();expectKeyword(kind);declarations=parseVariableDeclarationList(kind);consumeSemicolon();return markerApply(marker,delegate.createVariableDeclaration(declarations,kind))}function parseModuleSpecifier(){var marker=markerCreate(),specifier;if(lookahead.type!==Token.StringLiteral){throwError({},Messages.InvalidModuleSpecifier)}specifier=delegate.createModuleSpecifier(lookahead);lex();return markerApply(marker,specifier)}function parseExportBatchSpecifier(){var marker=markerCreate();expect("*");return markerApply(marker,delegate.createExportBatchSpecifier())}function parseExportSpecifier(){var id,name=null,marker=markerCreate(),from;if(matchKeyword("default")){lex();id=markerApply(marker,delegate.createIdentifier("default"))}else{id=parseVariableIdentifier()}if(matchContextualKeyword("as")){lex();name=parseNonComputedProperty()}return markerApply(marker,delegate.createExportSpecifier(id,name))}function parseExportDeclaration(){var backtrackToken,id,previousAllowKeyword,declaration=null,isExportFromIdentifier,src=null,specifiers=[],marker=markerCreate();expectKeyword("export");if(matchKeyword("default")){lex();if(matchKeyword("function")||matchKeyword("class")){backtrackToken=lookahead;lex();if(isIdentifierName(lookahead)){id=parseNonComputedProperty();rewind(backtrackToken);return markerApply(marker,delegate.createExportDeclaration(true,parseSourceElement(),[id],null))}rewind(backtrackToken);switch(lookahead.value){case"class":return markerApply(marker,delegate.createExportDeclaration(true,parseClassExpression(),[],null));case"function":return markerApply(marker,delegate.createExportDeclaration(true,parseFunctionExpression(),[],null))}}if(matchContextualKeyword("from")){throwError({},Messages.UnexpectedToken,lookahead.value)}if(match("{")){declaration=parseObjectInitialiser()}else if(match("[")){declaration=parseArrayInitialiser()}else{declaration=parseAssignmentExpression()}consumeSemicolon();return markerApply(marker,delegate.createExportDeclaration(true,declaration,[],null))}if(lookahead.type===Token.Keyword){switch(lookahead.value){case"let":case"const":case"var":case"class":case"function":return markerApply(marker,delegate.createExportDeclaration(false,parseSourceElement(),specifiers,null))}}if(match("*")){specifiers.push(parseExportBatchSpecifier());if(!matchContextualKeyword("from")){throwError({},lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value)}lex();src=parseModuleSpecifier();consumeSemicolon();return markerApply(marker,delegate.createExportDeclaration(false,null,specifiers,src))}expect("{");do{isExportFromIdentifier=isExportFromIdentifier||matchKeyword("default");specifiers.push(parseExportSpecifier())}while(match(",")&&lex());expect("}");if(matchContextualKeyword("from")){lex();src=parseModuleSpecifier();consumeSemicolon()}else if(isExportFromIdentifier){throwError({},lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value)}else{consumeSemicolon()}return markerApply(marker,delegate.createExportDeclaration(false,declaration,specifiers,src))}function parseImportSpecifier(){var id,name=null,marker=markerCreate();id=parseNonComputedProperty();if(matchContextualKeyword("as")){lex();name=parseVariableIdentifier()}return markerApply(marker,delegate.createImportSpecifier(id,name))}function parseNamedImports(){var specifiers=[];expect("{");do{specifiers.push(parseImportSpecifier())}while(match(",")&&lex());expect("}");return specifiers}function parseImportDefaultSpecifier(){var id,marker=markerCreate();id=parseNonComputedProperty();return markerApply(marker,delegate.createImportDefaultSpecifier(id))}function parseImportNamespaceSpecifier(){var id,marker=markerCreate();expect("*");if(!matchContextualKeyword("as")){throwError({},Messages.NoAsAfterImportNamespace)}lex();id=parseNonComputedProperty();return markerApply(marker,delegate.createImportNamespaceSpecifier(id))}function parseImportDeclaration(){var specifiers,src,marker=markerCreate();expectKeyword("import");specifiers=[];if(lookahead.type===Token.StringLiteral){src=parseModuleSpecifier();consumeSemicolon();return markerApply(marker,delegate.createImportDeclaration(specifiers,src))}if(!matchKeyword("default")&&isIdentifierName(lookahead)){specifiers.push(parseImportDefaultSpecifier());if(match(",")){lex()}}if(match("*")){specifiers.push(parseImportNamespaceSpecifier())}else if(match("{")){specifiers=specifiers.concat(parseNamedImports())}if(!matchContextualKeyword("from")){throwError({},lookahead.value?Messages.UnexpectedToken:Messages.MissingFromClause,lookahead.value)}lex();src=parseModuleSpecifier();consumeSemicolon();return markerApply(marker,delegate.createImportDeclaration(specifiers,src))}function parseEmptyStatement(){var marker=markerCreate();expect(";");return markerApply(marker,delegate.createEmptyStatement())}function parseExpressionStatement(){var marker=markerCreate(),expr=parseExpression();consumeSemicolon();return markerApply(marker,delegate.createExpressionStatement(expr))}function parseIfStatement(){var test,consequent,alternate,marker=markerCreate();expectKeyword("if");expect("(");test=parseExpression();expect(")");consequent=parseStatement();if(matchKeyword("else")){lex();alternate=parseStatement()}else{alternate=null}return markerApply(marker,delegate.createIfStatement(test,consequent,alternate))}function parseDoWhileStatement(){var body,test,oldInIteration,marker=markerCreate();expectKeyword("do");oldInIteration=state.inIteration;state.inIteration=true;body=parseStatement();state.inIteration=oldInIteration;expectKeyword("while");expect("(");test=parseExpression();expect(")");if(match(";")){lex()}return markerApply(marker,delegate.createDoWhileStatement(body,test))}function parseWhileStatement(){var test,body,oldInIteration,marker=markerCreate();expectKeyword("while");expect("(");test=parseExpression();expect(")");oldInIteration=state.inIteration;state.inIteration=true;body=parseStatement();state.inIteration=oldInIteration;return markerApply(marker,delegate.createWhileStatement(test,body))}function parseForVariableDeclaration(){var marker=markerCreate(),token=lex(),declarations=parseVariableDeclarationList();return markerApply(marker,delegate.createVariableDeclaration(declarations,token.value))}function parseForStatement(opts){var init,test,update,left,right,body,operator,oldInIteration,marker=markerCreate();init=test=update=null;expectKeyword("for");if(matchContextualKeyword("each")){throwError({},Messages.EachNotAllowed)}expect("(");if(match(";")){lex()}else{if(matchKeyword("var")||matchKeyword("let")||matchKeyword("const")){state.allowIn=false;init=parseForVariableDeclaration();state.allowIn=true;if(init.declarations.length===1){if(matchKeyword("in")||matchContextualKeyword("of")){operator=lookahead;if(!((operator.value==="in"||init.kind!=="var")&&init.declarations[0].init)){lex();left=init;right=parseExpression();init=null}}}}else{state.allowIn=false;init=parseExpression();state.allowIn=true;if(matchContextualKeyword("of")){operator=lex();left=init;right=parseExpression();init=null}else if(matchKeyword("in")){if(!isAssignableLeftHandSide(init)){throwError({},Messages.InvalidLHSInForIn)}operator=lex();left=init;right=parseExpression();init=null}}if(typeof left==="undefined"){expect(";")}}if(typeof left==="undefined"){if(!match(";")){test=parseExpression()}expect(";");if(!match(")")){update=parseExpression()}}expect(")");oldInIteration=state.inIteration;state.inIteration=true;if(!(opts!==undefined&&opts.ignoreBody)){body=parseStatement()}state.inIteration=oldInIteration;if(typeof left==="undefined"){return markerApply(marker,delegate.createForStatement(init,test,update,body))}if(operator.value==="in"){return markerApply(marker,delegate.createForInStatement(left,right,body))}return markerApply(marker,delegate.createForOfStatement(left,right,body))}function parseContinueStatement(){var label=null,key,marker=markerCreate();expectKeyword("continue");if(source.charCodeAt(index)===59){lex();if(!state.inIteration){throwError({},Messages.IllegalContinue)}return markerApply(marker,delegate.createContinueStatement(null))}if(peekLineTerminator()){if(!state.inIteration){throwError({},Messages.IllegalContinue)}return markerApply(marker,delegate.createContinueStatement(null))}if(lookahead.type===Token.Identifier){label=parseVariableIdentifier();key="$"+label.name;if(!Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError({},Messages.UnknownLabel,label.name)}}consumeSemicolon();if(label===null&&!state.inIteration){throwError({},Messages.IllegalContinue)}return markerApply(marker,delegate.createContinueStatement(label))}function parseBreakStatement(){var label=null,key,marker=markerCreate();expectKeyword("break");if(source.charCodeAt(index)===59){lex();if(!(state.inIteration||state.inSwitch)){throwError({},Messages.IllegalBreak)}return markerApply(marker,delegate.createBreakStatement(null))}if(peekLineTerminator()){if(!(state.inIteration||state.inSwitch)){throwError({},Messages.IllegalBreak)}return markerApply(marker,delegate.createBreakStatement(null))}if(lookahead.type===Token.Identifier){label=parseVariableIdentifier();key="$"+label.name;if(!Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError({},Messages.UnknownLabel,label.name)}}consumeSemicolon();if(label===null&&!(state.inIteration||state.inSwitch)){throwError({},Messages.IllegalBreak)}return markerApply(marker,delegate.createBreakStatement(label))}function parseReturnStatement(){var argument=null,marker=markerCreate();expectKeyword("return");if(!state.inFunctionBody){throwErrorTolerant({},Messages.IllegalReturn)}if(source.charCodeAt(index)===32){if(isIdentifierStart(source.charCodeAt(index+1))){argument=parseExpression();consumeSemicolon();return markerApply(marker,delegate.createReturnStatement(argument))}}if(peekLineTerminator()){return markerApply(marker,delegate.createReturnStatement(null))}if(!match(";")){if(!match("}")&&lookahead.type!==Token.EOF){argument=parseExpression()}}consumeSemicolon();return markerApply(marker,delegate.createReturnStatement(argument))}function parseWithStatement(){var object,body,marker=markerCreate();if(strict){throwErrorTolerant({},Messages.StrictModeWith)}expectKeyword("with");expect("(");object=parseExpression();expect(")");body=parseStatement();return markerApply(marker,delegate.createWithStatement(object,body))}function parseSwitchCase(){var test,consequent=[],sourceElement,marker=markerCreate();if(matchKeyword("default")){lex();test=null}else{expectKeyword("case");test=parseExpression()}expect(":");while(index<length){if(match("}")||matchKeyword("default")||matchKeyword("case")){break}sourceElement=parseSourceElement();if(typeof sourceElement==="undefined"){break}consequent.push(sourceElement)}return markerApply(marker,delegate.createSwitchCase(test,consequent))}function parseSwitchStatement(){var discriminant,cases,clause,oldInSwitch,defaultFound,marker=markerCreate();expectKeyword("switch");expect("(");discriminant=parseExpression();expect(")");expect("{");cases=[];if(match("}")){lex();return markerApply(marker,delegate.createSwitchStatement(discriminant,cases))}oldInSwitch=state.inSwitch;state.inSwitch=true;defaultFound=false;while(index<length){if(match("}")){break}clause=parseSwitchCase();if(clause.test===null){if(defaultFound){throwError({},Messages.MultipleDefaultsInSwitch)}defaultFound=true}cases.push(clause)}state.inSwitch=oldInSwitch;expect("}");return markerApply(marker,delegate.createSwitchStatement(discriminant,cases))}function parseThrowStatement(){var argument,marker=markerCreate();expectKeyword("throw");if(peekLineTerminator()){throwError({},Messages.NewlineAfterThrow)}argument=parseExpression();consumeSemicolon();return markerApply(marker,delegate.createThrowStatement(argument))}function parseCatchClause(){var param,body,marker=markerCreate();expectKeyword("catch");expect("(");if(match(")")){throwUnexpected(lookahead)}param=parseExpression();if(strict&&param.type===Syntax.Identifier&&isRestrictedWord(param.name)){throwErrorTolerant({},Messages.StrictCatchVariable)}expect(")");body=parseBlock();return markerApply(marker,delegate.createCatchClause(param,body))}function parseTryStatement(){var block,handlers=[],finalizer=null,marker=markerCreate();expectKeyword("try");block=parseBlock();if(matchKeyword("catch")){handlers.push(parseCatchClause())}if(matchKeyword("finally")){lex();finalizer=parseBlock()}if(handlers.length===0&&!finalizer){throwError({},Messages.NoCatchOrFinally)}return markerApply(marker,delegate.createTryStatement(block,[],handlers,finalizer))}function parseDebuggerStatement(){var marker=markerCreate();expectKeyword("debugger");consumeSemicolon();return markerApply(marker,delegate.createDebuggerStatement())}function parseStatement(){var type=lookahead.type,marker,expr,labeledBody,key;if(type===Token.EOF){throwUnexpected(lookahead)}if(type===Token.Punctuator){switch(lookahead.value){case";":return parseEmptyStatement();case"{":return parseBlock();case"(":return parseExpressionStatement();default:break}}if(type===Token.Keyword){switch(lookahead.value){case"break":return parseBreakStatement();case"continue":return parseContinueStatement();case"debugger":return parseDebuggerStatement();case"do":return parseDoWhileStatement();case"for":return parseForStatement();case"function":return parseFunctionDeclaration();case"class":return parseClassDeclaration();case"if":return parseIfStatement();case"return":return parseReturnStatement();case"switch":return parseSwitchStatement();case"throw":return parseThrowStatement();case"try":return parseTryStatement();case"var":return parseVariableStatement();case"while":return parseWhileStatement();case"with":return parseWithStatement();default:break}}if(matchAsyncFuncExprOrDecl()){return parseFunctionDeclaration()}marker=markerCreate();expr=parseExpression();if(expr.type===Syntax.Identifier&&match(":")){lex();key="$"+expr.name;if(Object.prototype.hasOwnProperty.call(state.labelSet,key)){throwError({},Messages.Redeclaration,"Label",expr.name)}state.labelSet[key]=true;labeledBody=parseStatement();delete state.labelSet[key];return markerApply(marker,delegate.createLabeledStatement(expr,labeledBody))}consumeSemicolon();return markerApply(marker,delegate.createExpressionStatement(expr))}function parseConciseBody(){if(match("{")){return parseFunctionSourceElements()}return parseAssignmentExpression()}function parseFunctionSourceElements(){var sourceElement,sourceElements=[],token,directive,firstRestricted,oldLabelSet,oldInIteration,oldInSwitch,oldInFunctionBody,oldParenthesizedCount,marker=markerCreate();expect("{");while(index<length){if(lookahead.type!==Token.StringLiteral){break}token=lookahead;sourceElement=parseSourceElement();sourceElements.push(sourceElement);if(sourceElement.expression.type!==Syntax.Literal){break}directive=source.slice(token.range[0]+1,token.range[1]-1);if(directive==="use strict"){strict=true;if(firstRestricted){throwErrorTolerant(firstRestricted,Messages.StrictOctalLiteral)}}else{if(!firstRestricted&&token.octal){firstRestricted=token}}}oldLabelSet=state.labelSet;oldInIteration=state.inIteration;oldInSwitch=state.inSwitch;oldInFunctionBody=state.inFunctionBody;oldParenthesizedCount=state.parenthesizedCount;state.labelSet={};state.inIteration=false;state.inSwitch=false;state.inFunctionBody=true;state.parenthesizedCount=0;while(index<length){if(match("}")){break}sourceElement=parseSourceElement();if(typeof sourceElement==="undefined"){break}sourceElements.push(sourceElement)}expect("}");state.labelSet=oldLabelSet;state.inIteration=oldInIteration;state.inSwitch=oldInSwitch;state.inFunctionBody=oldInFunctionBody;state.parenthesizedCount=oldParenthesizedCount;return markerApply(marker,delegate.createBlockStatement(sourceElements))}function validateParam(options,param,name){var key="$"+name;if(strict){if(isRestrictedWord(name)){options.stricted=param;options.message=Messages.StrictParamName}if(Object.prototype.hasOwnProperty.call(options.paramSet,key)){options.stricted=param;options.message=Messages.StrictParamDupe}}else if(!options.firstRestricted){if(isRestrictedWord(name)){options.firstRestricted=param;options.message=Messages.StrictParamName}else if(isStrictModeReservedWord(name)){options.firstRestricted=param;options.message=Messages.StrictReservedWord}else if(Object.prototype.hasOwnProperty.call(options.paramSet,key)){options.firstRestricted=param;options.message=Messages.StrictParamDupe}}options.paramSet[key]=true}function parseParam(options){var marker,token,rest,param,def;token=lookahead;if(token.value==="..."){token=lex();rest=true}if(match("[")){marker=markerCreate();param=parseArrayInitialiser();reinterpretAsDestructuredParameter(options,param);if(match(":")){param.typeAnnotation=parseTypeAnnotation();markerApply(marker,param)}}else if(match("{")){marker=markerCreate();if(rest){throwError({},Messages.ObjectPatternAsRestParameter)}param=parseObjectInitialiser();reinterpretAsDestructuredParameter(options,param);if(match(":")){param.typeAnnotation=parseTypeAnnotation();markerApply(marker,param)}}else{param=rest?parseTypeAnnotatableIdentifier(false,false):parseTypeAnnotatableIdentifier(false,true);validateParam(options,token,token.value)}if(match("=")){if(rest){throwErrorTolerant(lookahead,Messages.DefaultRestParameter)}lex();def=parseAssignmentExpression();++options.defaultCount}if(rest){if(!match(")")){throwError({},Messages.ParameterAfterRestParameter)}options.rest=param;return false}options.params.push(param);options.defaults.push(def);return!match(")")}function parseParams(firstRestricted){var options,marker=markerCreate();options={params:[],defaultCount:0,defaults:[],rest:null,firstRestricted:firstRestricted};expect("(");if(!match(")")){options.paramSet={};while(index<length){if(!parseParam(options)){break}expect(",")}}expect(")");if(options.defaultCount===0){options.defaults=[]}if(match(":")){options.returnType=parseTypeAnnotation()}return markerApply(marker,options)}function parseFunctionDeclaration(){var id,body,token,tmp,firstRestricted,message,generator,isAsync,previousStrict,previousYieldAllowed,previousAwaitAllowed,marker=markerCreate(),typeParameters;isAsync=false;if(matchAsync()){lex();isAsync=true}expectKeyword("function");generator=false;if(match("*")){lex();generator=true}token=lookahead;id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterDeclaration()}if(strict){if(isRestrictedWord(token.value)){throwErrorTolerant(token,Messages.StrictFunctionName)}}else{if(isRestrictedWord(token.value)){firstRestricted=token;message=Messages.StrictFunctionName}else if(isStrictModeReservedWord(token.value)){firstRestricted=token;message=Messages.StrictReservedWord}}tmp=parseParams(firstRestricted);firstRestricted=tmp.firstRestricted;if(tmp.message){message=tmp.message}previousStrict=strict;previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=generator;previousAwaitAllowed=state.awaitAllowed;state.awaitAllowed=isAsync;body=parseFunctionSourceElements();if(strict&&firstRestricted){throwError(firstRestricted,message)}if(strict&&tmp.stricted){throwErrorTolerant(tmp.stricted,message)}strict=previousStrict;state.yieldAllowed=previousYieldAllowed;state.awaitAllowed=previousAwaitAllowed;return markerApply(marker,delegate.createFunctionDeclaration(id,tmp.params,tmp.defaults,body,tmp.rest,generator,false,isAsync,tmp.returnType,typeParameters))}function parseFunctionExpression(){var token,id=null,firstRestricted,message,tmp,body,generator,isAsync,previousStrict,previousYieldAllowed,previousAwaitAllowed,marker=markerCreate(),typeParameters;isAsync=false;if(matchAsync()){lex();isAsync=true}expectKeyword("function");generator=false;if(match("*")){lex();generator=true}if(!match("(")){if(!match("<")){token=lookahead;id=parseVariableIdentifier();if(strict){if(isRestrictedWord(token.value)){throwErrorTolerant(token,Messages.StrictFunctionName)}}else{if(isRestrictedWord(token.value)){firstRestricted=token;message=Messages.StrictFunctionName}else if(isStrictModeReservedWord(token.value)){firstRestricted=token;message=Messages.StrictReservedWord}}}if(match("<")){typeParameters=parseTypeParameterDeclaration()}}tmp=parseParams(firstRestricted);firstRestricted=tmp.firstRestricted;if(tmp.message){message=tmp.message}previousStrict=strict;previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=generator;previousAwaitAllowed=state.awaitAllowed;state.awaitAllowed=isAsync;body=parseFunctionSourceElements();if(strict&&firstRestricted){throwError(firstRestricted,message)}if(strict&&tmp.stricted){throwErrorTolerant(tmp.stricted,message)}strict=previousStrict;state.yieldAllowed=previousYieldAllowed;state.awaitAllowed=previousAwaitAllowed;return markerApply(marker,delegate.createFunctionExpression(id,tmp.params,tmp.defaults,body,tmp.rest,generator,false,isAsync,tmp.returnType,typeParameters))}function parseYieldExpression(){var delegateFlag,expr,marker=markerCreate();expectKeyword("yield",!strict);delegateFlag=false;if(match("*")){lex();delegateFlag=true}expr=parseAssignmentExpression();return markerApply(marker,delegate.createYieldExpression(expr,delegateFlag))}function parseAwaitExpression(){var expr,marker=markerCreate();expectContextualKeyword("await");expr=parseAssignmentExpression();return markerApply(marker,delegate.createAwaitExpression(expr))}function parseMethodDefinition(existingPropNames,key,isStatic,generator,computed){var token,param,propType,isValidDuplicateProp=false,isAsync,typeParameters,tokenValue,returnType,annotationMarker;propType=isStatic?ClassPropertyType.static:ClassPropertyType.prototype;if(generator){return delegate.createMethodDefinition(propType,"",key,parsePropertyMethodFunction({generator:true}))}tokenValue=key.type==="Identifier"&&key.name;if(tokenValue==="get"&&!match("(")){key=parseObjectPropertyKey();if(existingPropNames[propType].hasOwnProperty(key.name)){isValidDuplicateProp=existingPropNames[propType][key.name].get===undefined&&existingPropNames[propType][key.name].data===undefined&&existingPropNames[propType][key.name].set!==undefined; if(!isValidDuplicateProp){throwError(key,Messages.IllegalDuplicateClassProperty)}}else{existingPropNames[propType][key.name]={}}existingPropNames[propType][key.name].get=true;expect("(");expect(")");if(match(":")){returnType=parseTypeAnnotation()}return delegate.createMethodDefinition(propType,"get",key,parsePropertyFunction({generator:false,returnType:returnType}))}if(tokenValue==="set"&&!match("(")){key=parseObjectPropertyKey();if(existingPropNames[propType].hasOwnProperty(key.name)){isValidDuplicateProp=existingPropNames[propType][key.name].set===undefined&&existingPropNames[propType][key.name].data===undefined&&existingPropNames[propType][key.name].get!==undefined;if(!isValidDuplicateProp){throwError(key,Messages.IllegalDuplicateClassProperty)}}else{existingPropNames[propType][key.name]={}}existingPropNames[propType][key.name].set=true;expect("(");token=lookahead;param=[parseTypeAnnotatableIdentifier()];expect(")");if(match(":")){returnType=parseTypeAnnotation()}return delegate.createMethodDefinition(propType,"set",key,parsePropertyFunction({params:param,generator:false,name:token,returnType:returnType}))}if(match("<")){typeParameters=parseTypeParameterDeclaration()}isAsync=tokenValue==="async"&&!match("(");if(isAsync){key=parseObjectPropertyKey()}if(existingPropNames[propType].hasOwnProperty(key.name)){throwError(key,Messages.IllegalDuplicateClassProperty)}else{existingPropNames[propType][key.name]={}}existingPropNames[propType][key.name].data=true;return delegate.createMethodDefinition(propType,"",key,parsePropertyMethodFunction({generator:false,async:isAsync,typeParameters:typeParameters}))}function parseClassProperty(existingPropNames,key,computed,isStatic){var typeAnnotation;typeAnnotation=parseTypeAnnotation();expect(";");return delegate.createClassProperty(key,typeAnnotation,computed,isStatic)}function parseClassElement(existingProps){var computed,generator=false,key,marker=markerCreate(),isStatic=false;if(match(";")){lex();return}if(lookahead.value==="static"){lex();isStatic=true}if(match("*")){lex();generator=true}computed=lookahead.value==="[";key=parseObjectPropertyKey();if(!generator&&lookahead.value===":"){return markerApply(marker,parseClassProperty(existingProps,key,computed,isStatic))}return markerApply(marker,parseMethodDefinition(existingProps,key,isStatic,generator,computed))}function parseClassBody(){var classElement,classElements=[],existingProps={},marker=markerCreate();existingProps[ClassPropertyType.static]={};existingProps[ClassPropertyType.prototype]={};expect("{");while(index<length){if(match("}")){break}classElement=parseClassElement(existingProps);if(typeof classElement!=="undefined"){classElements.push(classElement)}}expect("}");return markerApply(marker,delegate.createClassBody(classElements))}function parseClassImplements(){var id,implemented=[],marker,typeParameters;expectContextualKeyword("implements");while(index<length){marker=markerCreate();id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterInstantiation()}else{typeParameters=null}implemented.push(markerApply(marker,delegate.createClassImplements(id,typeParameters)));if(!match(",")){break}expect(",")}return implemented}function parseClassExpression(){var id,implemented,previousYieldAllowed,superClass=null,superTypeParameters,marker=markerCreate(),typeParameters;expectKeyword("class");if(!matchKeyword("extends")&&!matchContextualKeyword("implements")&&!match("{")){id=parseVariableIdentifier()}if(match("<")){typeParameters=parseTypeParameterDeclaration()}if(matchKeyword("extends")){expectKeyword("extends");previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=false;superClass=parseLeftHandSideExpressionAllowCall();if(match("<")){superTypeParameters=parseTypeParameterInstantiation()}state.yieldAllowed=previousYieldAllowed}if(matchContextualKeyword("implements")){implemented=parseClassImplements()}return markerApply(marker,delegate.createClassExpression(id,superClass,parseClassBody(),typeParameters,superTypeParameters,implemented))}function parseClassDeclaration(){var id,implemented,previousYieldAllowed,superClass=null,superTypeParameters,marker=markerCreate(),typeParameters;expectKeyword("class");id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterDeclaration()}if(matchKeyword("extends")){expectKeyword("extends");previousYieldAllowed=state.yieldAllowed;state.yieldAllowed=false;superClass=parseLeftHandSideExpressionAllowCall();if(match("<")){superTypeParameters=parseTypeParameterInstantiation()}state.yieldAllowed=previousYieldAllowed}if(matchContextualKeyword("implements")){implemented=parseClassImplements()}return markerApply(marker,delegate.createClassDeclaration(id,superClass,parseClassBody(),typeParameters,superTypeParameters,implemented))}function parseSourceElement(){var token;if(lookahead.type===Token.Keyword){switch(lookahead.value){case"const":case"let":return parseConstLetDeclaration(lookahead.value);case"function":return parseFunctionDeclaration();default:return parseStatement()}}if(matchContextualKeyword("type")&&lookahead2().type===Token.Identifier){return parseTypeAlias()}if(matchContextualKeyword("interface")&&lookahead2().type===Token.Identifier){return parseInterface()}if(matchContextualKeyword("declare")){token=lookahead2();if(token.type===Token.Keyword){switch(token.value){case"class":return parseDeclareClass();case"function":return parseDeclareFunction();case"var":return parseDeclareVariable()}}else if(token.type===Token.Identifier&&token.value==="module"){return parseDeclareModule()}}if(lookahead.type!==Token.EOF){return parseStatement()}}function parseProgramElement(){if(lookahead.type===Token.Keyword){switch(lookahead.value){case"export":return parseExportDeclaration();case"import":return parseImportDeclaration()}}return parseSourceElement()}function parseProgramElements(){var sourceElement,sourceElements=[],token,directive,firstRestricted;while(index<length){token=lookahead;if(token.type!==Token.StringLiteral){break}sourceElement=parseProgramElement();sourceElements.push(sourceElement);if(sourceElement.expression.type!==Syntax.Literal){break}directive=source.slice(token.range[0]+1,token.range[1]-1);if(directive==="use strict"){strict=true;if(firstRestricted){throwErrorTolerant(firstRestricted,Messages.StrictOctalLiteral)}}else{if(!firstRestricted&&token.octal){firstRestricted=token}}}while(index<length){sourceElement=parseProgramElement();if(typeof sourceElement==="undefined"){break}sourceElements.push(sourceElement)}return sourceElements}function parseProgram(){var body,marker=markerCreate();strict=false;peek();body=parseProgramElements();return markerApply(marker,delegate.createProgram(body))}function addComment(type,value,start,end,loc){var comment;assert(typeof start==="number","Comment must have valid position");if(state.lastCommentStart>=start){return}state.lastCommentStart=start;comment={type:type,value:value};if(extra.range){comment.range=[start,end]}if(extra.loc){comment.loc=loc}extra.comments.push(comment);if(extra.attachComment){extra.leadingComments.push(comment);extra.trailingComments.push(comment)}}function scanComment(){var comment,ch,loc,start,blockComment,lineComment;comment="";blockComment=false;lineComment=false;while(index<length){ch=source[index];if(lineComment){ch=source[index++];if(isLineTerminator(ch.charCodeAt(0))){loc.end={line:lineNumber,column:index-lineStart-1};lineComment=false;addComment("Line",comment,start,index-1,loc);if(ch==="\r"&&source[index]==="\n"){++index}++lineNumber;lineStart=index;comment=""}else if(index>=length){lineComment=false;comment+=ch;loc.end={line:lineNumber,column:length-lineStart};addComment("Line",comment,start,length,loc)}else{comment+=ch}}else if(blockComment){if(isLineTerminator(ch.charCodeAt(0))){if(ch==="\r"){++index;comment+="\r"}if(ch!=="\r"||source[index]==="\n"){comment+=source[index];++lineNumber;++index;lineStart=index;if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}}else{ch=source[index++];if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}comment+=ch;if(ch==="*"){ch=source[index];if(ch==="/"){comment=comment.substr(0,comment.length-1);blockComment=false;++index;loc.end={line:lineNumber,column:index-lineStart};addComment("Block",comment,start,index,loc);comment=""}}}}else if(ch==="/"){ch=source[index+1];if(ch==="/"){loc={start:{line:lineNumber,column:index-lineStart}};start=index;index+=2;lineComment=true;if(index>=length){loc.end={line:lineNumber,column:index-lineStart};lineComment=false;addComment("Line",comment,start,index,loc)}}else if(ch==="*"){start=index;index+=2;blockComment=true;loc={start:{line:lineNumber,column:index-lineStart-2}};if(index>=length){throwError({},Messages.UnexpectedToken,"ILLEGAL")}}else{break}}else if(isWhiteSpace(ch.charCodeAt(0))){++index}else if(isLineTerminator(ch.charCodeAt(0))){++index;if(ch==="\r"&&source[index]==="\n"){++index}++lineNumber;lineStart=index}else{break}}}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 getQualifiedXJSName(object){if(object.type===Syntax.XJSIdentifier){return object.name}if(object.type===Syntax.XJSNamespacedName){return object.namespace.name+":"+object.name.name}if(object.type===Syntax.XJSMemberExpression){return getQualifiedXJSName(object.object)+"."+getQualifiedXJSName(object.property)}}function isXJSIdentifierStart(ch){return ch!==92&&isIdentifierStart(ch)}function isXJSIdentifierPart(ch){return ch!==92&&(ch===45||isIdentifierPart(ch))}function scanXJSIdentifier(){var ch,start,value="";start=index;while(index<length){ch=source.charCodeAt(index);if(!isXJSIdentifierPart(ch)){break}value+=source[index++]}return{type:Token.XJSIdentifier,value:value,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanXJSEntity(){var ch,str="",start=index,count=0,code;ch=source[index];assert(ch==="&","Entity must start with an ampersand");index++;while(index<length&&count++<10){ch=source[index++];if(ch===";"){break}str+=ch}if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){code=+("0"+str.substr(1))}else{code=+str.substr(1).replace(Regex.LeadingZeros,"")}if(!isNaN(code)){return String.fromCharCode(code)}}else if(XHTMLEntities[str]){return XHTMLEntities[str]}}index=start+1;return"&"}function scanXJSText(stopChars){var ch,str="",start;start=index;while(index<length){ch=source[index];if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=scanXJSEntity()}else{index++;if(ch==="\r"&&source[index]==="\n"){str+=ch;ch=source[index];index++}if(isLineTerminator(ch.charCodeAt(0))){++lineNumber;lineStart=index}str+=ch}}return{type:Token.XJSText,value:str,lineNumber:lineNumber,lineStart:lineStart,range:[start,index]}}function scanXJSStringLiteral(){var innerToken,quote,start;quote=source[index];assert(quote==="'"||quote==='"',"String literal must starts with a quote");start=index;++index;innerToken=scanXJSText([quote]);if(quote!==source[index]){throwError({},Messages.UnexpectedToken,"ILLEGAL")}++index;innerToken.range=[start,index];return innerToken}function advanceXJSChild(){var ch=source.charCodeAt(index);if(ch!==123&&ch!==60){return scanXJSText(["<","{"])}return scanPunctuator()}function parseXJSIdentifier(){var token,marker=markerCreate();if(lookahead.type!==Token.XJSIdentifier){throwUnexpected(lookahead)}token=lex();return markerApply(marker,delegate.createXJSIdentifier(token.value))}function parseXJSNamespacedName(){var namespace,name,marker=markerCreate();namespace=parseXJSIdentifier();expect(":");name=parseXJSIdentifier();return markerApply(marker,delegate.createXJSNamespacedName(namespace,name))}function parseXJSMemberExpression(){var marker=markerCreate(),expr=parseXJSIdentifier();while(match(".")){lex();expr=markerApply(marker,delegate.createXJSMemberExpression(expr,parseXJSIdentifier()))}return expr}function parseXJSElementName(){if(lookahead2().value===":"){return parseXJSNamespacedName()}if(lookahead2().value==="."){return parseXJSMemberExpression()}return parseXJSIdentifier()}function parseXJSAttributeName(){if(lookahead2().value===":"){return parseXJSNamespacedName()}return parseXJSIdentifier()}function parseXJSAttributeValue(){var value,marker;if(match("{")){value=parseXJSExpressionContainer();if(value.expression.type===Syntax.XJSEmptyExpression){throwError(value,"XJS attributes must only be assigned a non-empty "+"expression")}}else if(match("<")){value=parseXJSElement()}else if(lookahead.type===Token.XJSText){marker=markerCreate();value=markerApply(marker,delegate.createLiteral(lex()))}else{throwError({},Messages.InvalidXJSAttributeValue)}return value}function parseXJSEmptyExpression(){var marker=markerCreatePreserveWhitespace();while(source.charAt(index)!=="}"){index++}return markerApply(marker,delegate.createXJSEmptyExpression())}function parseXJSExpressionContainer(){var expression,origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;state.inXJSChild=false;state.inXJSTag=false;expect("{");if(match("}")){expression=parseXJSEmptyExpression()}else{expression=parseExpression()}state.inXJSChild=origInXJSChild;state.inXJSTag=origInXJSTag;expect("}");return markerApply(marker,delegate.createXJSExpressionContainer(expression))}function parseXJSSpreadAttribute(){var expression,origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;state.inXJSChild=false;state.inXJSTag=false;expect("{");expect("...");expression=parseAssignmentExpression();state.inXJSChild=origInXJSChild;state.inXJSTag=origInXJSTag;expect("}");return markerApply(marker,delegate.createXJSSpreadAttribute(expression))}function parseXJSAttribute(){var name,marker;if(match("{")){return parseXJSSpreadAttribute()}marker=markerCreate();name=parseXJSAttributeName();if(match("=")){lex();return markerApply(marker,delegate.createXJSAttribute(name,parseXJSAttributeValue()))}return markerApply(marker,delegate.createXJSAttribute(name))}function parseXJSChild(){var token,marker;if(match("{")){token=parseXJSExpressionContainer()}else if(lookahead.type===Token.XJSText){marker=markerCreatePreserveWhitespace();token=markerApply(marker,delegate.createLiteral(lex()))}else{token=parseXJSElement()}return token}function parseXJSClosingElement(){var name,origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;state.inXJSChild=false;state.inXJSTag=true;expect("<");expect("/");name=parseXJSElementName();state.inXJSChild=origInXJSChild;state.inXJSTag=origInXJSTag;expect(">");return markerApply(marker,delegate.createXJSClosingElement(name))}function parseXJSOpeningElement(){var name,attribute,attributes=[],selfClosing=false,origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;state.inXJSChild=false;state.inXJSTag=true;expect("<");name=parseXJSElementName();while(index<length&&lookahead.value!=="/"&&lookahead.value!==">"){attributes.push(parseXJSAttribute())}state.inXJSTag=origInXJSTag;if(lookahead.value==="/"){expect("/");state.inXJSChild=origInXJSChild;expect(">");selfClosing=true}else{state.inXJSChild=true;expect(">")}return markerApply(marker,delegate.createXJSOpeningElement(name,attributes,selfClosing))}function parseXJSElement(){var openingElement,closingElement=null,children=[],origInXJSChild,origInXJSTag,marker=markerCreate();origInXJSChild=state.inXJSChild;origInXJSTag=state.inXJSTag;openingElement=parseXJSOpeningElement();if(!openingElement.selfClosing){while(index<length){state.inXJSChild=false;if(lookahead.value==="<"&&lookahead2().value==="/"){break}state.inXJSChild=true;children.push(parseXJSChild())}state.inXJSChild=origInXJSChild;state.inXJSTag=origInXJSTag;closingElement=parseXJSClosingElement();if(getQualifiedXJSName(closingElement.name)!==getQualifiedXJSName(openingElement.name)){throwError({},Messages.ExpectedXJSClosingTag,getQualifiedXJSName(openingElement.name))}}if(!origInXJSChild&&match("<")){throwError(lookahead,Messages.AdjacentXJSElements)}return markerApply(marker,delegate.createXJSElement(openingElement,closingElement,children))}function parseTypeAlias(){var id,marker=markerCreate(),typeParameters=null,right;expectContextualKeyword("type");id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterDeclaration()}expect("=");right=parseType();consumeSemicolon();return markerApply(marker,delegate.createTypeAlias(id,typeParameters,right))}function parseInterfaceExtends(){var marker=markerCreate(),id,typeParameters=null;id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterInstantiation()}return markerApply(marker,delegate.createInterfaceExtends(id,typeParameters))}function parseInterfaceish(marker,allowStatic){var body,bodyMarker,extended=[],id,typeParameters=null;id=parseVariableIdentifier();if(match("<")){typeParameters=parseTypeParameterDeclaration()}if(matchKeyword("extends")){expectKeyword("extends");while(index<length){extended.push(parseInterfaceExtends());if(!match(",")){break}expect(",")}}bodyMarker=markerCreate();body=markerApply(bodyMarker,parseObjectType(allowStatic));return markerApply(marker,delegate.createInterface(id,typeParameters,body,extended))}function parseInterface(){var body,bodyMarker,extended=[],id,marker=markerCreate(),typeParameters=null;expectContextualKeyword("interface");return parseInterfaceish(marker,false)}function parseDeclareClass(){var marker=markerCreate(),ret;expectContextualKeyword("declare");expectKeyword("class");ret=parseInterfaceish(marker,true);ret.type=Syntax.DeclareClass;return ret}function parseDeclareFunction(){var id,idMarker,marker=markerCreate(),params,returnType,rest,tmp,typeParameters=null,value,valueMarker;expectContextualKeyword("declare");expectKeyword("function");idMarker=markerCreate();id=parseVariableIdentifier();valueMarker=markerCreate();if(match("<")){typeParameters=parseTypeParameterDeclaration()}expect("(");tmp=parseFunctionTypeParams();params=tmp.params;rest=tmp.rest;expect(")");expect(":");returnType=parseType();value=markerApply(valueMarker,delegate.createFunctionTypeAnnotation(params,returnType,rest,typeParameters));id.typeAnnotation=markerApply(valueMarker,delegate.createTypeAnnotation(value));markerApply(idMarker,id);consumeSemicolon();return markerApply(marker,delegate.createDeclareFunction(id))}function parseDeclareVariable(){var id,marker=markerCreate();expectContextualKeyword("declare");expectKeyword("var");id=parseTypeAnnotatableIdentifier();consumeSemicolon();return markerApply(marker,delegate.createDeclareVariable(id))}function parseDeclareModule(){var body=[],bodyMarker,id,idMarker,marker=markerCreate(),token;expectContextualKeyword("declare");expectContextualKeyword("module");if(lookahead.type===Token.StringLiteral){if(strict&&lookahead.octal){throwErrorTolerant(lookahead,Messages.StrictOctalLiteral)}idMarker=markerCreate();id=markerApply(idMarker,delegate.createLiteral(lex()))}else{id=parseVariableIdentifier()}bodyMarker=markerCreate();expect("{");while(index<length&&!match("}")){token=lookahead2();switch(token.value){case"class":body.push(parseDeclareClass());break;case"function":body.push(parseDeclareFunction());break;case"var":body.push(parseDeclareVariable());break;default:throwUnexpected(lookahead)}}expect("}");return markerApply(marker,delegate.createDeclareModule(id,markerApply(bodyMarker,delegate.createBlockStatement(body))))}function collectToken(){var start,loc,token,range,value,entry;if(!state.inXJSChild){skipComment()}start=index;loc={start:{line:lineNumber,column:index-lineStart}};token=extra.advance();loc.end={line:lineNumber,column:index-lineStart};if(token.type!==Token.EOF){range=[token.range[0],token.range[1]];value=source.slice(token.range[0],token.range[1]);entry={type:TokenName[token.type],value:value,range:range,loc:loc};if(token.regex){entry.regex={pattern:token.regex.pattern,flags:token.regex.flags}}extra.tokens.push(entry)}return token}function collectRegex(){var pos,loc,regex,token;skipComment();pos=index;loc={start:{line:lineNumber,column:index-lineStart}};regex=extra.scanRegExp();loc.end={line:lineNumber,column:index-lineStart};if(!extra.tokenize){if(extra.tokens.length>0){token=extra.tokens[extra.tokens.length-1];if(token.range[0]===pos&&token.type==="Punctuator"){if(token.value==="/"||token.value==="/="){extra.tokens.pop()}}}extra.tokens.push({type:"RegularExpression",value:regex.literal,regex:regex.regex,range:[pos,index],loc:loc})}return regex}function filterTokenLocation(){var i,entry,token,tokens=[];for(i=0;i<extra.tokens.length;++i){entry=extra.tokens[i];token={type:entry.type,value:entry.value};if(entry.regex){token.regex={pattern:entry.regex.pattern,flags:entry.regex.flags}}if(extra.range){token.range=entry.range}if(extra.loc){token.loc=entry.loc}tokens.push(token)}extra.tokens=tokens}function patch(){if(extra.comments){extra.skipComment=skipComment;skipComment=scanComment}if(typeof extra.tokens!=="undefined"){extra.advance=advance;extra.scanRegExp=scanRegExp;advance=collectToken;scanRegExp=collectRegex}}function unpatch(){if(typeof extra.skipComment==="function"){skipComment=extra.skipComment}if(typeof extra.scanRegExp==="function"){advance=extra.advance;scanRegExp=extra.scanRegExp}}function extend(object,properties){var entry,result={};for(entry in object){if(object.hasOwnProperty(entry)){result[entry]=object[entry]}}for(entry in properties){if(properties.hasOwnProperty(entry)){result[entry]=properties[entry]}}return result}function tokenize(code,options){var toString,token,tokens;toString=String;if(typeof code!=="string"&&!(code instanceof String)){code=toString(code)}delegate=SyntaxTreeDelegate;source=code;index=0;lineNumber=source.length>0?1:0;lineStart=0;length=source.length;lookahead=null;state={allowKeyword:true,allowIn:true,labelSet:{},inFunctionBody:false,inIteration:false,inSwitch:false,lastCommentStart:-1};extra={};options=options||{};options.tokens=true;extra.tokens=[];extra.tokenize=true;extra.openParenToken=-1;extra.openCurlyToken=-1;extra.range=typeof options.range==="boolean"&&options.range;extra.loc=typeof options.loc==="boolean"&&options.loc;if(typeof options.comment==="boolean"&&options.comment){extra.comments=[]}if(typeof options.tolerant==="boolean"&&options.tolerant){extra.errors=[]}if(length>0){if(typeof source[0]==="undefined"){if(code instanceof String){source=code.valueOf()}}}patch();try{peek();if(lookahead.type===Token.EOF){return extra.tokens}token=lex();while(lookahead.type!==Token.EOF){try{token=lex()}catch(lexError){token=lookahead;if(extra.errors){extra.errors.push(lexError);break}else{throw lexError}}}filterTokenLocation();tokens=extra.tokens;if(typeof extra.comments!=="undefined"){tokens.comments=extra.comments}if(typeof extra.errors!=="undefined"){tokens.errors=extra.errors}}catch(e){throw e}finally{unpatch();extra={}}return tokens}function parse(code,options){var program,toString;toString=String;if(typeof code!=="string"&&!(code instanceof String)){code=toString(code)}delegate=SyntaxTreeDelegate;source=code;index=0;lineNumber=source.length>0?1:0;lineStart=0;length=source.length;lookahead=null;state={allowKeyword:false,allowIn:true,labelSet:{},parenthesizedCount:0,inFunctionBody:false,inIteration:false,inSwitch:false,inXJSChild:false,inXJSTag:false,inType:false,lastCommentStart:-1,yieldAllowed:false,awaitAllowed:false};extra={};if(typeof options!=="undefined"){extra.range=typeof options.range==="boolean"&&options.range;extra.loc=typeof options.loc==="boolean"&&options.loc;extra.attachComment=typeof options.attachComment==="boolean"&&options.attachComment;if(extra.loc&&options.source!==null&&options.source!==undefined){delegate=extend(delegate,{postProcess:function(node){node.loc.source=toString(options.source);return node}})}if(typeof options.tokens==="boolean"&&options.tokens){extra.tokens=[]}if(typeof options.comment==="boolean"&&options.comment){extra.comments=[]}if(typeof options.tolerant==="boolean"&&options.tolerant){extra.errors=[]}if(extra.attachComment){extra.range=true;extra.comments=[];extra.bottomRightStack=[];extra.trailingComments=[];extra.leadingComments=[]}}if(length>0){if(typeof source[0]==="undefined"){if(code instanceof String){source=code.valueOf()}}}patch();try{program=parseProgram();if(typeof extra.comments!=="undefined"){program.comments=extra.comments}if(typeof extra.tokens!=="undefined"){filterTokenLocation();program.tokens=extra.tokens}if(typeof extra.errors!=="undefined"){program.errors=extra.errors}}catch(e){throw e}finally{unpatch();extra={}}return program}exports.version="8001.1001.0-dev-harmony-fb";exports.tokenize=tokenize;exports.parse=parse;exports.Syntax=function(){var name,types={};if(typeof Object.create==="function"){types=Object.create(null)}for(name in Syntax){if(Syntax.hasOwnProperty(name)){types[name]=Syntax[name]}}if(typeof Object.freeze==="function"){Object.freeze(types)}return types}()})},{}],147:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var linesModule=require("./lines");var fromString=linesModule.fromString;var Lines=linesModule.Lines;var concat=linesModule.concat;var comparePos=require("./util").comparePos;var childNodesCacheKey=require("private").makeUniqueKey();function getSortedChildNodes(node,resultArray){if(!node){return}if(resultArray){if(n.Node.check(node)&&n.SourceLocation.check(node.loc)){for(var i=resultArray.length-1;i>=0;--i){if(comparePos(resultArray[i].loc.end,node.loc.start)<=0){break}}resultArray.splice(i+1,0,node);return}}else if(node[childNodesCacheKey]){return node[childNodesCacheKey]}var names;if(isArray.check(node)){names=Object.keys(node)}else if(isObject.check(node)){names=types.getFieldNames(node)}else{return}if(!resultArray){Object.defineProperty(node,childNodesCacheKey,{value:resultArray=[],enumerable:false})}for(var i=0,nameCount=names.length;i<nameCount;++i){getSortedChildNodes(node[names[i]],resultArray)}return resultArray}function decorateComment(node,comment){var childNodes=getSortedChildNodes(node);var left=0,right=childNodes.length;while(left<right){var middle=left+right>>1;var child=childNodes[middle];if(comparePos(child.loc.start,comment.loc.start)<=0&&comparePos(comment.loc.end,child.loc.end)<=0){decorateComment(comment.enclosingNode=child,comment);return}if(comparePos(child.loc.end,comment.loc.start)<=0){var precedingNode=child;left=middle+1;continue}if(comparePos(comment.loc.end,child.loc.start)<=0){var followingNode=child;right=middle;continue}throw new Error("Comment location overlaps with node location")}if(precedingNode){comment.precedingNode=precedingNode}if(followingNode){comment.followingNode=followingNode}}exports.attach=function(comments,ast,lines){if(!isArray.check(comments)){return}var tiesToBreak=[];comments.forEach(function(comment){comment.loc.lines=lines;decorateComment(ast,comment);var pn=comment.precedingNode;var en=comment.enclosingNode;var fn=comment.followingNode;if(pn&&fn){var tieCount=tiesToBreak.length;if(tieCount>0){var lastTie=tiesToBreak[tieCount-1];assert.strictEqual(lastTie.precedingNode===comment.precedingNode,lastTie.followingNode===comment.followingNode);if(lastTie.followingNode!==comment.followingNode){breakTies(tiesToBreak,lines)}}tiesToBreak.push(comment)}else if(pn){breakTies(tiesToBreak,lines);Comments.forNode(pn).addTrailing(comment)}else if(fn){breakTies(tiesToBreak,lines);Comments.forNode(fn).addLeading(comment)}else if(en){breakTies(tiesToBreak,lines);Comments.forNode(en).addDangling(comment)}else{throw new Error("AST contains no nodes at all?")}});breakTies(tiesToBreak,lines)};function breakTies(tiesToBreak,lines){var tieCount=tiesToBreak.length;if(tieCount===0){return}var pn=tiesToBreak[0].precedingNode;var fn=tiesToBreak[0].followingNode;var gapEndPos=fn.loc.start;for(var indexOfFirstLeadingComment=tieCount;indexOfFirstLeadingComment>0;--indexOfFirstLeadingComment){var comment=tiesToBreak[indexOfFirstLeadingComment-1];assert.strictEqual(comment.precedingNode,pn);assert.strictEqual(comment.followingNode,fn);var gap=lines.sliceString(comment.loc.end,gapEndPos);if(/\S/.test(gap)){break}gapEndPos=comment.loc.start}while(indexOfFirstLeadingComment<=tieCount&&(comment=tiesToBreak[indexOfFirstLeadingComment])&&comment.type==="Line"&&comment.loc.start.column>fn.loc.start.column){++indexOfFirstLeadingComment}tiesToBreak.forEach(function(comment,i){if(i<indexOfFirstLeadingComment){Comments.forNode(pn).addTrailing(comment)}else{Comments.forNode(fn).addLeading(comment)}});tiesToBreak.length=0}function Comments(){assert.ok(this instanceof Comments);this.leading=[];this.dangling=[];this.trailing=[]}var Cp=Comments.prototype;Comments.forNode=function forNode(node){var comments=node.comments;if(!comments){Object.defineProperty(node,"comments",{value:comments=new Comments,enumerable:false})}return comments};Cp.forEach=function forEach(callback,context){this.leading.forEach(callback,context);this.trailing.forEach(callback,context)};Cp.addLeading=function addLeading(comment){this.leading.push(comment)};Cp.addDangling=function addDangling(comment){this.dangling.push(comment)};Cp.addTrailing=function addTrailing(comment){comment.trailing=true;if(comment.type==="Block"){this.trailing.push(comment)}else{this.leading.push(comment)}};function printLeadingComment(comment,options){var loc=comment.loc;var lines=loc&&loc.lines;var parts=[];if(comment.type==="Block"){parts.push("/*",fromString(comment.value,options),"*/")}else if(comment.type==="Line"){parts.push("//",fromString(comment.value,options))}else assert.fail(comment.type);if(comment.trailing){parts.push("\n")}else if(lines instanceof Lines){var trailingSpace=lines.slice(loc.end,lines.skipSpaces(loc.end)); if(trailingSpace.length===1){parts.push(trailingSpace)}else{parts.push(new Array(trailingSpace.length).join("\n"))}}else{parts.push("\n")}return concat(parts).stripMargin(loc?loc.start.column:0)}function printTrailingComment(comment,options){var loc=comment.loc;var lines=loc&&loc.lines;var parts=[];if(lines instanceof Lines){var fromPos=lines.skipSpaces(loc.start,true)||lines.firstPos();var leadingSpace=lines.slice(fromPos,loc.start);if(leadingSpace.length===1){parts.push(leadingSpace)}else{parts.push(new Array(leadingSpace.length).join("\n"))}}if(comment.type==="Block"){parts.push("/*",fromString(comment.value,options),"*/")}else if(comment.type==="Line"){parts.push("//",fromString(comment.value,options),"\n")}else assert.fail(comment.type);return concat(parts).stripMargin(loc?loc.start.column:0,true)}exports.printComments=function(comments,innerLines,options){if(innerLines){assert.ok(innerLines instanceof Lines)}else{innerLines=fromString("")}if(!comments||!(comments.leading.length+comments.trailing.length)){return innerLines}var parts=[];comments.leading.forEach(function(comment){parts.push(printLeadingComment(comment,options))});parts.push(innerLines);comments.trailing.forEach(function(comment){assert.strictEqual(comment.type,"Block");parts.push(printTrailingComment(comment,options))});return concat(parts)}},{"./lines":148,"./types":154,"./util":155,assert:91,"private":124}],148:[function(require,module,exports){var assert=require("assert");var sourceMap=require("source-map");var normalizeOptions=require("./options").normalize;var secretKey=require("private").makeUniqueKey();var types=require("./types");var isString=types.builtInTypes.string;var comparePos=require("./util").comparePos;var Mapping=require("./mapping");function getSecret(lines){return lines[secretKey]}function Lines(infos,sourceFileName){assert.ok(this instanceof Lines);assert.ok(infos.length>0);if(sourceFileName){isString.assert(sourceFileName)}else{sourceFileName=null}Object.defineProperty(this,secretKey,{value:{infos:infos,mappings:[],name:sourceFileName,cachedSourceMap:null}});if(sourceFileName){getSecret(this).mappings.push(new Mapping(this,{start:this.firstPos(),end:this.lastPos()}))}}exports.Lines=Lines;var Lp=Lines.prototype;Object.defineProperties(Lp,{length:{get:function(){return getSecret(this).infos.length}},name:{get:function(){return getSecret(this).name}}});function copyLineInfo(info){return{line:info.line,indent:info.indent,sliceStart:info.sliceStart,sliceEnd:info.sliceEnd}}var fromStringCache={};var hasOwn=fromStringCache.hasOwnProperty;var maxCacheKeyLen=10;function countSpaces(spaces,tabWidth){var count=0;var len=spaces.length;for(var i=0;i<len;++i){var ch=spaces.charAt(i);if(ch===" "){count+=1}else if(ch===" "){assert.strictEqual(typeof tabWidth,"number");assert.ok(tabWidth>0);var next=Math.ceil(count/tabWidth)*tabWidth;if(next===count){count+=tabWidth}else{count=next}}else if(ch==="\r"){}else{assert.fail("unexpected whitespace character",ch)}}return count}exports.countSpaces=countSpaces;var leadingSpaceExp=/^\s*/;function fromString(string,options){if(string instanceof Lines)return string;string+="";var tabWidth=options&&options.tabWidth;var tabless=string.indexOf(" ")<0;var cacheable=!options&&tabless&&string.length<=maxCacheKeyLen;assert.ok(tabWidth||tabless,"No tab width specified but encountered tabs in string\n"+string);if(cacheable&&hasOwn.call(fromStringCache,string))return fromStringCache[string];var lines=new Lines(string.split("\n").map(function(line){var spaces=leadingSpaceExp.exec(line)[0];return{line:line,indent:countSpaces(spaces,tabWidth),sliceStart:spaces.length,sliceEnd:line.length}}),normalizeOptions(options).sourceFileName);if(cacheable)fromStringCache[string]=lines;return lines}exports.fromString=fromString;function isOnlyWhitespace(string){return!/\S/.test(string)}Lp.toString=function(options){return this.sliceString(this.firstPos(),this.lastPos(),options)};Lp.getSourceMap=function(sourceMapName,sourceRoot){if(!sourceMapName){return null}var targetLines=this;function updateJSON(json){json=json||{};isString.assert(sourceMapName);json.file=sourceMapName;if(sourceRoot){isString.assert(sourceRoot);json.sourceRoot=sourceRoot}return json}var secret=getSecret(targetLines);if(secret.cachedSourceMap){return updateJSON(secret.cachedSourceMap.toJSON())}var smg=new sourceMap.SourceMapGenerator(updateJSON());var sourcesToContents={};secret.mappings.forEach(function(mapping){var sourceCursor=mapping.sourceLines.skipSpaces(mapping.sourceLoc.start)||mapping.sourceLines.lastPos();var targetCursor=targetLines.skipSpaces(mapping.targetLoc.start)||targetLines.lastPos();while(comparePos(sourceCursor,mapping.sourceLoc.end)<0&&comparePos(targetCursor,mapping.targetLoc.end)<0){var sourceChar=mapping.sourceLines.charAt(sourceCursor);var targetChar=targetLines.charAt(targetCursor);assert.strictEqual(sourceChar,targetChar);var sourceName=mapping.sourceLines.name;smg.addMapping({source:sourceName,original:{line:sourceCursor.line,column:sourceCursor.column},generated:{line:targetCursor.line,column:targetCursor.column}});if(!hasOwn.call(sourcesToContents,sourceName)){var sourceContent=mapping.sourceLines.toString();smg.setSourceContent(sourceName,sourceContent);sourcesToContents[sourceName]=sourceContent}targetLines.nextPos(targetCursor,true);mapping.sourceLines.nextPos(sourceCursor,true)}});secret.cachedSourceMap=smg;return smg.toJSON()};Lp.bootstrapCharAt=function(pos){assert.strictEqual(typeof pos,"object");assert.strictEqual(typeof pos.line,"number");assert.strictEqual(typeof pos.column,"number");var line=pos.line,column=pos.column,strings=this.toString().split("\n"),string=strings[line-1];if(typeof string==="undefined")return"";if(column===string.length&&line<strings.length)return"\n";if(column>=string.length)return"";return string.charAt(column)};Lp.charAt=function(pos){assert.strictEqual(typeof pos,"object");assert.strictEqual(typeof pos.line,"number");assert.strictEqual(typeof pos.column,"number");var line=pos.line,column=pos.column,secret=getSecret(this),infos=secret.infos,info=infos[line-1],c=column;if(typeof info==="undefined"||c<0)return"";var indent=this.getIndentAt(line);if(c<indent)return" ";c+=info.sliceStart-indent;if(c===info.sliceEnd&&line<this.length)return"\n";if(c>=info.sliceEnd)return"";return info.line.charAt(c)};Lp.stripMargin=function(width,skipFirstLine){if(width===0)return this;assert.ok(width>0,"negative margin: "+width);if(skipFirstLine&&this.length===1)return this;var secret=getSecret(this);var lines=new Lines(secret.infos.map(function(info,i){if(info.line&&(i>0||!skipFirstLine)){info=copyLineInfo(info);info.indent=Math.max(0,info.indent-width)}return info}));if(secret.mappings.length>0){var newMappings=getSecret(lines).mappings;assert.strictEqual(newMappings.length,0);secret.mappings.forEach(function(mapping){newMappings.push(mapping.indent(width,skipFirstLine,true))})}return lines};Lp.indent=function(by){if(by===0)return this;var secret=getSecret(this);var lines=new Lines(secret.infos.map(function(info){if(info.line){info=copyLineInfo(info);info.indent+=by}return info}));if(secret.mappings.length>0){var newMappings=getSecret(lines).mappings;assert.strictEqual(newMappings.length,0);secret.mappings.forEach(function(mapping){newMappings.push(mapping.indent(by))})}return lines};Lp.indentTail=function(by){if(by===0)return this;if(this.length<2)return this;var secret=getSecret(this);var lines=new Lines(secret.infos.map(function(info,i){if(i>0&&info.line){info=copyLineInfo(info);info.indent+=by}return info}));if(secret.mappings.length>0){var newMappings=getSecret(lines).mappings;assert.strictEqual(newMappings.length,0);secret.mappings.forEach(function(mapping){newMappings.push(mapping.indent(by,true))})}return lines};Lp.getIndentAt=function(line){assert.ok(line>=1,"no line "+line+" (line numbers start from 1)");var secret=getSecret(this),info=secret.infos[line-1];return Math.max(info.indent,0)};Lp.guessTabWidth=function(){var secret=getSecret(this);if(hasOwn.call(secret,"cachedTabWidth")){return secret.cachedTabWidth}var counts=[];var lastIndent=0;for(var line=1,last=this.length;line<=last;++line){var info=secret.infos[line-1];var sliced=info.line.slice(info.sliceStart,info.sliceEnd);if(isOnlyWhitespace(sliced)){continue}var diff=Math.abs(info.indent-lastIndent);counts[diff]=~~counts[diff]+1;lastIndent=info.indent}var maxCount=-1;var result=2;for(var tabWidth=1;tabWidth<counts.length;tabWidth+=1){if(hasOwn.call(counts,tabWidth)&&counts[tabWidth]>maxCount){maxCount=counts[tabWidth];result=tabWidth}}return secret.cachedTabWidth=result};Lp.isOnlyWhitespace=function(){return isOnlyWhitespace(this.toString())};Lp.isPrecededOnlyByWhitespace=function(pos){var secret=getSecret(this);var info=secret.infos[pos.line-1];var indent=Math.max(info.indent,0);var diff=pos.column-indent;if(diff<=0){return true}var start=info.sliceStart;var end=Math.min(start+diff,info.sliceEnd);var prefix=info.line.slice(start,end);return isOnlyWhitespace(prefix)};Lp.getLineLength=function(line){var secret=getSecret(this),info=secret.infos[line-1];return this.getIndentAt(line)+info.sliceEnd-info.sliceStart};Lp.nextPos=function(pos,skipSpaces){var l=Math.max(pos.line,0),c=Math.max(pos.column,0);if(c<this.getLineLength(l)){pos.column+=1;return skipSpaces?!!this.skipSpaces(pos,false,true):true}if(l<this.length){pos.line+=1;pos.column=0;return skipSpaces?!!this.skipSpaces(pos,false,true):true}return false};Lp.prevPos=function(pos,skipSpaces){var l=pos.line,c=pos.column;if(c<1){l-=1;if(l<1)return false;c=this.getLineLength(l)}else{c=Math.min(c-1,this.getLineLength(l))}pos.line=l;pos.column=c;return skipSpaces?!!this.skipSpaces(pos,true,true):true};Lp.firstPos=function(){return{line:1,column:0}};Lp.lastPos=function(){return{line:this.length,column:this.getLineLength(this.length)}};Lp.skipSpaces=function(pos,backward,modifyInPlace){if(pos){pos=modifyInPlace?pos:{line:pos.line,column:pos.column}}else if(backward){pos=this.lastPos()}else{pos=this.firstPos()}if(backward){while(this.prevPos(pos)){if(!isOnlyWhitespace(this.charAt(pos))&&this.nextPos(pos)){return pos}}return null}else{while(isOnlyWhitespace(this.charAt(pos))){if(!this.nextPos(pos)){return null}}return pos}};Lp.trimLeft=function(){var pos=this.skipSpaces(this.firstPos(),false,true);return pos?this.slice(pos):emptyLines};Lp.trimRight=function(){var pos=this.skipSpaces(this.lastPos(),true,true);return pos?this.slice(this.firstPos(),pos):emptyLines};Lp.trim=function(){var start=this.skipSpaces(this.firstPos(),false,true);if(start===null)return emptyLines;var end=this.skipSpaces(this.lastPos(),true,true);assert.notStrictEqual(end,null);return this.slice(start,end)};Lp.eachPos=function(callback,startPos,skipSpaces){var pos=this.firstPos();if(startPos){pos.line=startPos.line,pos.column=startPos.column}if(skipSpaces&&!this.skipSpaces(pos,false,true)){return}do callback.call(this,pos);while(this.nextPos(pos,skipSpaces))};Lp.bootstrapSlice=function(start,end){var strings=this.toString().split("\n").slice(start.line-1,end.line);strings.push(strings.pop().slice(0,end.column));strings[0]=strings[0].slice(start.column);return fromString(strings.join("\n"))};Lp.slice=function(start,end){if(!end){if(!start){return this}end=this.lastPos()}var secret=getSecret(this);var sliced=secret.infos.slice(start.line-1,end.line);if(start.line===end.line){sliced[0]=sliceInfo(sliced[0],start.column,end.column)}else{assert.ok(start.line<end.line);sliced[0]=sliceInfo(sliced[0],start.column);sliced.push(sliceInfo(sliced.pop(),0,end.column))}var lines=new Lines(sliced);if(secret.mappings.length>0){var newMappings=getSecret(lines).mappings;assert.strictEqual(newMappings.length,0);secret.mappings.forEach(function(mapping){var sliced=mapping.slice(this,start,end);if(sliced){newMappings.push(sliced)}},this)}return lines};function sliceInfo(info,startCol,endCol){var sliceStart=info.sliceStart;var sliceEnd=info.sliceEnd;var indent=Math.max(info.indent,0);var lineLength=indent+sliceEnd-sliceStart;if(typeof endCol==="undefined"){endCol=lineLength}startCol=Math.max(startCol,0);endCol=Math.min(endCol,lineLength);endCol=Math.max(endCol,startCol);if(endCol<indent){indent=endCol;sliceEnd=sliceStart}else{sliceEnd-=lineLength-endCol}lineLength=endCol;lineLength-=startCol;if(startCol<indent){indent-=startCol}else{startCol-=indent;indent=0;sliceStart+=startCol}assert.ok(indent>=0);assert.ok(sliceStart<=sliceEnd);assert.strictEqual(lineLength,indent+sliceEnd-sliceStart);if(info.indent===indent&&info.sliceStart===sliceStart&&info.sliceEnd===sliceEnd){return info}return{line:info.line,indent:indent,sliceStart:sliceStart,sliceEnd:sliceEnd}}Lp.bootstrapSliceString=function(start,end,options){return this.slice(start,end).toString(options)};Lp.sliceString=function(start,end,options){if(!end){if(!start){return this}end=this.lastPos()}options=normalizeOptions(options);var infos=getSecret(this).infos;var parts=[];var tabWidth=options.tabWidth;for(var line=start.line;line<=end.line;++line){var info=infos[line-1];if(line===start.line){if(line===end.line){info=sliceInfo(info,start.column,end.column)}else{info=sliceInfo(info,start.column)}}else if(line===end.line){info=sliceInfo(info,0,end.column)}var indent=Math.max(info.indent,0);var before=info.line.slice(0,info.sliceStart);if(options.reuseWhitespace&&isOnlyWhitespace(before)&&countSpaces(before,options.tabWidth)===indent){parts.push(info.line.slice(0,info.sliceEnd));continue}var tabs=0;var spaces=indent;if(options.useTabs){tabs=Math.floor(indent/tabWidth);spaces-=tabs*tabWidth}var result="";if(tabs>0){result+=new Array(tabs+1).join(" ")}if(spaces>0){result+=new Array(spaces+1).join(" ")}result+=info.line.slice(info.sliceStart,info.sliceEnd);parts.push(result)}return parts.join("\n")};Lp.isEmpty=function(){return this.length<2&&this.getLineLength(1)<1};Lp.join=function(elements){var separator=this;var separatorSecret=getSecret(separator);var infos=[];var mappings=[];var prevInfo;function appendSecret(secret){if(secret===null)return;if(prevInfo){var info=secret.infos[0];var indent=new Array(info.indent+1).join(" ");var prevLine=infos.length;var prevColumn=Math.max(prevInfo.indent,0)+prevInfo.sliceEnd-prevInfo.sliceStart;prevInfo.line=prevInfo.line.slice(0,prevInfo.sliceEnd)+indent+info.line.slice(info.sliceStart,info.sliceEnd);prevInfo.sliceEnd=prevInfo.line.length;if(secret.mappings.length>0){secret.mappings.forEach(function(mapping){mappings.push(mapping.add(prevLine,prevColumn))})}}else if(secret.mappings.length>0){mappings.push.apply(mappings,secret.mappings)}secret.infos.forEach(function(info,i){if(!prevInfo||i>0){prevInfo=copyLineInfo(info);infos.push(prevInfo)}})}function appendWithSeparator(secret,i){if(i>0)appendSecret(separatorSecret);appendSecret(secret)}elements.map(function(elem){var lines=fromString(elem);if(lines.isEmpty())return null;return getSecret(lines)}).forEach(separator.isEmpty()?appendSecret:appendWithSeparator);if(infos.length<1)return emptyLines;var lines=new Lines(infos);getSecret(lines).mappings=mappings;return lines};exports.concat=function(elements){return emptyLines.join(elements)};Lp.concat=function(other){var args=arguments,list=[this];list.push.apply(list,args);assert.strictEqual(list.length,args.length+1);return emptyLines.join(list)};var emptyLines=fromString("")},{"./mapping":149,"./options":150,"./types":154,"./util":155,assert:91,"private":124,"source-map":165}],149:[function(require,module,exports){var assert=require("assert");var types=require("./types");var isString=types.builtInTypes.string;var isNumber=types.builtInTypes.number;var SourceLocation=types.namedTypes.SourceLocation;var Position=types.namedTypes.Position;var linesModule=require("./lines");var comparePos=require("./util").comparePos;function Mapping(sourceLines,sourceLoc,targetLoc){assert.ok(this instanceof Mapping);assert.ok(sourceLines instanceof linesModule.Lines);SourceLocation.assert(sourceLoc);if(targetLoc){assert.ok(isNumber.check(targetLoc.start.line)&&isNumber.check(targetLoc.start.column)&&isNumber.check(targetLoc.end.line)&&isNumber.check(targetLoc.end.column))}else{targetLoc=sourceLoc}Object.defineProperties(this,{sourceLines:{value:sourceLines},sourceLoc:{value:sourceLoc},targetLoc:{value:targetLoc}})}var Mp=Mapping.prototype;module.exports=Mapping;Mp.slice=function(lines,start,end){assert.ok(lines instanceof linesModule.Lines);Position.assert(start);if(end){Position.assert(end)}else{end=lines.lastPos()}var sourceLines=this.sourceLines;var sourceLoc=this.sourceLoc;var targetLoc=this.targetLoc;function skip(name){var sourceFromPos=sourceLoc[name];var targetFromPos=targetLoc[name];var targetToPos=start;if(name==="end"){targetToPos=end}else{assert.strictEqual(name,"start")}return skipChars(sourceLines,sourceFromPos,lines,targetFromPos,targetToPos)}if(comparePos(start,targetLoc.start)<=0){if(comparePos(targetLoc.end,end)<=0){targetLoc={start:subtractPos(targetLoc.start,start.line,start.column),end:subtractPos(targetLoc.end,start.line,start.column)}}else if(comparePos(end,targetLoc.start)<=0){return null}else{sourceLoc={start:sourceLoc.start,end:skip("end")};targetLoc={start:subtractPos(targetLoc.start,start.line,start.column),end:subtractPos(end,start.line,start.column)}}}else{if(comparePos(targetLoc.end,start)<=0){return null}if(comparePos(targetLoc.end,end)<=0){sourceLoc={start:skip("start"),end:sourceLoc.end};targetLoc={start:{line:1,column:0},end:subtractPos(targetLoc.end,start.line,start.column)}}else{sourceLoc={start:skip("start"),end:skip("end")};targetLoc={start:{line:1,column:0},end:subtractPos(end,start.line,start.column)}}}return new Mapping(this.sourceLines,sourceLoc,targetLoc)};Mp.add=function(line,column){return new Mapping(this.sourceLines,this.sourceLoc,{start:addPos(this.targetLoc.start,line,column),end:addPos(this.targetLoc.end,line,column)})};function addPos(toPos,line,column){return{line:toPos.line+line-1,column:toPos.line===1?toPos.column+column:toPos.column}}Mp.subtract=function(line,column){return new Mapping(this.sourceLines,this.sourceLoc,{start:subtractPos(this.targetLoc.start,line,column),end:subtractPos(this.targetLoc.end,line,column)})};function subtractPos(fromPos,line,column){return{line:fromPos.line-line+1,column:fromPos.line===line?fromPos.column-column:fromPos.column}}Mp.indent=function(by,skipFirstLine,noNegativeColumns){if(by===0){return this}var targetLoc=this.targetLoc;var startLine=targetLoc.start.line;var endLine=targetLoc.end.line;if(skipFirstLine&&startLine===1&&endLine===1){return this}targetLoc={start:targetLoc.start,end:targetLoc.end};if(!skipFirstLine||startLine>1){var startColumn=targetLoc.start.column+by;targetLoc.start={line:startLine,column:noNegativeColumns?Math.max(0,startColumn):startColumn}}if(!skipFirstLine||endLine>1){var endColumn=targetLoc.end.column+by;targetLoc.end={line:endLine,column:noNegativeColumns?Math.max(0,endColumn):endColumn}}return new Mapping(this.sourceLines,this.sourceLoc,targetLoc)};function skipChars(sourceLines,sourceFromPos,targetLines,targetFromPos,targetToPos){assert.ok(sourceLines instanceof linesModule.Lines);assert.ok(targetLines instanceof linesModule.Lines);Position.assert(sourceFromPos);Position.assert(targetFromPos);Position.assert(targetToPos);var targetComparison=comparePos(targetFromPos,targetToPos);if(targetComparison===0){return sourceFromPos}if(targetComparison<0){var sourceCursor=sourceLines.skipSpaces(sourceFromPos);var targetCursor=targetLines.skipSpaces(targetFromPos);var lineDiff=targetToPos.line-targetCursor.line;sourceCursor.line+=lineDiff;targetCursor.line+=lineDiff;if(lineDiff>0){sourceCursor.column=0;targetCursor.column=0}else{assert.strictEqual(lineDiff,0)}while(comparePos(targetCursor,targetToPos)<0&&targetLines.nextPos(targetCursor,true)){assert.ok(sourceLines.nextPos(sourceCursor,true));assert.strictEqual(sourceLines.charAt(sourceCursor),targetLines.charAt(targetCursor))}}else{var sourceCursor=sourceLines.skipSpaces(sourceFromPos,true);var targetCursor=targetLines.skipSpaces(targetFromPos,true);var lineDiff=targetToPos.line-targetCursor.line;sourceCursor.line+=lineDiff;targetCursor.line+=lineDiff;if(lineDiff<0){sourceCursor.column=sourceLines.getLineLength(sourceCursor.line);targetCursor.column=targetLines.getLineLength(targetCursor.line)}else{assert.strictEqual(lineDiff,0)}while(comparePos(targetToPos,targetCursor)<0&&targetLines.prevPos(targetCursor,true)){assert.ok(sourceLines.prevPos(sourceCursor,true));assert.strictEqual(sourceLines.charAt(sourceCursor),targetLines.charAt(targetCursor))}}return sourceCursor}},{"./lines":148,"./types":154,"./util":155,assert:91}],150:[function(require,module,exports){var defaults={esprima:require("esprima-fb"),tabWidth:4,useTabs:false,reuseWhitespace:true,wrapColumn:74,sourceFileName:null,sourceMapName:null,sourceRoot:null,inputSourceMap:null,range:false,tolerant:true},hasOwn=defaults.hasOwnProperty;exports.normalize=function(options){options=options||defaults;function get(key){return hasOwn.call(options,key)?options[key]:defaults[key]}return{tabWidth:+get("tabWidth"),useTabs:!!get("useTabs"),reuseWhitespace:!!get("reuseWhitespace"),wrapColumn:Math.max(get("wrapColumn"),0),sourceFileName:get("sourceFileName"),sourceMapName:get("sourceMapName"),sourceRoot:get("sourceRoot"),inputSourceMap:get("inputSourceMap"),esprima:get("esprima"),range:get("range"),tolerant:get("tolerant")}}},{"esprima-fb":146}],151:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isObject=types.builtInTypes.object;var isArray=types.builtInTypes.array;var isFunction=types.builtInTypes.function;var Patcher=require("./patcher").Patcher;var normalizeOptions=require("./options").normalize;var fromString=require("./lines").fromString;var attachComments=require("./comments").attach;exports.parse=function parse(source,options){options=normalizeOptions(options);var lines=fromString(source,options);var sourceWithoutTabs=lines.toString({tabWidth:options.tabWidth,reuseWhitespace:false,useTabs:false});var program=options.esprima.parse(sourceWithoutTabs,{loc:true,range:options.range,comment:true,tolerant:options.tolerant});var comments=program.comments;delete program.comments;var file=b.file(program);file.loc={lines:lines,indent:0,start:lines.firstPos(),end:lines.lastPos()};var copy=new TreeCopier(lines).copy(file);attachComments(comments,copy.program,lines);return copy};function TreeCopier(lines){assert.ok(this instanceof TreeCopier);this.lines=lines;this.indent=0}var TCp=TreeCopier.prototype;TCp.copy=function(node){if(isArray.check(node)){return node.map(this.copy,this)}if(!isObject.check(node)){return node}if(n.MethodDefinition&&n.MethodDefinition.check(node)||n.Property.check(node)&&(node.method||node.shorthand)){node.value.loc=null;if(n.FunctionExpression.check(node.value)){node.value.id=null}}var copy=Object.create(Object.getPrototypeOf(node),{original:{value:node,configurable:false,enumerable:false,writable:true}});var loc=node.loc;var oldIndent=this.indent;var newIndent=oldIndent;if(loc){if(loc.start.line<1){loc.start.line=1}if(loc.end.line<1){loc.end.line=1}if(this.lines.isPrecededOnlyByWhitespace(loc.start)){newIndent=this.indent=loc.start.column}loc.lines=this.lines;loc.indent=newIndent}var keys=Object.keys(node);var keyCount=keys.length;for(var i=0;i<keyCount;++i){var key=keys[i];if(key==="loc"){copy[key]=node[key]}else if(key==="comments"){}else{copy[key]=this.copy(node[key])}}this.indent=oldIndent;if(node.comments){Object.defineProperty(copy,"comments",{value:node.comments,enumerable:false})}return copy}},{"./comments":147,"./lines":148,"./options":150,"./patcher":152,"./types":154,assert:91}],152:[function(require,module,exports){var assert=require("assert");var linesModule=require("./lines");var types=require("./types");var getFieldValue=types.getFieldValue;var Node=types.namedTypes.Node;var Expression=types.namedTypes.Expression;var SourceLocation=types.namedTypes.SourceLocation;var util=require("./util");var comparePos=util.comparePos;var NodePath=types.NodePath;var isObject=types.builtInTypes.object;var isArray=types.builtInTypes.array;var isString=types.builtInTypes.string;function Patcher(lines){assert.ok(this instanceof Patcher);assert.ok(lines instanceof linesModule.Lines);var self=this,replacements=[];self.replace=function(loc,lines){if(isString.check(lines))lines=linesModule.fromString(lines);replacements.push({lines:lines,start:loc.start,end:loc.end})};self.get=function(loc){loc=loc||{start:{line:1,column:0},end:{line:lines.length,column:lines.getLineLength(lines.length)}};var sliceFrom=loc.start,toConcat=[];function pushSlice(from,to){assert.ok(comparePos(from,to)<=0);toConcat.push(lines.slice(from,to))}replacements.sort(function(a,b){return comparePos(a.start,b.start)}).forEach(function(rep){if(comparePos(sliceFrom,rep.start)>0){}else{pushSlice(sliceFrom,rep.start);toConcat.push(rep.lines);sliceFrom=rep.end}});pushSlice(sliceFrom,loc.end);return linesModule.concat(toConcat)}}exports.Patcher=Patcher;exports.getReprinter=function(path){assert.ok(path instanceof NodePath);var node=path.value;if(!Node.check(node))return;var orig=node.original;var origLoc=orig&&orig.loc;var lines=origLoc&&origLoc.lines;var reprints=[];if(!lines||!findReprints(path,reprints))return;return function(print){var patcher=new Patcher(lines);reprints.forEach(function(reprint){var old=reprint.oldPath.value;SourceLocation.assert(old.loc,true);patcher.replace(old.loc,print(reprint.newPath).indentTail(old.loc.indent))});return patcher.get(origLoc).indentTail(-orig.loc.indent)}};function findReprints(newPath,reprints){var newNode=newPath.value;Node.assert(newNode);var oldNode=newNode.original;Node.assert(oldNode);assert.deepEqual(reprints,[]);if(newNode.type!==oldNode.type){return false}var oldPath=new NodePath(oldNode);var canReprint=findChildReprints(newPath,oldPath,reprints);if(!canReprint){reprints.length=0}return canReprint}function findAnyReprints(newPath,oldPath,reprints){var newNode=newPath.value;var oldNode=oldPath.value;if(newNode===oldNode)return true;if(isArray.check(newNode))return findArrayReprints(newPath,oldPath,reprints);if(isObject.check(newNode))return findObjectReprints(newPath,oldPath,reprints);return false}function findArrayReprints(newPath,oldPath,reprints){var newNode=newPath.value;var oldNode=oldPath.value;isArray.assert(newNode);var len=newNode.length;if(!(isArray.check(oldNode)&&oldNode.length===len))return false;for(var i=0;i<len;++i)if(!findAnyReprints(newPath.get(i),oldPath.get(i),reprints))return false;return true}function findObjectReprints(newPath,oldPath,reprints){var newNode=newPath.value;isObject.assert(newNode);if(newNode.original===null){return false}var oldNode=oldPath.value;if(!isObject.check(oldNode))return false;if(Node.check(newNode)){if(!Node.check(oldNode)){return false}if(!oldNode.loc){return false}if(newNode.type===oldNode.type){var childReprints=[];if(findChildReprints(newPath,oldPath,childReprints)){reprints.push.apply(reprints,childReprints)}else{reprints.push({newPath:newPath,oldPath:oldPath})}return true}if(Expression.check(newNode)&&Expression.check(oldNode)){reprints.push({newPath:newPath,oldPath:oldPath});return true}return false}return findChildReprints(newPath,oldPath,reprints)}var reusablePos={line:1,column:0};function hasOpeningParen(oldPath){var oldNode=oldPath.value;var loc=oldNode.loc;var lines=loc&&loc.lines;if(lines){var pos=reusablePos;pos.line=loc.start.line;pos.column=loc.start.column;while(lines.prevPos(pos)){var ch=lines.charAt(pos);if(ch==="("){var rootPath=oldPath;while(rootPath.parentPath)rootPath=rootPath.parentPath;return comparePos(rootPath.value.loc.start,pos)<=0}if(ch!==" "){return false}}}return false}function hasClosingParen(oldPath){var oldNode=oldPath.value;var loc=oldNode.loc;var lines=loc&&loc.lines;if(lines){var pos=reusablePos;pos.line=loc.end.line;pos.column=loc.end.column;do{var ch=lines.charAt(pos);if(ch===")"){var rootPath=oldPath;while(rootPath.parentPath)rootPath=rootPath.parentPath;return comparePos(pos,rootPath.value.loc.end)<=0}if(ch!==" "){return false}}while(lines.nextPos(pos))}return false}function hasParens(oldPath){return hasOpeningParen(oldPath)&&hasClosingParen(oldPath)}function findChildReprints(newPath,oldPath,reprints){var newNode=newPath.value;var oldNode=oldPath.value;isObject.assert(newNode);isObject.assert(oldNode);if(newNode.original===null){return false}if(!newPath.canBeFirstInStatement()&&newPath.firstInStatement()&&!hasOpeningParen(oldPath))return false;if(newPath.needsParens(true)&&!hasParens(oldPath)){return false}for(var k in util.getUnionOfKeys(newNode,oldNode)){if(k==="loc")continue;if(!findAnyReprints(newPath.get(k),oldPath.get(k),reprints))return false}return true}},{"./lines":148,"./types":154,"./util":155,assert:91}],153:[function(require,module,exports){var assert=require("assert");var sourceMap=require("source-map");var printComments=require("./comments").printComments;var linesModule=require("./lines");var fromString=linesModule.fromString;var concat=linesModule.concat;var normalizeOptions=require("./options").normalize;var getReprinter=require("./patcher").getReprinter;var types=require("./types");var namedTypes=types.namedTypes;var isString=types.builtInTypes.string;var isObject=types.builtInTypes.object;var NodePath=types.NodePath;var util=require("./util");function PrintResult(code,sourceMap){assert.ok(this instanceof PrintResult);isString.assert(code);this.code=code;if(sourceMap){isObject.assert(sourceMap);this.map=sourceMap}}var PRp=PrintResult.prototype;var warnedAboutToString=false;PRp.toString=function(){if(!warnedAboutToString){console.warn("Deprecation warning: recast.print now returns an object with "+"a .code property. You appear to be treating the object as a "+"string, which might still work but is strongly discouraged.");warnedAboutToString=true}return this.code};var emptyPrintResult=new PrintResult("");function Printer(originalOptions){assert.ok(this instanceof Printer);var explicitTabWidth=originalOptions&&originalOptions.tabWidth;var options=normalizeOptions(originalOptions);assert.notStrictEqual(options,originalOptions);options.sourceFileName=null;function printWithComments(path){assert.ok(path instanceof NodePath);return printComments(path.node.comments,print(path),options)}function print(path,includeComments){if(includeComments)return printWithComments(path);assert.ok(path instanceof NodePath);if(!explicitTabWidth){var oldTabWidth=options.tabWidth;var loc=path.node.loc;if(loc&&loc.lines&&loc.lines.guessTabWidth){options.tabWidth=loc.lines.guessTabWidth();var lines=maybeReprint(path);options.tabWidth=oldTabWidth;return lines}}return maybeReprint(path)}function maybeReprint(path){var reprinter=getReprinter(path);if(reprinter)return maybeAddParens(path,reprinter(maybeReprint));return printRootGenerically(path)}function printRootGenerically(path){return genericPrint(path,options,printWithComments)}function printGenerically(path){return genericPrint(path,options,printGenerically)}this.print=function(ast){if(!ast){return emptyPrintResult}var path=ast instanceof NodePath?ast:new NodePath(ast);var lines=print(path,true);return new PrintResult(lines.toString(options),util.composeSourceMaps(options.inputSourceMap,lines.getSourceMap(options.sourceMapName,options.sourceRoot)))};this.printGenerically=function(ast){if(!ast){return emptyPrintResult}var path=ast instanceof NodePath?ast:new NodePath(ast);var oldReuseWhitespace=options.reuseWhitespace;options.reuseWhitespace=false;var pr=new PrintResult(printGenerically(path).toString(options));options.reuseWhitespace=oldReuseWhitespace;return pr}}exports.Printer=Printer;function maybeAddParens(path,lines){return path.needsParens()?concat(["(",lines,")"]):lines}function genericPrint(path,options,printPath){assert.ok(path instanceof NodePath);return maybeAddParens(path,genericPrintNoParens(path,options,printPath))}function genericPrintNoParens(path,options,print){var n=path.value;if(!n){return fromString("") }if(typeof n==="string"){return fromString(n,options)}namedTypes.Node.assert(n);switch(n.type){case"File":path=path.get("program");n=path.node;namedTypes.Program.assert(n);case"Program":return maybeAddSemicolon(printStatementSequence(path.get("body"),options,print));case"EmptyStatement":return fromString("");case"ExpressionStatement":return concat([print(path.get("expression")),";"]);case"BinaryExpression":case"LogicalExpression":case"AssignmentExpression":return fromString(" ").join([print(path.get("left")),n.operator,print(path.get("right"))]);case"MemberExpression":var parts=[print(path.get("object"))];if(n.computed)parts.push("[",print(path.get("property")),"]");else parts.push(".",print(path.get("property")));return concat(parts);case"Path":return fromString(".").join(n.body);case"Identifier":return fromString(n.name,options);case"SpreadElement":case"SpreadElementPattern":case"SpreadProperty":case"SpreadPropertyPattern":return concat(["...",print(path.get("argument"))]);case"FunctionDeclaration":case"FunctionExpression":var parts=[];if(n.async)parts.push("async ");parts.push("function");if(n.generator)parts.push("*");if(n.id)parts.push(" ",print(path.get("id")));parts.push("(",printFunctionParams(path,options,print),") ",print(path.get("body")));return concat(parts);case"ArrowFunctionExpression":var parts=[];if(n.async)parts.push("async ");if(n.params.length===1){parts.push(print(path.get("params",0)))}else{parts.push("(",printFunctionParams(path,options,print),")")}parts.push(" => ",print(path.get("body")));return concat(parts);case"MethodDefinition":var parts=[];if(n.static){parts.push("static ")}parts.push(printMethod(n.kind,path.get("key"),path.get("value"),options,print));return concat(parts);case"YieldExpression":var parts=["yield"];if(n.delegate)parts.push("*");if(n.argument)parts.push(" ",print(path.get("argument")));return concat(parts);case"AwaitExpression":var parts=["await"];if(n.all)parts.push("*");if(n.argument)parts.push(" ",print(path.get("argument")));return concat(parts);case"ModuleDeclaration":var parts=["module",print(path.get("id"))];if(n.source){assert.ok(!n.body);parts.push("from",print(path.get("source")))}else{parts.push(print(path.get("body")))}return fromString(" ").join(parts);case"ImportSpecifier":case"ExportSpecifier":var parts=[print(path.get("id"))];if(n.name)parts.push(" as ",print(path.get("name")));return concat(parts);case"ExportBatchSpecifier":return fromString("*");case"ImportNamespaceSpecifier":return concat(["* as ",print(path.get("id"))]);case"ImportDefaultSpecifier":return print(path.get("id"));case"ExportDeclaration":var parts=["export"];if(n["default"]){parts.push(" default")}else if(n.specifiers&&n.specifiers.length>0){if(n.specifiers.length===1&&n.specifiers[0].type==="ExportBatchSpecifier"){parts.push(" *")}else{parts.push(" { ",fromString(", ").join(path.get("specifiers").map(print))," }")}if(n.source)parts.push(" from ",print(path.get("source")));parts.push(";");return concat(parts)}if(n.declaration){if(!namedTypes.Node.check(n.declaration)){console.log(JSON.stringify(n,null,2))}var decLines=print(path.get("declaration"));parts.push(" ",decLines);if(lastNonSpaceCharacter(decLines)!==";"){parts.push(";")}}return concat(parts);case"ImportDeclaration":var parts=["import "];if(n.specifiers&&n.specifiers.length>0){var foundImportSpecifier=false;path.get("specifiers").each(function(sp){if(sp.name>0){parts.push(", ")}if(namedTypes.ImportDefaultSpecifier.check(sp.value)||namedTypes.ImportNamespaceSpecifier.check(sp.value)){assert.strictEqual(foundImportSpecifier,false)}else{namedTypes.ImportSpecifier.assert(sp.value);if(!foundImportSpecifier){foundImportSpecifier=true;parts.push("{")}}parts.push(print(sp))});if(foundImportSpecifier){parts.push("}")}parts.push(" from ")}parts.push(print(path.get("source")),";");return concat(parts);case"BlockStatement":var naked=printStatementSequence(path.get("body"),options,print);if(naked.isEmpty())return fromString("{}");return concat(["{\n",naked.indent(options.tabWidth),"\n}"]);case"ReturnStatement":var parts=["return"];if(n.argument){var argLines=print(path.get("argument"));if(argLines.length>1&&namedTypes.XJSElement&&namedTypes.XJSElement.check(n.argument)){parts.push(" (\n",argLines.indent(options.tabWidth),"\n)")}else{parts.push(" ",argLines)}}parts.push(";");return concat(parts);case"CallExpression":return concat([print(path.get("callee")),printArgumentsList(path,options,print)]);case"ObjectExpression":case"ObjectPattern":var allowBreak=false,len=n.properties.length,parts=[len>0?"{\n":"{"];path.get("properties").map(function(childPath){var prop=childPath.value;var i=childPath.name;var lines=print(childPath).indent(options.tabWidth);var multiLine=lines.length>1;if(multiLine&&allowBreak){parts.push("\n")}parts.push(lines);if(i<len-1){parts.push(multiLine?",\n\n":",\n");allowBreak=!multiLine}});parts.push(len>0?"\n}":"}");return concat(parts);case"PropertyPattern":return concat([print(path.get("key")),": ",print(path.get("pattern"))]);case"Property":if(n.method||n.kind==="get"||n.kind==="set"){return printMethod(n.kind,path.get("key"),path.get("value"),options,print)}if(path.node.shorthand){return print(path.get("key"))}else{return concat([print(path.get("key")),": ",print(path.get("value"))])}case"ArrayExpression":case"ArrayPattern":var elems=n.elements,len=elems.length,parts=["["];path.get("elements").each(function(elemPath){var elem=elemPath.value;if(!elem){parts.push(",")}else{var i=elemPath.name;if(i>0)parts.push(" ");parts.push(print(elemPath));if(i<len-1)parts.push(",")}});parts.push("]");return concat(parts);case"SequenceExpression":return fromString(", ").join(path.get("expressions").map(print));case"ThisExpression":return fromString("this");case"Literal":if(typeof n.value!=="string")return fromString(n.value,options);case"ModuleSpecifier":return fromString(nodeStr(n),options);case"UnaryExpression":var parts=[n.operator];if(/[a-z]$/.test(n.operator))parts.push(" ");parts.push(print(path.get("argument")));return concat(parts);case"UpdateExpression":var parts=[print(path.get("argument")),n.operator];if(n.prefix)parts.reverse();return concat(parts);case"ConditionalExpression":return concat(["(",print(path.get("test"))," ? ",print(path.get("consequent"))," : ",print(path.get("alternate")),")"]);case"NewExpression":var parts=["new ",print(path.get("callee"))];var args=n.arguments;if(args){parts.push(printArgumentsList(path,options,print))}return concat(parts);case"VariableDeclaration":var parts=[n.kind," "];var maxLen=0;var printed=path.get("declarations").map(function(childPath){var lines=print(childPath);maxLen=Math.max(lines.length,maxLen);return lines});if(maxLen===1){parts.push(fromString(", ").join(printed))}else if(printed.length>1){parts.push(fromString(",\n").join(printed).indentTail(n.kind.length+1))}else{parts.push(printed[0])}var parentNode=path.parent&&path.parent.node;if(!namedTypes.ForStatement.check(parentNode)&&!namedTypes.ForInStatement.check(parentNode)&&!(namedTypes.ForOfStatement&&namedTypes.ForOfStatement.check(parentNode))){parts.push(";")}return concat(parts);case"VariableDeclarator":return n.init?fromString(" = ").join([print(path.get("id")),print(path.get("init"))]):print(path.get("id"));case"WithStatement":return concat(["with (",print(path.get("object")),") ",print(path.get("body"))]);case"IfStatement":var con=adjustClause(print(path.get("consequent")),options),parts=["if (",print(path.get("test")),")",con];if(n.alternate)parts.push(endsWithBrace(con)?" else":"\nelse",adjustClause(print(path.get("alternate")),options));return concat(parts);case"ForStatement":var init=print(path.get("init")),sep=init.length>1?";\n":"; ",forParen="for (",indented=fromString(sep).join([init,print(path.get("test")),print(path.get("update"))]).indentTail(forParen.length),head=concat([forParen,indented,")"]),clause=adjustClause(print(path.get("body")),options),parts=[head];if(head.length>1){parts.push("\n");clause=clause.trimLeft()}parts.push(clause);return concat(parts);case"WhileStatement":return concat(["while (",print(path.get("test")),")",adjustClause(print(path.get("body")),options)]);case"ForInStatement":return concat([n.each?"for each (":"for (",print(path.get("left"))," in ",print(path.get("right")),")",adjustClause(print(path.get("body")),options)]);case"ForOfStatement":return concat(["for (",print(path.get("left"))," of ",print(path.get("right")),")",adjustClause(print(path.get("body")),options)]);case"DoWhileStatement":var doBody=concat(["do",adjustClause(print(path.get("body")),options)]),parts=[doBody];if(endsWithBrace(doBody))parts.push(" while");else parts.push("\nwhile");parts.push(" (",print(path.get("test")),");");return concat(parts);case"BreakStatement":var parts=["break"];if(n.label)parts.push(" ",print(path.get("label")));parts.push(";");return concat(parts);case"ContinueStatement":var parts=["continue"];if(n.label)parts.push(" ",print(path.get("label")));parts.push(";");return concat(parts);case"LabeledStatement":return concat([print(path.get("label")),":\n",print(path.get("body"))]);case"TryStatement":var parts=["try ",print(path.get("block"))];path.get("handlers").each(function(handler){parts.push(" ",print(handler))});if(n.finalizer)parts.push(" finally ",print(path.get("finalizer")));return concat(parts);case"CatchClause":var parts=["catch (",print(path.get("param"))];if(n.guard)parts.push(" if ",print(path.get("guard")));parts.push(") ",print(path.get("body")));return concat(parts);case"ThrowStatement":return concat(["throw ",print(path.get("argument")),";"]);case"SwitchStatement":return concat(["switch (",print(path.get("discriminant")),") {\n",fromString("\n").join(path.get("cases").map(print)),"\n}"]);case"SwitchCase":var parts=[];if(n.test)parts.push("case ",print(path.get("test")),":");else parts.push("default:");if(n.consequent.length>0){parts.push("\n",printStatementSequence(path.get("consequent"),options,print).indent(options.tabWidth))}return concat(parts);case"DebuggerStatement":return fromString("debugger;");case"XJSAttribute":var parts=[print(path.get("name"))];if(n.value)parts.push("=",print(path.get("value")));return concat(parts);case"XJSIdentifier":return fromString(n.name,options);case"XJSNamespacedName":return fromString(":").join([print(path.get("namespace")),print(path.get("name"))]);case"XJSMemberExpression":return fromString(".").join([print(path.get("object")),print(path.get("property"))]);case"XJSSpreadAttribute":return concat(["{...",print(path.get("argument")),"}"]);case"XJSExpressionContainer":return concat(["{",print(path.get("expression")),"}"]);case"XJSElement":var openingLines=print(path.get("openingElement"));if(n.openingElement.selfClosing){assert.ok(!n.closingElement);return openingLines}var childLines=concat(path.get("children").map(function(childPath){var child=childPath.value;if(namedTypes.Literal.check(child)&&typeof child.value==="string"){if(/\S/.test(child.value)){return child.value.replace(/^\s+|\s+$/g,"")}else if(/\n/.test(child.value)){return"\n"}}return print(childPath)})).indentTail(options.tabWidth);var closingLines=print(path.get("closingElement"));return concat([openingLines,childLines,closingLines]);case"XJSOpeningElement":var parts=["<",print(path.get("name"))];var attrParts=[];path.get("attributes").each(function(attrPath){attrParts.push(" ",print(attrPath))});var attrLines=concat(attrParts);var needLineWrap=attrLines.length>1||attrLines.getLineLength(1)>options.wrapColumn;if(needLineWrap){attrParts.forEach(function(part,i){if(part===" "){assert.strictEqual(i%2,0);attrParts[i]="\n"}});attrLines=concat(attrParts).indentTail(options.tabWidth)}parts.push(attrLines,n.selfClosing?" />":">");return concat(parts);case"XJSClosingElement":return concat(["</",print(path.get("name")),">"]);case"XJSText":return fromString(n.value,options);case"XJSEmptyExpression":return fromString("");case"TypeAnnotatedIdentifier":var parts=[print(path.get("annotation"))," ",print(path.get("identifier"))];return concat(parts);case"ClassBody":if(n.body.length===0){return fromString("{}")}return concat(["{\n",printStatementSequence(path.get("body"),options,print).indent(options.tabWidth),"\n}"]);case"ClassPropertyDefinition":var parts=["static ",print(path.get("definition"))];if(!namedTypes.MethodDefinition.check(n.definition))parts.push(";");return concat(parts);case"ClassProperty":return concat([print(path.get("id")),";"]);case"ClassDeclaration":case"ClassExpression":var parts=["class"];if(n.id)parts.push(" ",print(path.get("id")));if(n.superClass)parts.push(" extends ",print(path.get("superClass")));parts.push(" ",print(path.get("body")));return concat(parts);case"Node":case"Printable":case"SourceLocation":case"Position":case"Statement":case"Function":case"Pattern":case"Expression":case"Declaration":case"Specifier":case"NamedSpecifier":case"Block":case"Line":throw new Error("unprintable type: "+JSON.stringify(n.type));case"ClassHeritage":case"ComprehensionBlock":case"ComprehensionExpression":case"Glob":case"TaggedTemplateExpression":case"TemplateElement":case"TemplateLiteral":case"GeneratorExpression":case"LetStatement":case"LetExpression":case"GraphExpression":case"GraphIndexExpression":case"AnyTypeAnnotation":case"BooleanTypeAnnotation":case"ClassImplements":case"DeclareClass":case"DeclareFunction":case"DeclareModule":case"DeclareVariable":case"FunctionTypeAnnotation":case"FunctionTypeParam":case"GenericTypeAnnotation":case"InterfaceDeclaration":case"InterfaceExtends":case"IntersectionTypeAnnotation":case"MemberTypeAnnotation":case"NullableTypeAnnotation":case"NumberTypeAnnotation":case"ObjectTypeAnnotation":case"ObjectTypeCallProperty":case"ObjectTypeIndexer":case"ObjectTypeProperty":case"QualifiedTypeIdentifier":case"StringLiteralTypeAnnotation":case"StringTypeAnnotation":case"TupleTypeAnnotation":case"Type":case"TypeAlias":case"TypeAnnotation":case"TypeParameterDeclaration":case"TypeParameterInstantiation":case"TypeofTypeAnnotation":case"UnionTypeAnnotation":case"VoidTypeAnnotation":case"XMLDefaultDeclaration":case"XMLAnyName":case"XMLQualifiedIdentifier":case"XMLFunctionQualifiedIdentifier":case"XMLAttributeSelector":case"XMLFilterExpression":case"XML":case"XMLElement":case"XMLList":case"XMLEscape":case"XMLText":case"XMLStartTag":case"XMLEndTag":case"XMLPointTag":case"XMLName":case"XMLAttribute":case"XMLCdata":case"XMLComment":case"XMLProcessingInstruction":default:debugger;throw new Error("unknown type: "+JSON.stringify(n.type))}return p}function printStatementSequence(path,options,print){var inClassBody=path.parent&&namedTypes.ClassBody&&namedTypes.ClassBody.check(path.parent.node);var filtered=path.filter(function(stmtPath){var stmt=stmtPath.value;if(!stmt)return false;if(stmt.type==="EmptyStatement")return false;if(!inClassBody){namedTypes.Statement.assert(stmt)}return true});var prevTrailingSpace=null;var len=filtered.length;var parts=[];filtered.forEach(function(stmtPath,i){var printed=print(stmtPath);var stmt=stmtPath.value;var needSemicolon=true;var multiLine=printed.length>1;var notFirst=i>0;var notLast=i<len-1;var leadingSpace;var trailingSpace;if(inClassBody){var stmt=stmtPath.value;if(namedTypes.MethodDefinition.check(stmt)||namedTypes.ClassPropertyDefinition.check(stmt)&&namedTypes.MethodDefinition.check(stmt.definition)){needSemicolon=false}}if(needSemicolon){printed=maybeAddSemicolon(printed)}var trueLoc=options.reuseWhitespace&&getTrueLoc(stmt);var lines=trueLoc&&trueLoc.lines;if(notFirst){if(lines){var beforeStart=lines.skipSpaces(trueLoc.start,true);var beforeStartLine=beforeStart?beforeStart.line:1;var leadingGap=trueLoc.start.line-beforeStartLine;leadingSpace=Array(leadingGap+1).join("\n")}else{leadingSpace=multiLine?"\n\n":"\n"}}else{leadingSpace=""}if(notLast){if(lines){var afterEnd=lines.skipSpaces(trueLoc.end);var afterEndLine=afterEnd?afterEnd.line:lines.length;var trailingGap=afterEndLine-trueLoc.end.line;trailingSpace=Array(trailingGap+1).join("\n")}else{trailingSpace=multiLine?"\n\n":"\n"}}else{trailingSpace=""}parts.push(maxSpace(prevTrailingSpace,leadingSpace),printed);if(notLast){prevTrailingSpace=trailingSpace}else if(trailingSpace){parts.push(trailingSpace)}});return concat(parts)}function getTrueLoc(node){if(!node.loc){return null}if(!node.comments){return node.loc}var start=node.loc.start;var end=node.loc.end;node.comments.forEach(function(comment){if(comment.loc){if(util.comparePos(comment.loc.start,start)<0){start=comment.loc.start}if(util.comparePos(end,comment.loc.end)<0){end=comment.loc.end}}});return{lines:node.loc.lines,start:start,end:end}}function maxSpace(s1,s2){if(!s1&&!s2){return fromString("")}if(!s1){return fromString(s2)}if(!s2){return fromString(s1)}var spaceLines1=fromString(s1);var spaceLines2=fromString(s2);if(spaceLines2.length>spaceLines1.length){return spaceLines2}return spaceLines1}function printMethod(kind,keyPath,valuePath,options,print){var parts=[];var key=keyPath.value;var value=valuePath.value;namedTypes.FunctionExpression.assert(value);if(value.async){parts.push("async ")}if(!kind||kind==="init"){if(value.generator){parts.push("*")}}else{assert.ok(kind==="get"||kind==="set");parts.push(kind," ")}parts.push(print(keyPath),"(",printFunctionParams(valuePath,options,print),") ",print(valuePath.get("body")));return concat(parts)}function printArgumentsList(path,options,print){var printed=path.get("arguments").map(print);var joined=fromString(", ").join(printed);if(joined.getLineLength(1)>options.wrapColumn){joined=fromString(",\n").join(printed);return concat(["(\n",joined.indent(options.tabWidth),"\n)"])}return concat(["(",joined,")"])}function printFunctionParams(path,options,print){var fun=path.node;namedTypes.Function.assert(fun);var params=path.get("params");var defaults=path.get("defaults");var printed=params.map(defaults.value?function(param){var p=print(param);var d=defaults.get(param.name);return d.value?concat([p,"=",print(d)]):p}:print);if(fun.rest){printed.push(concat(["...",print(path.get("rest"))]))}var joined=fromString(", ").join(printed);if(joined.length>1||joined.getLineLength(1)>options.wrapColumn){joined=fromString(",\n").join(printed);return concat(["\n",joined.indent(options.tabWidth)])}return joined}function adjustClause(clause,options){if(clause.length>1)return concat([" ",clause]);return concat(["\n",maybeAddSemicolon(clause).indent(options.tabWidth)])}function lastNonSpaceCharacter(lines){var pos=lines.lastPos();do{var ch=lines.charAt(pos);if(/\S/.test(ch))return ch}while(lines.prevPos(pos))}function endsWithBrace(lines){return lastNonSpaceCharacter(lines)==="}"}function nodeStr(n){namedTypes.Literal.assert(n);isString.assert(n.value);return JSON.stringify(n.value)}function maybeAddSemicolon(lines){var eoc=lastNonSpaceCharacter(lines);if(!eoc||"\n};".indexOf(eoc)<0)return concat([lines,";"]);return lines}},{"./comments":147,"./lines":148,"./options":150,"./patcher":152,"./types":154,"./util":155,assert:91,"source-map":165}],154:[function(require,module,exports){var types=require("ast-types");var def=types.Type.def;def("File").bases("Node").build("program").field("program",def("Program"));types.finalize();module.exports=types},{"ast-types":89}],155:[function(require,module,exports){var assert=require("assert");var getFieldValue=require("./types").getFieldValue;var sourceMap=require("source-map");var SourceMapConsumer=sourceMap.SourceMapConsumer;var SourceMapGenerator=sourceMap.SourceMapGenerator;var hasOwn=Object.prototype.hasOwnProperty;function getUnionOfKeys(){var result={};var argc=arguments.length;for(var i=0;i<argc;++i){var keys=Object.keys(arguments[i]);var keyCount=keys.length;for(var j=0;j<keyCount;++j){result[keys[j]]=true}}return result}exports.getUnionOfKeys=getUnionOfKeys;function comparePos(pos1,pos2){return pos1.line-pos2.line||pos1.column-pos2.column}exports.comparePos=comparePos;exports.composeSourceMaps=function(formerMap,latterMap){if(formerMap){if(!latterMap){return formerMap}}else{return latterMap||null}var smcFormer=new SourceMapConsumer(formerMap);var smcLatter=new SourceMapConsumer(latterMap);var smg=new SourceMapGenerator({file:latterMap.file,sourceRoot:latterMap.sourceRoot});var sourcesToContents={};smcLatter.eachMapping(function(mapping){var origPos=smcFormer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});var sourceName=origPos.source;if(sourceName===null){return}smg.addMapping({source:sourceName,original:{line:origPos.line,column:origPos.column},generated:{line:mapping.generatedLine,column:mapping.generatedColumn},name:mapping.name});var sourceContent=smcFormer.sourceContentFor(sourceName);if(sourceContent&&!hasOwn.call(sourcesToContents,sourceName)){sourcesToContents[sourceName]=sourceContent;smg.setSourceContent(sourceName,sourceContent)}});return smg.toJSON()}},{"./types":154,assert:91,"source-map":165}],156:[function(require,module,exports){(function(process){var types=require("./lib/types");var parse=require("./lib/parser").parse;var Printer=require("./lib/printer").Printer;function print(node,options){return new Printer(options).print(node)}function prettyPrint(node,options){return new Printer(options).printGenerically(node)}function run(transformer,options){return runFile(process.argv[2],transformer,options)}function runFile(path,transformer,options){require("fs").readFile(path,"utf-8",function(err,code){if(err){console.error(err);return}runString(code,transformer,options)})}function defaultWriteback(output){process.stdout.write(output)}function runString(code,transformer,options){var writeback=options&&options.writeback||defaultWriteback;transformer(parse(code,options),function(node){writeback(print(node,options).code)})}Object.defineProperties(exports,{parse:{enumerable:true,value:parse},visit:{enumerable:true,value:types.visit},print:{enumerable:true,value:print},prettyPrint:{enumerable:false,value:prettyPrint},types:{enumerable:false,value:types},run:{enumerable:false,value:run}})}).call(this,require("_process"))},{"./lib/parser":151,"./lib/printer":153,"./lib/types":154,_process:100,fs:90}],157:[function(require,module,exports){(function(process){var Stream=require("stream");exports=module.exports=through;through.through=through;function through(write,end,opts){write=write||function(data){this.queue(data)};end=end||function(){this.queue(null)};var ended=false,destroyed=false,buffer=[],_ended=false;var stream=new Stream;stream.readable=stream.writable=true;stream.paused=false;stream.autoDestroy=!(opts&&opts.autoDestroy===false);stream.write=function(data){write.call(this,data);return!stream.paused};function drain(){while(buffer.length&&!stream.paused){var data=buffer.shift();if(null===data)return stream.emit("end");else stream.emit("data",data)}}stream.queue=stream.push=function(data){if(_ended)return stream;if(data==null)_ended=true;buffer.push(data);drain();return stream};stream.on("end",function(){stream.readable=false;if(!stream.writable&&stream.autoDestroy)process.nextTick(function(){stream.destroy()})});function _end(){stream.writable=false;end.call(stream);if(!stream.readable&&stream.autoDestroy)stream.destroy()}stream.end=function(data){if(ended)return;ended=true;if(arguments.length)stream.write(data);_end();return stream};stream.destroy=function(){if(destroyed)return;destroyed=true;ended=true;buffer.length=0;stream.writable=stream.readable=false;stream.emit("close");return stream};stream.pause=function(){if(stream.paused)return;stream.paused=true;return stream};stream.resume=function(){if(stream.paused){stream.paused=false;stream.emit("resume")}drain();if(!stream.paused)stream.emit("drain");return stream};return stream}}).call(this,require("_process"))},{_process:100,stream:112}],158:[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}}}()},{}],159:[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:161}],160:[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}},{}],161:[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:{})},{}],162:[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:{})},{}],163:[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,})\}/))){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}})()},{}],164:[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":159,"./data/iu-mappings.json":160,regenerate:161,regjsgen:162,regjsparser:163}],165:[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":170,"./source-map/source-map-generator":171,"./source-map/source-node":172}],166:[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":173,amdefine:174}],167:[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":168,amdefine:174}],168:[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:174}],169:[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:174}],170:[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":166,"./base64-vlq":167,"./binary-search":169,"./util":173,amdefine:174}],171:[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":166,"./base64-vlq":167,"./util":173,amdefine:174}],172:[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":171,"./util":173,amdefine:174}],173:[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:174}],174:[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:100,path:99}],175:[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:"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:"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:"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-super-constructor-call":{type:"Program",body:[{type:"IfStatement",test:{type:"Identifier",name:"SUPER_NAME"},consequent:{type:"BlockStatement",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"}]}}]},alternate:null}]},"corejs-iterator":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"CORE_ID"},property:{type:"Identifier",name:"$for"},computed:false},property:{type:"Identifier",name:"getIterator"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"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-override":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"exports"},right:{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-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-wildcard":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{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"}]}}]},"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:"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:"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}]},inherits:{type:"Program",body:[{type:"ExpressionStatement",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:"LogicalExpression",left:{type:"Identifier",name:"parent"},operator:"&&",right:{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:"IfStatement",test:{type:"Identifier",name:"parent"},consequent:{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"}}},alternate:null}]},expression:false}}]},"interop-require":{type:"Program",body:[{type:"ExpressionStatement",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:"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:"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-getter-memoization":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperty"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"KEY"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},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"},{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:"value"},value:{type:"Identifier",name:"VALUE"},kind:"init"}]}]}}]},"object-without-properties":{type:"Program",body:[{type:"ExpressionStatement",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}}]},"prototype-properties":{type:"Program",body:[{type:"ExpressionStatement",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}}]},"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}}]},"sliced-to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"},{type:"Identifier",name:"i"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",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:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"arr"}}]},alternate:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"_arr"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"_iterator"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"arr"},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"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"_step"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"_iterator"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"_arr"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"_step"},property:{type:"Identifier",name:"value"},computed:false}]}},{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"Identifier",name:"i"},operator:"&&",right:{type:"BinaryExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"_arr"},property:{type:"Identifier",name:"length"},computed:false},operator:"===",right:{type:"Identifier",name:"i"}}},consequent:{type:"BreakStatement",label:null},alternate:null}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"_arr"}}]}}]},expression:false}}]},system:{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:"FunctionExpression",id:null,params:[{type:"Identifier",name:"EXPORT_IDENTIFIER"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"setters"},value:{type:"Identifier",name:"SETTERS"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"execute"},value:{type:"Identifier",name:"EXECUTE"},kind:"init"}]}}]},expression:false}]}}]},"tagged-template-literal":{type:"Program",body:[{type:"ExpressionStatement",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:"freeze"},computed:false},arguments:[{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:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"freeze"},computed:false},arguments:[{type:"Identifier",name:"raw"}]},kind:"init"}]},kind:"init"}]}]}]}}]},expression:false}}]},"to-array":{type:"Program",body:[{type:"ExpressionStatement",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:"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)});
app/components/Right/About/AboutPaper.js
SpotifiyOrganization/spotifyHack
import React from 'react'; import { Row } from 'react-materialize'; const AboutPaper = () => { return ( <Row style={{height: '95vh', marginBottom: '0'}}> <Row style={{paddingTop: '20px', paddingLeft: '20px', paddingRight: '20px'}}> <Row><h5>About Us</h5></Row> <Row><a href="https://www.linkedin.com/in/ryanmargono/"><h>Ryan Margono: web scraping / front end / back end</h></a> </Row> <Row><a href="https://www.linkedin.com/in/erenchen/"><h>Eren Chen: web scraping / play/pause function</h> </a> </Row> <Row><a href="https://www.linkedin.com/in/alvinwen424/"><h>Alvin Wen: web audio</h> </a></Row> <Row><a href="https://www.linkedin.com/in/mikhailqader/"><h>Mikhail Qadar: web audio</h> </a></Row> </Row> </Row> ); } export default AboutPaper;
ajax/libs/aui/5.6.7/aui/js/aui-dependencies.js
narikei/cdnjs
!function(){"use strict";function a(c,d){p||(p=new o(function(b){b.forEach(function(b){a.init(b.addedNodes),f(b.removedNodes)})}),p.observe(document,{childList:!0,subtree:!0})),d||(d={}),"function"==typeof d&&(d={insert:d}),l(d,a.defaults);var e=m(c,d);d.ready&&n.sheet.insertRule(c+":not(."+d.classname+"),["+c+"]:not(."+d.classname+"),."+c+":not(."+d.classname+"){display:none}",n.sheet.cssRules.length);for(var g=e.existing(),h=0;h<g.length;h++)b(c,d,g[h]);return q[c]=d,e}function b(a,b,e){h(e,"blacklisted")||c(a,b,e,function(c){if(!c)return d(a,b,e);if(c!==e&&e.parentNode){var f=document.createComment("placeholder");if(e.parentNode.insertBefore(f,e),e.parentNode.removeChild(e),"string"==typeof c){var g=document.createElement("div");g.innerHTML=c,c=g.children}j(c,function(a){f.parentNode.insertBefore(a,f)}),f.parentNode.removeChild(f)}})}function c(a,b,c,d){var e=/^[^(]+\([^,)]+,/,f=b.ready;return d=d||function(){},h(c,a+".ready-called")?d():(h(c,a+".ready-called",!0),l(c,b.prototype),void(f&&e.test(f)?f(c,d):f?d(f(c)):d()))}function d(a,b,c){var d=b.insert;h(c,a+".insert-called")||c.parentNode&&(h(c,a+".insert-called",!0),g(a,b,c),i(c,b.classname),d&&d(c))}function e(a,b,c){!b.remove||h(c,"blacklisted")||h(c,a+".remove-called")||(h(c,a+".remove-called",!0),b.remove(c))}function f(a){j(a,function(a){f(a.children);for(var b in k(a))b in q&&e(b,q[b],a)})}function g(a,b,c){function d(a,b,c){(a.insert||a.update||a)(b,c)}function e(a,b,c,d){(a.update||a)(b,c,d)}function f(a,b,c){a.remove(b,c)}if(b.attributes&&!h(c,a+".attributes-called")){h(c,a+".attributes-called",!0);var g=new o(function(a){a.forEach(function(a){var g=a.attributeName,h=c.attributes[g],i=b.attributes[g];i&&(h&&null===a.oldValue&&(i.insert||i.update||i)?d(i,c,h.nodeValue):h&&null!==a.oldValue&&(i.update||i)?e(i,c,h.nodeValue,a.oldValue):!h&&i.remove&&f(i,c,a.oldValue))})});g.observe(c,{attributes:!0,attributeOldValue:!0});for(var i=0;i<c.attributes.length;i++){var j=c.attributes[i],k=b.attributes[j.nodeName];k&&d(k,c,j.nodeValue)}}}function h(a,b,c){return void 0===c?a.__SKATE_DATA&&a.__SKATE_DATA[b]:(a.__SKATE_DATA||(a.__SKATE_DATA={}),a.__SKATE_DATA[b]=c,a)}function i(a,b){a.classList?a.classList.add(b):a.className+=a.className?" "+b:b}function j(a,b){if(a){if(a.nodeType){if(1!==a.nodeType)return;a=[a]}if(a.length)for(var c=0;c<a.length;c++)a[c]&&1===a[c].nodeType&&b(a[c],c)}}function k(a){var b=h(a,"possible-ids");if(b)return b;var c=a.tagName.toLowerCase();b={},b[c]=c;for(var d=0;d<a.attributes.length;d++){var e=a.attributes[d].nodeName;b[e]=e}return a.className.split(" ").forEach(function(a){a&&(b[a]=a)}),h(a,"possible-ids",b),b}function l(a,b){for(var c in b)void 0===a[c]&&(a[c]=b[c]);return a}function m(b,d){var e=d.type.indexOf(a.types.TAG)>-1,f=d.type.indexOf(a.types.ATTR)>-1,g=d.type.indexOf(a.types.CLASS)>-1,h=function(){var a=[];return e&&a.push(b),f&&a.push("["+b+"]"),g&&a.push("."+b),a.join(", ")}(),i=function(){if(!e)throw new Error('Cannot construct "'+b+'" as a custom element.');var a=document.createElement(b);return c(b,d,a),a};return i.existing=function(a){return(a||document).querySelectorAll(i.selector())},i.selector=function(){return h},i}var n=document.createElement("style"),o=window.MutationObserver||window.WebkitMutationObserver||window.MozMutationObserver;o||(o=function(a){this.callback=a,this.elements=[]},o.prototype={observe:function(a,b){function c(c){return b.childList&&(b.subtree||c.target.parentNode===a)}function d(b){return b.target===a}function e(a,b){return l(b,{addedNodes:null,attributeName:null,attributeNamespace:null,nextSibling:a.target.nextSibling,oldValue:null,previousSibling:a.target.previousSibling,removedNodes:null,target:a.target,type:"childList"})}var f=this,g={},h={target:a,options:b,insertHandler:function(a){c(a)&&f.callback([e(a,{addedNodes:[a.target]})])},removeHandler:function(a){c(a)&&f.callback([e(a,{removedNodes:[a.target]})])},attributeHandler:function(a){d(a)&&(f.callback([e(a,{attributeName:a.attrName,oldValue:b.attributeOldValue?g[a.attrName]||a.prevValue||null:null,type:"attributes"})]),b.attributeOldValue&&(g[a.attrName]=a.newValue))}};return this.elements.push(h),b.childList&&(a.addEventListener("DOMSubtreeModified",h.insertHandler),a.addEventListener("DOMNodeRemoved",h.removeHandler)),b.attributes&&a.addEventListener("DOMAttrModified",h.attributeHandler),this},disconnect:function(){for(var a in this.elements){var b=this.elements[a];b.target.removeEventListener("DOMSubtreeModified",b.insertHandler),b.target.removeEventListener("DOMNodeRemoved",b.removeHandler),b.target.removeEventListener("DOMAttrModified",b.attributeHandler)}}});var p,q={};a.types={ANY:"act",ATTR:"a",CLASS:"c",NOATTR:"ct",NOCLASS:"at",NOTAG:"ac",TAG:"t"},a.defaults={attributes:!1,classname:"__skate",listen:!0,prototype:{},type:a.types.ANY},a.blacklist=function(b,c){return void 0===c&&(c=!0),j(b,function(b){h(b,"blacklisted",!0),c&&a.blacklist(b.children,!0)}),a},a.destroy=function(){return p.disconnect(),p=void 0,q={},a},a.init=function(c){return j(c,function(c){for(var d in k(c))d in q&&b(d,q[d],c);a.init(c.children)}),a},a.watch=function(a){return new o(a)},a.whitelist=function(b,c){return void 0===c&&(c=!0),j(b,function(b){h(b,"blacklisted",void 0),c&&a.whitelist(b.children,!0)}),a},document.getElementsByTagName("head")[0].appendChild(n),"function"==typeof define&&define.amd?define("skate",[],function(){return a}):window.skate=a}(),function(a,b){"function"==typeof define&&define.amd?define(b):"object"==typeof exports?module.exports=b(require,exports,module):a.Tether=b()}(this,function(){return function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r={}.hasOwnProperty,s=[].indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(b in this&&this[b]===a)return b;return-1},t=[].slice;null==this.Tether&&(this.Tether={modules:[]}),k=function(a){var b,c,d,e,f;if(c=getComputedStyle(a).position,"fixed"===c)return a;for(d=void 0,b=a;b=b.parentNode;){try{e=getComputedStyle(b)}catch(g){}if(null==e)return b;if(/(auto|scroll)/.test(e.overflow+e["overflow-y"]+e["overflow-x"])&&("absolute"!==c||"relative"===(f=e.position)||"absolute"===f||"fixed"===f))return b}return document.body},o=function(){var a;return a=0,function(){return a++}}(),q={},i=function(a){var b,d,f,g,h;if(f=a._tetherZeroElement,null==f&&(f=a.createElement("div"),f.setAttribute("data-tether-id",o()),e(f.style,{top:0,left:0,position:"absolute"}),a.body.appendChild(f),a._tetherZeroElement=f),b=f.getAttribute("data-tether-id"),null==q[b]){q[b]={},h=f.getBoundingClientRect();for(d in h)g=h[d],q[b][d]=g;c(function(){return q[b]=void 0})}return q[b]},m=null,g=function(a){var b,c,d,e,f,g,h;a===document?(c=document,a=document.documentElement):c=a.ownerDocument,d=c.documentElement,b={},h=a.getBoundingClientRect();for(e in h)g=h[e],b[e]=g;return f=i(c),b.top-=f.top,b.left-=f.left,null==b.width&&(b.width=document.body.scrollWidth-b.left-b.right),null==b.height&&(b.height=document.body.scrollHeight-b.top-b.bottom),b.top=b.top-d.clientTop,b.left=b.left-d.clientLeft,b.right=c.body.clientWidth-b.width-b.left,b.bottom=c.body.clientHeight-b.height-b.top,b},h=function(a){return a.offsetParent||document.documentElement},j=function(){var a,b,c,d,f;return a=document.createElement("div"),a.style.width="100%",a.style.height="200px",b=document.createElement("div"),e(b.style,{position:"absolute",top:0,left:0,pointerEvents:"none",visibility:"hidden",width:"200px",height:"150px",overflow:"hidden"}),b.appendChild(a),document.body.appendChild(b),d=a.offsetWidth,b.style.overflow="scroll",f=a.offsetWidth,d===f&&(f=b.clientWidth),document.body.removeChild(b),c=d-f,{width:c,height:c}},e=function(a){var b,c,d,e,f,g,h;for(null==a&&(a={}),b=[],Array.prototype.push.apply(b,arguments),h=b.slice(1),f=0,g=h.length;g>f;f++)if(d=h[f])for(c in d)r.call(d,c)&&(e=d[c],a[c]=e);return a},n=function(a,b){var c,d,e,f,g;if(null!=a.classList){for(f=b.split(" "),g=[],d=0,e=f.length;e>d;d++)c=f[d],c.trim()&&g.push(a.classList.remove(c));return g}return a.className=a.className.replace(new RegExp("(^| )"+b.split(" ").join("|")+"( |$)","gi")," ")},b=function(a,b){var c,d,e,f,g;if(null!=a.classList){for(f=b.split(" "),g=[],d=0,e=f.length;e>d;d++)c=f[d],c.trim()&&g.push(a.classList.add(c));return g}return n(a,b),a.className+=" "+b},l=function(a,b){return null!=a.classList?a.classList.contains(b):new RegExp("(^| )"+b+"( |$)","gi").test(a.className)},p=function(a,c,d){var e,f,g,h,i,j;for(f=0,h=d.length;h>f;f++)e=d[f],s.call(c,e)<0&&l(a,e)&&n(a,e);for(j=[],g=0,i=c.length;i>g;g++)e=c[g],j.push(l(a,e)?void 0:b(a,e));return j},d=[],c=function(a){return d.push(a)},f=function(){var a,b;for(b=[];a=d.pop();)b.push(a());return b},a=function(){function a(){}return a.prototype.on=function(a,b,c,d){var e;return null==d&&(d=!1),null==this.bindings&&(this.bindings={}),null==(e=this.bindings)[a]&&(e[a]=[]),this.bindings[a].push({handler:b,ctx:c,once:d})},a.prototype.once=function(a,b,c){return this.on(a,b,c,!0)},a.prototype.off=function(a,b){var c,d,e;if(null!=(null!=(d=this.bindings)?d[a]:void 0)){if(null==b)return delete this.bindings[a];for(c=0,e=[];c<this.bindings[a].length;)e.push(this.bindings[a][c].handler===b?this.bindings[a].splice(c,1):c++);return e}},a.prototype.trigger=function(){var a,b,c,d,e,f,g,h,i;if(c=arguments[0],a=2<=arguments.length?t.call(arguments,1):[],null!=(g=this.bindings)?g[c]:void 0){for(e=0,i=[];e<this.bindings[c].length;)h=this.bindings[c][e],d=h.handler,b=h.ctx,f=h.once,d.apply(null!=b?b:this,a),i.push(f?this.bindings[c].splice(e,1):e++);return i}},a}(),this.Tether.Utils={getScrollParent:k,getBounds:g,getOffsetParent:h,extend:e,addClass:b,removeClass:n,hasClass:l,updateClasses:p,defer:c,flush:f,uniqueId:o,Evented:a,getScrollBarSize:j}}.call(this),function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D=[].slice,E=function(a,b){return function(){return a.apply(b,arguments)}};if(null==this.Tether)throw new Error("You must include the utils.js file before tether.js");d=this.Tether,C=d.Utils,p=C.getScrollParent,q=C.getSize,n=C.getOuterSize,l=C.getBounds,m=C.getOffsetParent,j=C.extend,e=C.addClass,w=C.removeClass,z=C.updateClasses,i=C.defer,k=C.flush,o=C.getScrollBarSize,A=function(a,b,c){return null==c&&(c=1),a+c>=b&&b>=a-c},y=function(){var a,b,c,d,e;for(a=document.createElement("div"),e=["transform","webkitTransform","OTransform","MozTransform","msTransform"],c=0,d=e.length;d>c;c++)if(b=e[c],void 0!==a.style[b])return b}(),x=[],v=function(){var a,b,c;for(b=0,c=x.length;c>b;b++)a=x[b],a.position(!1);return k()},r=function(){var a;return null!=(a="undefined"!=typeof performance&&null!==performance&&"function"==typeof performance.now?performance.now():void 0)?a:+new Date},function(){var a,b,c,d,e,f,g,h,i;for(b=null,c=null,d=null,e=function(){if(null!=c&&c>16)return c=Math.min(c-16,250),void(d=setTimeout(e,250));if(!(null!=b&&r()-b<10))return null!=d&&(clearTimeout(d),d=null),b=r(),v(),c=r()-b},h=["resize","scroll","touchmove"],i=[],f=0,g=h.length;g>f;f++)a=h[f],i.push(window.addEventListener(a,e));return i}(),a={center:"center",left:"right",right:"left"},b={middle:"middle",top:"bottom",bottom:"top"},c={top:0,left:0,middle:"50%",center:"50%",bottom:"100%",right:"100%"},h=function(c,d){var e,f;return e=c.left,f=c.top,"auto"===e&&(e=a[d.left]),"auto"===f&&(f=b[d.top]),{left:e,top:f}},g=function(a){var b,d;return{left:null!=(b=c[a.left])?b:a.left,top:null!=(d=c[a.top])?d:a.top}},f=function(){var a,b,c,d,e,f,g;for(b=1<=arguments.length?D.call(arguments,0):[],c={top:0,left:0},e=0,f=b.length;f>e;e++)g=b[e],d=g.top,a=g.left,"string"==typeof d&&(d=parseFloat(d,10)),"string"==typeof a&&(a=parseFloat(a,10)),c.top+=d,c.left+=a;return c},s=function(a,b){return"string"==typeof a.left&&-1!==a.left.indexOf("%")&&(a.left=parseFloat(a.left,10)/100*b.width),"string"==typeof a.top&&-1!==a.top.indexOf("%")&&(a.top=parseFloat(a.top,10)/100*b.height),a},t=u=function(a){var b,c,d;return d=a.split(" "),c=d[0],b=d[1],{top:c,left:b}},B=function(){function a(a){this.position=E(this.position,this);var b,c,e,f,g;for(x.push(this),this.history=[],this.setOptions(a,!1),f=d.modules,c=0,e=f.length;e>c;c++)b=f[c],null!=(g=b.initialize)&&g.call(this);this.position()}return a.modules=[],a.prototype.getClass=function(a){var b,c;return(null!=(b=this.options.classes)?b[a]:void 0)?this.options.classes[a]:(null!=(c=this.options.classes)?c[a]:void 0)!==!1?this.options.classPrefix?""+this.options.classPrefix+"-"+a:a:""},a.prototype.setOptions=function(a,b){var c,d,f,g,h,i;for(this.options=a,null==b&&(b=!0),c={offset:"0 0",targetOffset:"0 0",targetAttachment:"auto auto",classPrefix:"tether"},this.options=j(c,this.options),h=this.options,this.element=h.element,this.target=h.target,this.targetModifier=h.targetModifier,"viewport"===this.target?(this.target=document.body,this.targetModifier="visible"):"scroll-handle"===this.target&&(this.target=document.body,this.targetModifier="scroll-handle"),i=["element","target"],f=0,g=i.length;g>f;f++){if(d=i[f],null==this[d])throw new Error("Tether Error: Both element and target must be defined");null!=this[d].jquery?this[d]=this[d][0]:"string"==typeof this[d]&&(this[d]=document.querySelector(this[d]))}if(e(this.element,this.getClass("element")),e(this.target,this.getClass("target")),!this.options.attachment)throw new Error("Tether Error: You must provide an attachment");return this.targetAttachment=t(this.options.targetAttachment),this.attachment=t(this.options.attachment),this.offset=u(this.options.offset),this.targetOffset=u(this.options.targetOffset),null!=this.scrollParent&&this.disable(),this.scrollParent="scroll-handle"===this.targetModifier?this.target:p(this.target),this.options.enabled!==!1?this.enable(b):void 0},a.prototype.getTargetBounds=function(){var a,b,c,d,e,f,g,h,i;if(null==this.targetModifier)return l(this.target);switch(this.targetModifier){case"visible":return this.target===document.body?{top:pageYOffset,left:pageXOffset,height:innerHeight,width:innerWidth}:(a=l(this.target),e={height:a.height,width:a.width,top:a.top,left:a.left},e.height=Math.min(e.height,a.height-(pageYOffset-a.top)),e.height=Math.min(e.height,a.height-(a.top+a.height-(pageYOffset+innerHeight))),e.height=Math.min(innerHeight,e.height),e.height-=2,e.width=Math.min(e.width,a.width-(pageXOffset-a.left)),e.width=Math.min(e.width,a.width-(a.left+a.width-(pageXOffset+innerWidth))),e.width=Math.min(innerWidth,e.width),e.width-=2,e.top<pageYOffset&&(e.top=pageYOffset),e.left<pageXOffset&&(e.left=pageXOffset),e);case"scroll-handle":return i=this.target,i===document.body?(i=document.documentElement,a={left:pageXOffset,top:pageYOffset,height:innerHeight,width:innerWidth}):a=l(i),h=getComputedStyle(i),c=i.scrollWidth>i.clientWidth||"scroll"===[h.overflow,h.overflowX]||this.target!==document.body,f=0,c&&(f=15),d=a.height-parseFloat(h.borderTopWidth)-parseFloat(h.borderBottomWidth)-f,e={width:15,height:.975*d*(d/i.scrollHeight),left:a.left+a.width-parseFloat(h.borderLeftWidth)-15},b=0,408>d&&this.target===document.body&&(b=-11e-5*Math.pow(d,2)-.00727*d+22.58),this.target!==document.body&&(e.height=Math.max(e.height,24)),g=this.target.scrollTop/(i.scrollHeight-d),e.top=g*(d-e.height-b)+a.top+parseFloat(h.borderTopWidth),this.target===document.body&&(e.height=Math.max(e.height,24)),e}},a.prototype.clearCache=function(){return this._cache={}},a.prototype.cache=function(a,b){return null==this._cache&&(this._cache={}),null==this._cache[a]&&(this._cache[a]=b.call(this)),this._cache[a]},a.prototype.enable=function(a){return null==a&&(a=!0),e(this.target,this.getClass("enabled")),e(this.element,this.getClass("enabled")),this.enabled=!0,this.scrollParent!==document&&this.scrollParent.addEventListener("scroll",this.position),a?this.position():void 0},a.prototype.disable=function(){return w(this.target,this.getClass("enabled")),w(this.element,this.getClass("enabled")),this.enabled=!1,null!=this.scrollParent?this.scrollParent.removeEventListener("scroll",this.position):void 0},a.prototype.destroy=function(){var a,b,c,d,e;for(this.disable(),e=[],a=c=0,d=x.length;d>c;a=++c){if(b=x[a],b===this){x.splice(a,1);break}e.push(void 0)}return e},a.prototype.updateAttachClasses=function(a,b){var c,d,e,f,g,h,j,k,l,m=this;for(null==a&&(a=this.attachment),null==b&&(b=this.targetAttachment),f=["left","top","bottom","right","middle","center"],(null!=(l=this._addAttachClasses)?l.length:void 0)&&this._addAttachClasses.splice(0,this._addAttachClasses.length),c=null!=this._addAttachClasses?this._addAttachClasses:this._addAttachClasses=[],a.top&&c.push(""+this.getClass("element-attached")+"-"+a.top),a.left&&c.push(""+this.getClass("element-attached")+"-"+a.left),b.top&&c.push(""+this.getClass("target-attached")+"-"+b.top),b.left&&c.push(""+this.getClass("target-attached")+"-"+b.left),d=[],g=0,j=f.length;j>g;g++)e=f[g],d.push(""+this.getClass("element-attached")+"-"+e);for(h=0,k=f.length;k>h;h++)e=f[h],d.push(""+this.getClass("target-attached")+"-"+e);return i(function(){return null!=m._addAttachClasses?(z(m.element,m._addAttachClasses,d),z(m.target,m._addAttachClasses,d),m._addAttachClasses=void 0):void 0})},a.prototype.position=function(a){var b,c,e,i,j,n,p,q,r,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T=this;if(null==a&&(a=!0),this.enabled){for(this.clearCache(),D=h(this.targetAttachment,this.attachment),this.updateAttachClasses(this.attachment,D),b=this.cache("element-bounds",function(){return l(T.element)}),I=b.width,e=b.height,0===I&&0===e&&null!=this.lastSize?(N=this.lastSize,I=N.width,e=N.height):this.lastSize={width:I,height:e},G=F=this.cache("target-bounds",function(){return T.getTargetBounds()}),r=s(g(this.attachment),{width:I,height:e}),E=s(g(D),G),j=s(this.offset,{width:I,height:e}),n=s(this.targetOffset,G),r=f(r,j),E=f(E,n),i=F.left+E.left-r.left,H=F.top+E.top-r.top,O=d.modules,J=0,L=O.length;L>J;J++)if(p=O[J],y=p.position.call(this,{left:i,top:H,targetAttachment:D,targetPos:F,attachment:this.attachment,elementPos:b,offset:r,targetOffset:E,manualOffset:j,manualTargetOffset:n,scrollbarSize:B}),null!=y&&"object"==typeof y){if(y===!1)return!1;H=y.top,i=y.left}if(q={page:{top:H,left:i},viewport:{top:H-pageYOffset,bottom:pageYOffset-H-e+innerHeight,left:i-pageXOffset,right:pageXOffset-i-I+innerWidth}},document.body.scrollWidth>window.innerWidth&&(B=this.cache("scrollbar-size",o),q.viewport.bottom-=B.height),document.body.scrollHeight>window.innerHeight&&(B=this.cache("scrollbar-size",o),q.viewport.right-=B.width),(""!==(P=document.body.style.position)&&"static"!==P||""!==(Q=document.body.parentElement.style.position)&&"static"!==Q)&&(q.page.bottom=document.body.scrollHeight-H-e,q.page.right=document.body.scrollWidth-i-I),(null!=(R=this.options.optimizations)?R.moveElement:void 0)!==!1&&null==this.targetModifier){for(u=this.cache("target-offsetparent",function(){return m(T.target)}),x=this.cache("target-offsetparent-bounds",function(){return l(u)}),w=getComputedStyle(u),c=getComputedStyle(this.element),v=x,t={},S=["Top","Left","Bottom","Right"],K=0,M=S.length;M>K;K++)C=S[K],t[C.toLowerCase()]=parseFloat(w["border"+C+"Width"]);x.right=document.body.scrollWidth-x.left-v.width+t.right,x.bottom=document.body.scrollHeight-x.top-v.height+t.bottom,q.page.top>=x.top+t.top&&q.page.bottom>=x.bottom&&q.page.left>=x.left+t.left&&q.page.right>=x.right&&(A=u.scrollTop,z=u.scrollLeft,q.offset={top:q.page.top-x.top+A-t.top,left:q.page.left-x.left+z-t.left})}return this.move(q),this.history.unshift(q),this.history.length>3&&this.history.pop(),a&&k(),!0}},a.prototype.move=function(a){var b,c,d,e,f,g,h,k,l,n,o,p,q,r,s,t,u,v=this;if(null!=this.element.parentNode){k={};for(n in a){k[n]={};for(e in a[n]){for(d=!1,t=this.history,r=0,s=t.length;s>r;r++)if(h=t[r],!A(null!=(u=h[n])?u[e]:void 0,a[n][e])){d=!0;break}d||(k[n][e]=!0)}}b={top:"",left:"",right:"",bottom:""},l=function(a,c){var d,e,f;return(null!=(f=v.options.optimizations)?f.gpu:void 0)===!1?(a.top?b.top=""+c.top+"px":b.bottom=""+c.bottom+"px",a.left?b.left=""+c.left+"px":b.right=""+c.right+"px"):(a.top?(b.top=0,e=c.top):(b.bottom=0,e=-c.bottom),a.left?(b.left=0,d=c.left):(b.right=0,d=-c.right),b[y]="translateX("+Math.round(d)+"px) translateY("+Math.round(e)+"px)","msTransform"!==y?b[y]+=" translateZ(0)":void 0)},f=!1,(k.page.top||k.page.bottom)&&(k.page.left||k.page.right)?(b.position="absolute",l(k.page,a.page)):(k.viewport.top||k.viewport.bottom)&&(k.viewport.left||k.viewport.right)?(b.position="fixed",l(k.viewport,a.viewport)):null!=k.offset&&k.offset.top&&k.offset.left?(b.position="absolute",g=this.cache("target-offsetparent",function(){return m(v.target)}),m(this.element)!==g&&i(function(){return v.element.parentNode.removeChild(v.element),g.appendChild(v.element)}),l(k.offset,a.offset),f=!0):(b.position="absolute",l({top:!0,left:!0},a.page)),f||"BODY"===this.element.parentNode.tagName||(this.element.parentNode.removeChild(this.element),document.body.appendChild(this.element)),q={},p=!1;for(e in b)o=b[e],c=this.element.style[e],""===c||""===o||"top"!==e&&"left"!==e&&"bottom"!==e&&"right"!==e||(c=parseFloat(c),o=parseFloat(o)),c!==o&&(p=!0,q[e]=b[e]);return p?i(function(){return j(v.element.style,q)}):void 0}},a}(),d.position=v,this.Tether=j(B,d)}.call(this),function(){var a,b,c,d,e,f,g,h,i,j,k=[].indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(b in this&&this[b]===a)return b;return-1};j=this.Tether.Utils,g=j.getOuterSize,f=j.getBounds,h=j.getSize,d=j.extend,i=j.updateClasses,c=j.defer,b={left:"right",right:"left",top:"bottom",bottom:"top",middle:"middle"},a=["left","top","right","bottom"],e=function(b,c){var d,e,g,h,i,j,k;if("scrollParent"===c?c=b.scrollParent:"window"===c&&(c=[pageXOffset,pageYOffset,innerWidth+pageXOffset,innerHeight+pageYOffset]),c===document&&(c=c.documentElement),null!=c.nodeType)for(e=h=f(c),i=getComputedStyle(c),c=[e.left,e.top,h.width+e.left,h.height+e.top],d=j=0,k=a.length;k>j;d=++j)g=a[d],g=g[0].toUpperCase()+g.substr(1),"Top"===g||"Left"===g?c[d]+=parseFloat(i["border"+g+"Width"]):c[d]-=parseFloat(i["border"+g+"Width"]);return c},this.Tether.modules.push({position:function(b){var g,h,j,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,ab,bb=this;if(H=b.top,s=b.left,C=b.targetAttachment,!this.options.constraints)return!0;for(z=function(b){var c,d,e,f;for(bb.removeClass(b),f=[],d=0,e=a.length;e>d;d++)c=a[d],f.push(bb.removeClass(""+b+"-"+c));return f},V=this.cache("element-bounds",function(){return f(bb.element)}),r=V.height,I=V.width,0===I&&0===r&&null!=this.lastSize&&(W=this.lastSize,I=W.width,r=W.height),E=this.cache("target-bounds",function(){return bb.getTargetBounds()}),D=E.height,F=E.width,B={},q={},h=[this.getClass("pinned"),this.getClass("out-of-bounds")],X=this.options.constraints,J=0,N=X.length;N>J;J++)p=X[J],p.outOfBoundsClass&&h.push(p.outOfBoundsClass),p.pinnedClass&&h.push(p.pinnedClass);for(K=0,O=h.length;O>K;K++)for(o=h[K],Y=["left","top","right","bottom"],L=0,P=Y.length;P>L;L++)A=Y[L],h.push(""+o+"-"+A);for(g=[],B=d({},C),q=d({},this.attachment),Z=this.options.constraints,M=0,Q=Z.length;Q>M;M++){if(p=Z[M],G=p.to,j=p.attachment,w=p.pin,null==j&&(j=""),k.call(j," ")>=0?($=j.split(" "),n=$[0],m=$[1]):m=n=j,l=e(this,G),("target"===n||"both"===n)&&(H<l[1]&&"top"===B.top&&(H+=D,B.top="bottom"),H+r>l[3]&&"bottom"===B.top&&(H-=D,B.top="top")),"together"===n&&(H<l[1]&&"top"===B.top&&("bottom"===q.top?(H+=D,B.top="bottom",H+=r,q.top="top"):"top"===q.top&&(H+=D,B.top="bottom",H-=r,q.top="bottom")),H+r>l[3]&&"bottom"===B.top&&("top"===q.top?(H-=D,B.top="top",H-=r,q.top="bottom"):"bottom"===q.top&&(H-=D,B.top="top",H+=r,q.top="top")),"middle"===B.top&&(H+r>l[3]&&"top"===q.top?(H-=r,q.top="bottom"):H<l[1]&&"bottom"===q.top&&(H+=r,q.top="top"))),("target"===m||"both"===m)&&(s<l[0]&&"left"===B.left&&(s+=F,B.left="right"),s+I>l[2]&&"right"===B.left&&(s-=F,B.left="left")),"together"===m&&(s<l[0]&&"left"===B.left?"right"===q.left?(s+=F,B.left="right",s+=I,q.left="left"):"left"===q.left&&(s+=F,B.left="right",s-=I,q.left="right"):s+I>l[2]&&"right"===B.left?"left"===q.left?(s-=F,B.left="left",s-=I,q.left="right"):"right"===q.left&&(s-=F,B.left="left",s+=I,q.left="left"):"center"===B.left&&(s+I>l[2]&&"left"===q.left?(s-=I,q.left="right"):s<l[0]&&"right"===q.left&&(s+=I,q.left="left"))),("element"===n||"both"===n)&&(H<l[1]&&"bottom"===q.top&&(H+=r,q.top="top"),H+r>l[3]&&"top"===q.top&&(H-=r,q.top="bottom")),("element"===m||"both"===m)&&(s<l[0]&&"right"===q.left&&(s+=I,q.left="left"),s+I>l[2]&&"left"===q.left&&(s-=I,q.left="right")),"string"==typeof w?w=function(){var a,b,c,d;for(c=w.split(","),d=[],b=0,a=c.length;a>b;b++)v=c[b],d.push(v.trim());return d}():w===!0&&(w=["top","left","right","bottom"]),w||(w=[]),x=[],t=[],H<l[1]&&(k.call(w,"top")>=0?(H=l[1],x.push("top")):t.push("top")),H+r>l[3]&&(k.call(w,"bottom")>=0?(H=l[3]-r,x.push("bottom")):t.push("bottom")),s<l[0]&&(k.call(w,"left")>=0?(s=l[0],x.push("left")):t.push("left")),s+I>l[2]&&(k.call(w,"right")>=0?(s=l[2]-I,x.push("right")):t.push("right")),x.length)for(y=null!=(_=this.options.pinnedClass)?_:this.getClass("pinned"),g.push(y),T=0,R=x.length;R>T;T++)A=x[T],g.push(""+y+"-"+A);if(t.length)for(u=null!=(ab=this.options.outOfBoundsClass)?ab:this.getClass("out-of-bounds"),g.push(u),U=0,S=t.length;S>U;U++)A=t[U],g.push(""+u+"-"+A);(k.call(x,"left")>=0||k.call(x,"right")>=0)&&(q.left=B.left=!1),(k.call(x,"top")>=0||k.call(x,"bottom")>=0)&&(q.top=B.top=!1),(B.top!==C.top||B.left!==C.left||q.top!==this.attachment.top||q.left!==this.attachment.left)&&this.updateAttachClasses(q,B)}return c(function(){return i(bb.target,g,h),i(bb.element,g,h)}),{top:H,left:s}}})}.call(this),function(){var a,b,c,d;d=this.Tether.Utils,b=d.getBounds,c=d.updateClasses,a=d.defer,this.Tether.modules.push({position:function(d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D=this;if(o=d.top,j=d.left,y=this.cache("element-bounds",function(){return b(D.element)}),i=y.height,p=y.width,n=this.getTargetBounds(),h=o+i,k=j+p,e=[],o<=n.bottom&&h>=n.top)for(z=["left","right"],q=0,u=z.length;u>q;q++)l=z[q],((A=n[l])===j||A===k)&&e.push(l);if(j<=n.right&&k>=n.left)for(B=["top","bottom"],r=0,v=B.length;v>r;r++)l=B[r],((C=n[l])===o||C===h)&&e.push(l);for(g=[],f=[],m=["left","top","right","bottom"],g.push(this.getClass("abutted")),s=0,w=m.length;w>s;s++)l=m[s],g.push(""+this.getClass("abutted")+"-"+l);for(e.length&&f.push(this.getClass("abutted")),t=0,x=e.length;x>t;t++)l=e[t],f.push(""+this.getClass("abutted")+"-"+l);return a(function(){return c(D.target,f,g),c(D.element,f,g)}),!0}})}.call(this),function(){this.Tether.modules.push({position:function(a){var b,c,d,e,f,g,h;return g=a.top,b=a.left,this.options.shift?(c=function(a){return"function"==typeof a?a.call(this,{top:g,left:b}):a},d=c(this.options.shift),"string"==typeof d?(d=d.split(" "),d[1]||(d[1]=d[0]),f=d[0],e=d[1],f=parseFloat(f,10),e=parseFloat(e,10)):(h=[d.top,d.left],f=h[0],e=h[1]),g+=f,b+=e,{top:g,left:b}):void 0}})}.call(this),this.Tether}),function(a,b){function c(a){var b=ob[a]={};return $.each(a.split(bb),function(a,c){b[c]=!0}),b}function d(a,c,d){if(d===b&&1===a.nodeType){var e="data-"+c.replace(qb,"-$1").toLowerCase();if(d=a.getAttribute(e),"string"==typeof d){try{d="true"===d?!0:"false"===d?!1:"null"===d?null:+d+""===d?+d:pb.test(d)?$.parseJSON(d):d}catch(f){}$.data(a,c,d)}else d=b}return d}function e(a){var b;for(b in a)if(("data"!==b||!$.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function f(){return!1}function g(){return!0}function h(a){return!a||!a.parentNode||11===a.parentNode.nodeType}function i(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}function j(a,b,c){if(b=b||0,$.isFunction(b))return $.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return $.grep(a,function(a){return a===b===c});if("string"==typeof b){var d=$.grep(a,function(a){return 1===a.nodeType});if(Kb.test(b))return $.filter(b,d,!c);b=$.filter(b,d)}return $.grep(a,function(a){return $.inArray(a,b)>=0===c})}function k(a){var b=Nb.split("|"),c=a.createDocumentFragment();if(c.createElement)for(;b.length;)c.createElement(b.pop());return c}function l(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function m(a,b){if(1===b.nodeType&&$.hasData(a)){var c,d,e,f=$._data(a),g=$._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)$.event.add(b,c,h[c][d])}g.data&&(g.data=$.extend({},g.data))}}function n(a,b){var c;1===b.nodeType&&(b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),$.support.html5Clone&&a.innerHTML&&!$.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Xb.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.selected=a.defaultSelected:"input"===c||"textarea"===c?b.defaultValue=a.defaultValue:"script"===c&&b.text!==a.text&&(b.text=a.text),b.removeAttribute($.expando))}function o(a){return"undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName("*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll("*"):[]}function p(a){Xb.test(a.type)&&(a.defaultChecked=a.checked)}function q(a,b){if(b in a)return b;for(var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=rc.length;e--;)if(b=rc[e]+c,b in a)return b;return d}function r(a,b){return a=b||a,"none"===$.css(a,"display")||!$.contains(a.ownerDocument,a)}function s(a,b){for(var c,d,e=[],f=0,g=a.length;g>f;f++)c=a[f],c.style&&(e[f]=$._data(c,"olddisplay"),b?(e[f]||"none"!==c.style.display||(c.style.display=""),""===c.style.display&&r(c)&&(e[f]=$._data(c,"olddisplay",w(c.nodeName)))):(d=cc(c,"display"),e[f]||"none"===d||$._data(c,"olddisplay",d)));for(f=0;g>f;f++)c=a[f],c.style&&(b&&"none"!==c.style.display&&""!==c.style.display||(c.style.display=b?e[f]||"":"none"));return a}function t(a,b,c){var d=kc.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function u(a,b,c,d){for(var e=c===(d?"border":"content")?4:"width"===b?1:0,f=0;4>e;e+=2)"margin"===c&&(f+=$.css(a,c+qc[e],!0)),d?("content"===c&&(f-=parseFloat(cc(a,"padding"+qc[e]))||0),"margin"!==c&&(f-=parseFloat(cc(a,"border"+qc[e]+"Width"))||0)):(f+=parseFloat(cc(a,"padding"+qc[e]))||0,"padding"!==c&&(f+=parseFloat(cc(a,"border"+qc[e]+"Width"))||0));return f}function v(a,b,c){var d="width"===b?a.offsetWidth:a.offsetHeight,e=!0,f=$.support.boxSizing&&"border-box"===$.css(a,"boxSizing");if(0>=d||null==d){if(d=cc(a,b),(0>d||null==d)&&(d=a.style[b]),lc.test(d))return d;e=f&&($.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+u(a,b,c||(f?"border":"content"),e)+"px"}function w(a){if(nc[a])return nc[a];var b=$("<"+a+">").appendTo(P.body),c=b.css("display");return b.remove(),("none"===c||""===c)&&(dc=P.body.appendChild(dc||$.extend(P.createElement("iframe"),{frameBorder:0,width:0,height:0})),ec&&dc.createElement||(ec=(dc.contentWindow||dc.contentDocument).document,ec.write("<!doctype html><html><body>"),ec.close()),b=ec.body.appendChild(ec.createElement(a)),c=cc(b,"display"),P.body.removeChild(dc)),nc[a]=c,c}function x(a,b,c,d){var e;if($.isArray(b))$.each(b,function(b,e){c||uc.test(a)?d(a,e):x(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==$.type(b))d(a,b);else for(e in b)x(a+"["+e+"]",b[e],c,d)}function y(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(bb),h=0,i=g.length;if($.isFunction(c))for(;i>h;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function z(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;for(var h,i=a[f],j=0,k=i?i.length:0,l=a===Kc;k>j&&(l||!h);j++)h=i[j](c,d,e),"string"==typeof h&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=z(a,c,d,e,h,g)));return!l&&h||g["*"]||(h=z(a,c,d,e,"*",g)),h}function A(a,c){var d,e,f=$.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&$.extend(!0,a,e)}function B(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);for(;"*"===j[0];)j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type")); if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}return g?(g!==j[0]&&j.unshift(g),d[g]):void 0}function C(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;if(a.dataFilter&&(b=a.dataFilter(b,a.dataType)),g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if("*"!==e){if("*"!==h&&h!==e){if(c=i[h+" "+e]||i["* "+e],!c)for(d in i)if(f=d.split(" "),f[1]===e&&(c=i[h+" "+f[0]]||i["* "+f[0]])){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function D(){try{return new a.XMLHttpRequest}catch(b){}}function E(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function F(){return setTimeout(function(){Vc=b},0),Vc=$.now()}function G(a,b){$.each(b,function(b,c){for(var d=(_c[b]||[]).concat(_c["*"]),e=0,f=d.length;f>e;e++)if(d[e].call(a,b,c))return})}function H(a,b,c){var d,e=0,f=$c.length,g=$.Deferred().always(function(){delete h.elem}),h=function(){for(var b=Vc||F(),c=Math.max(0,i.startTime+i.duration-b),d=c/i.duration||0,e=1-d,f=0,h=i.tweens.length;h>f;f++)i.tweens[f].run(e);return g.notifyWith(a,[i,e,c]),1>e&&h?c:(g.resolveWith(a,[i]),!1)},i=g.promise({elem:a,props:$.extend({},b),opts:$.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Vc||F(),duration:c.duration,tweens:[],createTween:function(b,c){var d=$.Tween(a,i.opts,b,c,i.opts.specialEasing[b]||i.opts.easing);return i.tweens.push(d),d},stop:function(b){for(var c=0,d=b?i.tweens.length:0;d>c;c++)i.tweens[c].run(1);return b?g.resolveWith(a,[i,b]):g.rejectWith(a,[i,b]),this}}),j=i.props;for(I(j,i.opts.specialEasing);f>e;e++)if(d=$c[e].call(i,a,j,i.opts))return d;return G(i,j),$.isFunction(i.opts.start)&&i.opts.start.call(a,i),$.fx.timer($.extend(h,{anim:i,queue:i.opts.queue,elem:a})),i.progress(i.opts.progress).done(i.opts.done,i.opts.complete).fail(i.opts.fail).always(i.opts.always)}function I(a,b){var c,d,e,f,g;for(c in a)if(d=$.camelCase(c),e=b[d],f=a[c],$.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=$.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function J(a,b,c){var d,e,f,g,h,i,j,k,l,m=this,n=a.style,o={},p=[],q=a.nodeType&&r(a);c.queue||(k=$._queueHooks(a,"fx"),null==k.unqueued&&(k.unqueued=0,l=k.empty.fire,k.empty.fire=function(){k.unqueued||l()}),k.unqueued++,m.always(function(){m.always(function(){k.unqueued--,$.queue(a,"fx").length||k.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[n.overflow,n.overflowX,n.overflowY],"inline"===$.css(a,"display")&&"none"===$.css(a,"float")&&($.support.inlineBlockNeedsLayout&&"inline"!==w(a.nodeName)?n.zoom=1:n.display="inline-block")),c.overflow&&(n.overflow="hidden",$.support.shrinkWrapBlocks||m.done(function(){n.overflow=c.overflow[0],n.overflowX=c.overflow[1],n.overflowY=c.overflow[2]}));for(d in b)if(f=b[d],Xc.exec(f)){if(delete b[d],i=i||"toggle"===f,f===(q?"hide":"show"))continue;p.push(d)}if(g=p.length){h=$._data(a,"fxshow")||$._data(a,"fxshow",{}),"hidden"in h&&(q=h.hidden),i&&(h.hidden=!q),q?$(a).show():m.done(function(){$(a).hide()}),m.done(function(){var b;$.removeData(a,"fxshow",!0);for(b in o)$.style(a,b,o[b])});for(d=0;g>d;d++)e=p[d],j=m.createTween(e,q?h[e]:0),o[e]=h[e]||$.style(a,e),e in h||(h[e]=j.start,q&&(j.end=j.start,j.start="width"===e||"height"===e?1:0))}}function K(a,b,c,d,e){return new K.prototype.init(a,b,c,d,e)}function L(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=qc[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function M(a){return $.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}var N,O,P=a.document,Q=a.location,R=a.navigator,S=a.jQuery,T=a.$,U=Array.prototype.push,V=Array.prototype.slice,W=Array.prototype.indexOf,X=Object.prototype.toString,Y=Object.prototype.hasOwnProperty,Z=String.prototype.trim,$=function(a,b){return new $.fn.init(a,b,N)},_=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,ab=/\S/,bb=/\s+/,cb=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,db=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,eb=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,fb=/^[\],:{}\s]*$/,gb=/(?:^|:|,)(?:\s*\[)+/g,hb=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,ib=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,jb=/^-ms-/,kb=/-([\da-z])/gi,lb=function(a,b){return(b+"").toUpperCase()},mb=function(){P.addEventListener?(P.removeEventListener("DOMContentLoaded",mb,!1),$.ready()):"complete"===P.readyState&&(P.detachEvent("onreadystatechange",mb),$.ready())},nb={};$.fn=$.prototype={constructor:$,init:function(a,c,d){var e,f,g;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if("string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:db.exec(a),!e||!e[1]&&c)return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a);if(e[1])return c=c instanceof $?c[0]:c,g=c&&c.nodeType?c.ownerDocument||c:P,a=$.parseHTML(e[1],g,!0),eb.test(e[1])&&$.isPlainObject(c)&&this.attr.call(a,c,!0),$.merge(this,a);if(f=P.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return d.find(a);this.length=1,this[0]=f}return this.context=P,this.selector=a,this}return $.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),$.makeArray(a,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return V.call(this)},get:function(a){return null==a?this.toArray():0>a?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=$.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,"find"===b?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return $.each(this,a,b)},ready:function(a){return $.ready.promise().done(a),this},eq:function(a){return a=+a,-1===a?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(V.apply(this,arguments),"slice",V.call(arguments).join(","))},map:function(a){return this.pushStack($.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:U,sort:[].sort,splice:[].splice},$.fn.init.prototype=$.fn,$.extend=$.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;for("boolean"==typeof h&&(k=h,h=arguments[1]||{},i=2),"object"==typeof h||$.isFunction(h)||(h={}),j===i&&(h=this,--i);j>i;i++)if(null!=(a=arguments[i]))for(c in a)d=h[c],e=a[c],h!==e&&(k&&e&&($.isPlainObject(e)||(f=$.isArray(e)))?(f?(f=!1,g=d&&$.isArray(d)?d:[]):g=d&&$.isPlainObject(d)?d:{},h[c]=$.extend(k,g,e)):e!==b&&(h[c]=e));return h},$.extend({noConflict:function(b){return a.$===$&&(a.$=T),b&&a.jQuery===$&&(a.jQuery=S),$},isReady:!1,readyWait:1,holdReady:function(a){a?$.readyWait++:$.ready(!0)},ready:function(a){if(a===!0?!--$.readyWait:!$.isReady){if(!P.body)return setTimeout($.ready,1);$.isReady=!0,a!==!0&&--$.readyWait>0||(O.resolveWith(P,[$]),$.fn.trigger&&$(P).trigger("ready").off("ready"))}},isFunction:function(a){return"function"===$.type(a)},isArray:Array.isArray||function(a){return"array"===$.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return null==a?String(a):nb[X.call(a)]||"object"},isPlainObject:function(a){if(!a||"object"!==$.type(a)||a.nodeType||$.isWindow(a))return!1;try{if(a.constructor&&!Y.call(a,"constructor")&&!Y.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||Y.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return a&&"string"==typeof a?("boolean"==typeof b&&(c=b,b=0),b=b||P,(d=eb.exec(a))?[b.createElement(d[1])]:(d=$.buildFragment([a],b,c?null:[]),$.merge([],(d.cacheable?$.clone(d.fragment):d.fragment).childNodes))):null},parseJSON:function(b){return b&&"string"==typeof b?(b=$.trim(b),a.JSON&&a.JSON.parse?a.JSON.parse(b):fb.test(b.replace(hb,"@").replace(ib,"]").replace(gb,""))?new Function("return "+b)():void $.error("Invalid JSON: "+b)):null},parseXML:function(c){var d,e;if(!c||"string"!=typeof c)return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return d&&d.documentElement&&!d.getElementsByTagName("parsererror").length||$.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&ab.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(jb,"ms-").replace(kb,lb)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||$.isFunction(a);if(d)if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;g>f&&c.apply(a[f++],d)!==!1;);else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;g>f&&c.call(a[f],f,a[f++])!==!1;);return a},trim:Z&&!Z.call("\ufeff\xa0")?function(a){return null==a?"":Z.call(a)}:function(a){return null==a?"":(a+"").replace(cb,"")},makeArray:function(a,b){var c,d=b||[];return null!=a&&(c=$.type(a),null==a.length||"string"===c||"function"===c||"regexp"===c||$.isWindow(a)?U.call(d,a):$.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(W)return W.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if("number"==typeof d)for(;d>f;f++)a[e++]=c[f];else for(;c[f]!==b;)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;for(c=!!c;g>f;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof $||i!==b&&"number"==typeof i&&(i>0&&a[0]&&a[i-1]||0===i||$.isArray(a));if(j)for(;i>h;h++)e=c(a[h],h,d),null!=e&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),null!=e&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return"string"==typeof c&&(d=a[c],c=a,a=d),$.isFunction(a)?(e=V.call(arguments,2),f=function(){return a.apply(c,e.concat(V.call(arguments)))},f.guid=a.guid=a.guid||$.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=null==d,k=0,l=a.length;if(d&&"object"==typeof d){for(k in d)$.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){if(i=h===b&&$.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call($(a),c)}):(c.call(a,e),c=null)),c)for(;l>k;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),$.ready.promise=function(b){if(!O)if(O=$.Deferred(),"complete"===P.readyState)setTimeout($.ready,1);else if(P.addEventListener)P.addEventListener("DOMContentLoaded",mb,!1),a.addEventListener("load",$.ready,!1);else{P.attachEvent("onreadystatechange",mb),a.attachEvent("onload",$.ready);var c=!1;try{c=null==a.frameElement&&P.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!$.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}$.ready()}}()}return O.promise(b)},$.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){nb["[object "+b+"]"]=b.toLowerCase()}),N=$(P);var ob={};$.Callbacks=function(a){a="string"==typeof a?ob[a]||c(a):$.extend({},a);var d,e,f,g,h,i,j=[],k=!a.once&&[],l=function(b){for(d=a.memory&&b,e=!0,i=g||0,g=0,h=j.length,f=!0;j&&h>i;i++)if(j[i].apply(b[0],b[1])===!1&&a.stopOnFalse){d=!1;break}f=!1,j&&(k?k.length&&l(k.shift()):d?j=[]:m.disable())},m={add:function(){if(j){var b=j.length;!function c(b){$.each(b,function(b,d){var e=$.type(d);"function"===e?a.unique&&m.has(d)||j.push(d):d&&d.length&&"string"!==e&&c(d)})}(arguments),f?h=j.length:d&&(g=b,l(d))}return this},remove:function(){return j&&$.each(arguments,function(a,b){for(var c;(c=$.inArray(b,j,c))>-1;)j.splice(c,1),f&&(h>=c&&h--,i>=c&&i--)}),this},has:function(a){return $.inArray(a,j)>-1},empty:function(){return j=[],this},disable:function(){return j=k=d=b,this},disabled:function(){return!j},lock:function(){return k=b,d||m.disable(),this},locked:function(){return!k},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],!j||e&&!k||(f?k.push(b):l(b)),this},fire:function(){return m.fireWith(this,arguments),this},fired:function(){return!!e}};return m},$.extend({Deferred:function(a){var b=[["resolve","done",$.Callbacks("once memory"),"resolved"],["reject","fail",$.Callbacks("once memory"),"rejected"],["notify","progress",$.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return $.Deferred(function(c){$.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]]($.isFunction(g)?function(){var a=g.apply(this,arguments);a&&$.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return null!=a?$.extend(a,d):d}},e={};return d.pipe=d.then,$.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b,c,d,e=0,f=V.call(arguments),g=f.length,h=1!==g||a&&$.isFunction(a.promise)?g:0,i=1===h?a:$.Deferred(),j=function(a,c,d){return function(e){c[a]=this,d[a]=arguments.length>1?V.call(arguments):e,d===b?i.notifyWith(c,d):--h||i.resolveWith(c,d)}};if(g>1)for(b=new Array(g),c=new Array(g),d=new Array(g);g>e;e++)f[e]&&$.isFunction(f[e].promise)?f[e].promise().done(j(e,d,f)).fail(i.reject).progress(j(e,c,b)):--h;return h||i.resolveWith(d,f),i.promise()}}),$.support=function(){var b,c,d,e,f,g,h,i,j,k,l,m=P.createElement("div");if(m.setAttribute("className","t"),m.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=m.getElementsByTagName("*"),d=m.getElementsByTagName("a")[0],!c||!d||!c.length)return{};e=P.createElement("select"),f=e.appendChild(P.createElement("option")),g=m.getElementsByTagName("input")[0],d.style.cssText="top:1px;float:left;opacity:.5",b={leadingWhitespace:3===m.firstChild.nodeType,tbody:!m.getElementsByTagName("tbody").length,htmlSerialize:!!m.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:"/a"===d.getAttribute("href"),opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:"on"===g.value,optSelected:f.selected,getSetAttribute:"t"!==m.className,enctype:!!P.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==P.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===P.compatMode,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},g.checked=!0,b.noCloneChecked=g.cloneNode(!0).checked,e.disabled=!0,b.optDisabled=!f.disabled;try{delete m.test}catch(n){b.deleteExpando=!1}if(!m.addEventListener&&m.attachEvent&&m.fireEvent&&(m.attachEvent("onclick",l=function(){b.noCloneEvent=!1}),m.cloneNode(!0).fireEvent("onclick"),m.detachEvent("onclick",l)),g=P.createElement("input"),g.value="t",g.setAttribute("type","radio"),b.radioValue="t"===g.value,g.setAttribute("checked","checked"),g.setAttribute("name","t"),m.appendChild(g),h=P.createDocumentFragment(),h.appendChild(m.lastChild),b.checkClone=h.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=g.checked,h.removeChild(g),h.appendChild(m),m.attachEvent)for(j in{submit:!0,change:!0,focusin:!0})i="on"+j,k=i in m,k||(m.setAttribute(i,"return;"),k="function"==typeof m[i]),b[j+"Bubbles"]=k;return $(function(){var c,d,e,f,g="padding:0;margin:0;border:0;display:block;overflow:hidden;",h=P.getElementsByTagName("body")[0];h&&(c=P.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",h.insertBefore(c,h.firstChild),d=P.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",e=d.getElementsByTagName("td"),e[0].style.cssText="padding:0;margin:0;border:0;display:none",k=0===e[0].offsetHeight,e[0].style.display="",e[1].style.display="none",b.reliableHiddenOffsets=k&&0===e[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%;",b.boxSizing=4===d.offsetWidth,b.doesNotIncludeMarginInBodyOffset=1!==h.offsetTop,a.getComputedStyle&&(b.pixelPosition="1%"!==(a.getComputedStyle(d,null)||{}).top,b.boxSizingReliable="4px"===(a.getComputedStyle(d,null)||{width:"4px"}).width,f=P.createElement("div"),f.style.cssText=d.style.cssText=g,f.style.marginRight=f.style.width="0",d.style.width="1px",d.appendChild(f),b.reliableMarginRight=!parseFloat((a.getComputedStyle(f,null)||{}).marginRight)),"undefined"!=typeof d.style.zoom&&(d.innerHTML="",d.style.cssText=g+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=3!==d.offsetWidth,c.style.zoom=1),h.removeChild(c),c=d=e=f=null)}),h.removeChild(m),c=d=e=f=g=h=m=null,b}();var pb=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,qb=/([A-Z])/g;$.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+($.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?$.cache[a[$.expando]]:a[$.expando],!!a&&!e(a)},data:function(a,c,d,e){if($.acceptData(a)){var f,g,h=$.expando,i="string"==typeof c,j=a.nodeType,k=j?$.cache:a,l=j?a[h]:a[h]&&h;if(l&&k[l]&&(e||k[l].data)||!i||d!==b)return l||(j?a[h]=l=$.deletedIds.pop()||$.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=$.noop)),("object"==typeof c||"function"==typeof c)&&(e?k[l]=$.extend(k[l],c):k[l].data=$.extend(k[l].data,c)),f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[$.camelCase(c)]=d),i?(g=f[c],null==g&&(g=f[$.camelCase(c)])):g=f,g}},removeData:function(a,b,c){if($.acceptData(a)){var d,f,g,h=a.nodeType,i=h?$.cache:a,j=h?a[$.expando]:$.expando;if(i[j]){if(b&&(d=c?i[j]:i[j].data)){$.isArray(b)||(b in d?b=[b]:(b=$.camelCase(b),b=b in d?[b]:b.split(" ")));for(f=0,g=b.length;g>f;f++)delete d[b[f]];if(!(c?e:$.isEmptyObject)(d))return}(c||(delete i[j].data,e(i[j])))&&(h?$.cleanData([a],!0):$.support.deleteExpando||i!=i.window?delete i[j]:i[j]=null)}}},_data:function(a,b,c){return $.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&$.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),$.fn.extend({data:function(a,c){var e,f,g,h,i,j=this[0],k=0,l=null;if(a===b){if(this.length&&(l=$.data(j),1===j.nodeType&&!$._data(j,"parsedAttrs"))){for(g=j.attributes,i=g.length;i>k;k++)h=g[k].name,h.indexOf("data-")||(h=$.camelCase(h.substring(5)),d(j,h,l[h]));$._data(j,"parsedAttrs",!0)}return l}return"object"==typeof a?this.each(function(){$.data(this,a)}):(e=a.split(".",2),e[1]=e[1]?"."+e[1]:"",f=e[1]+"!",$.access(this,function(c){return c===b?(l=this.triggerHandler("getData"+f,[e[0]]),l===b&&j&&(l=$.data(j,a),l=d(j,a,l)),l===b&&e[1]?this.data(e[0]):l):(e[1]=c,void this.each(function(){var b=$(this);b.triggerHandler("setData"+f,e),$.data(this,a,c),b.triggerHandler("changeData"+f,e)}))},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){$.removeData(this,a)})}}),$.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=$._data(a,b),c&&(!d||$.isArray(c)?d=$._data(a,b,$.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=$.queue(a,b),d=c.length,e=c.shift(),f=$._queueHooks(a,b),g=function(){$.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return $._data(a,c)||$._data(a,c,{empty:$.Callbacks("once memory").add(function(){$.removeData(a,b+"queue",!0),$.removeData(a,c,!0)})})}}),$.fn.extend({queue:function(a,c){var d=2;return"string"!=typeof a&&(c=a,a="fx",d--),arguments.length<d?$.queue(this[0],a):c===b?this:this.each(function(){var b=$.queue(this,a,c);$._queueHooks(this,a),"fx"===a&&"inprogress"!==b[0]&&$.dequeue(this,a)})},dequeue:function(a){return this.each(function(){$.dequeue(this,a)})},delay:function(a,b){return a=$.fx?$.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=$.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};for("string"!=typeof a&&(c=a,a=b),a=a||"fx";h--;)d=$._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var rb,sb,tb,ub=/[\t\r\n]/g,vb=/\r/g,wb=/^(?:button|input)$/i,xb=/^(?:button|input|object|select|textarea)$/i,yb=/^a(?:rea|)$/i,zb=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,Ab=$.support.getSetAttribute;$.fn.extend({attr:function(a,b){return $.access(this,$.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){$.removeAttr(this,a)})},prop:function(a,b){return $.access(this,$.prop,a,b,arguments.length>1)},removeProp:function(a){return a=$.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if($.isFunction(a))return this.each(function(b){$(this).addClass(a.call(this,b,this.className))});if(a&&"string"==typeof a)for(b=a.split(bb),c=0,d=this.length;d>c;c++)if(e=this[c],1===e.nodeType)if(e.className||1!==b.length){for(f=" "+e.className+" ",g=0,h=b.length;h>g;g++)f.indexOf(" "+b[g]+" ")<0&&(f+=b[g]+" ");e.className=$.trim(f)}else e.className=a;return this},removeClass:function(a){var c,d,e,f,g,h,i;if($.isFunction(a))return this.each(function(b){$(this).removeClass(a.call(this,b,this.className))});if(a&&"string"==typeof a||a===b)for(c=(a||"").split(bb),h=0,i=this.length;i>h;h++)if(e=this[h],1===e.nodeType&&e.className){for(d=(" "+e.className+" ").replace(ub," "),f=0,g=c.length;g>f;f++)for(;d.indexOf(" "+c[f]+" ")>=0;)d=d.replace(" "+c[f]+" "," ");e.className=a?$.trim(d):""}return this},toggleClass:function(a,b){var c=typeof a,d="boolean"==typeof b;return this.each($.isFunction(a)?function(c){$(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c)for(var e,f=0,g=$(this),h=b,i=a.split(bb);e=i[f++];)h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e);else("undefined"===c||"boolean"===c)&&(this.className&&$._data(this,"__className__",this.className),this.className=this.className||a===!1?"":$._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];{if(arguments.length)return e=$.isFunction(a),this.each(function(d){var f,g=$(this);1===this.nodeType&&(f=e?a.call(this,d,g.val()):a,null==f?f="":"number"==typeof f?f+="":$.isArray(f)&&(f=$.map(f,function(a){return null==a?"":a+""})),c=$.valHooks[this.type]||$.valHooks[this.nodeName.toLowerCase()],c&&"set"in c&&c.set(this,f,"value")!==b||(this.value=f))});if(f)return c=$.valHooks[f.type]||$.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,"string"==typeof d?d.replace(vb,""):null==d?"":d)}}}),$.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||($.support.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&$.nodeName(c.parentNode,"optgroup"))){if(b=$(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c=$.makeArray(b);return $(a).find("option").each(function(){this.selected=$.inArray($(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(a&&3!==i&&8!==i&&2!==i)return e&&$.isFunction($.fn[c])?$(a)[c](d):"undefined"==typeof a.getAttribute?$.prop(a,c,d):(h=1!==i||!$.isXMLDoc(a),h&&(c=c.toLowerCase(),g=$.attrHooks[c]||(zb.test(c)?sb:rb)),d!==b?null===d?void $.removeAttr(a,c):g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d):g&&"get"in g&&h&&null!==(f=g.get(a,c))?f:(f=a.getAttribute(c),null===f?b:f))},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&1===a.nodeType)for(d=b.split(bb);g<d.length;g++)e=d[g],e&&(c=$.propFix[e]||e,f=zb.test(e),f||$.attr(a,e,""),a.removeAttribute(Ab?e:c),f&&c in a&&(a[c]=!1))},attrHooks:{type:{set:function(a,b){if(wb.test(a.nodeName)&&a.parentNode)$.error("type property can't be changed");else if(!$.support.radioValue&&"radio"===b&&$.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return rb&&$.nodeName(a,"button")?rb.get(a,b):b in a?a.value:null},set:function(a,b,c){return rb&&$.nodeName(a,"button")?rb.set(a,b,c):void(a.value=b)}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(a&&3!==h&&8!==h&&2!==h)return g=1!==h||!$.isXMLDoc(a),g&&(c=$.propFix[c]||c,f=$.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&null!==(e=f.get(a,c))?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):xb.test(a.nodeName)||yb.test(a.nodeName)&&a.href?0:b}}}}),sb={get:function(a,c){var d,e=$.prop(a,c);return e===!0||"boolean"!=typeof e&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?$.removeAttr(a,c):(d=$.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},Ab||(tb={name:!0,id:!0,coords:!0},rb=$.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(tb[c]?""!==d.value:d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=P.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},$.each(["width","height"],function(a,b){$.attrHooks[b]=$.extend($.attrHooks[b],{set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}})}),$.attrHooks.contenteditable={get:rb.get,set:function(a,b,c){""===b&&(b="false"),rb.set(a,b,c)}}),$.support.hrefNormalized||$.each(["href","src","width","height"],function(a,c){$.attrHooks[c]=$.extend($.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return null===d?b:d}})}),$.support.style||($.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=b+""}}),$.support.optSelected||($.propHooks.selected=$.extend($.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),$.support.enctype||($.propFix.enctype="encoding"),$.support.checkOn||$.each(["radio","checkbox"],function(){$.valHooks[this]={get:function(a){return null===a.getAttribute("value")?"on":a.value}}}),$.each(["radio","checkbox"],function(){$.valHooks[this]=$.extend($.valHooks[this],{set:function(a,b){return $.isArray(b)?a.checked=$.inArray($(a).val(),b)>=0:void 0}})});var Bb=/^(?:textarea|input|select)$/i,Cb=/^([^\.]*|)(?:\.(.+)|)$/,Db=/(?:^|\s)hover(\.\S+|)\b/,Eb=/^key/,Fb=/^(?:mouse|contextmenu)|click/,Gb=/^(?:focusinfocus|focusoutblur)$/,Hb=function(a){return $.event.special.hover?a:a.replace(Db,"mouseenter$1 mouseleave$1")};$.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,p,q;if(3!==a.nodeType&&8!==a.nodeType&&c&&d&&(g=$._data(a))){for(d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=$.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return"undefined"==typeof $||a&&$.event.triggered===a.type?b:$.event.dispatch.apply(h.elem,arguments)},h.elem=a),c=$.trim(Hb(c)).split(" "),j=0;j<c.length;j++)k=Cb.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),q=$.event.special[l]||{},l=(f?q.delegateType:q.bindType)||l,q=$.event.special[l]||{},n=$.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&$.expr.match.needsContext.test(f),namespace:m.join(".")},o),p=i[l],p||(p=i[l]=[],p.delegateCount=0,q.setup&&q.setup.call(a,e,m,h)!==!1||(a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h))),q.add&&(q.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?p.splice(p.delegateCount++,0,n):p.push(n),$.event.global[l]=!0;a=null}},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=$.hasData(a)&&$._data(a);if(q&&(m=q.events)){for(b=$.trim(Hb(b||"")).split(" "),f=0;f<b.length;f++)if(g=Cb.exec(b[f])||[],h=i=g[1],j=g[2],h){for(n=$.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null,l=0;l<o.length;l++)p=o[l],!e&&i!==p.origType||c&&c.guid!==p.guid||j&&!j.test(p.namespace)||d&&d!==p.selector&&("**"!==d||!p.selector)||(o.splice(l--,1),p.selector&&o.delegateCount--,n.remove&&n.remove.call(a,p));0===o.length&&k!==o.length&&(n.teardown&&n.teardown.call(a,j,q.handle)!==!1||$.removeEvent(a,h,q.handle),delete m[h])}else for(h in m)$.event.remove(a,h+b[f],c,d,!0);$.isEmptyObject(m)&&(delete q.handle,$.removeData(a,"events",!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,f){if(!e||3!==e.nodeType&&8!==e.nodeType){var g,h,i,j,k,l,m,n,o,p,q=c.type||c,r=[];if(!Gb.test(q+$.event.triggered)&&(q.indexOf("!")>=0&&(q=q.slice(0,-1),h=!0),q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),e&&!$.event.customEvent[q]||$.event.global[q]))if(c="object"==typeof c?c[$.expando]?c:new $.Event(q,c):new $.Event(q),c.type=q,c.isTrigger=!0,c.exclusive=h,c.namespace=r.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,l=q.indexOf(":")<0?"on"+q:"",e){if(c.result=b,c.target||(c.target=e),d=null!=d?$.makeArray(d):[],d.unshift(c),m=$.event.special[q]||{},!m.trigger||m.trigger.apply(e,d)!==!1){if(o=[[e,m.bindType||q]],!f&&!m.noBubble&&!$.isWindow(e)){for(p=m.delegateType||q,j=Gb.test(p+q)?e:e.parentNode,k=e;j;j=j.parentNode)o.push([j,p]),k=j;k===(e.ownerDocument||P)&&o.push([k.defaultView||k.parentWindow||a,p])}for(i=0;i<o.length&&!c.isPropagationStopped();i++)j=o[i][0],c.type=o[i][1],n=($._data(j,"events")||{})[c.type]&&$._data(j,"handle"),n&&n.apply(j,d),n=l&&j[l],n&&$.acceptData(j)&&n.apply&&n.apply(j,d)===!1&&c.preventDefault();return c.type=q,f||c.isDefaultPrevented()||m._default&&m._default.apply(e.ownerDocument,d)!==!1||"click"===q&&$.nodeName(e,"a")||!$.acceptData(e)||l&&e[q]&&("focus"!==q&&"blur"!==q||0!==c.target.offsetWidth)&&!$.isWindow(e)&&(k=e[l],k&&(e[l]=null),$.event.triggered=q,e[q](),$.event.triggered=b,k&&(e[l]=k)),c.result}}else{g=$.cache;for(i in g)g[i].events&&g[i].events[q]&&$.event.trigger(c,d,g[i].handle.elem,!0)}}},dispatch:function(c){c=$.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m=($._data(this,"events")||{})[c.type]||[],n=m.delegateCount,o=V.call(arguments),p=!c.exclusive&&!c.namespace,q=$.event.special[c.type]||{},r=[];if(o[0]=c,c.delegateTarget=this,!q.preDispatch||q.preDispatch.call(this,c)!==!1){if(n&&(!c.button||"click"!==c.type))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||"click"!==c.type){for(h={},j=[],d=0;n>d;d++)k=m[d],l=k.selector,h[l]===b&&(h[l]=k.needsContext?$(l,this).index(f)>=0:$.find(l,this,null,[f]).length),h[l]&&j.push(k); j.length&&r.push({elem:f,matches:j})}for(m.length>n&&r.push({elem:this,matches:m.slice(n)}),d=0;d<r.length&&!c.isPropagationStopped();d++)for(i=r[d],c.currentTarget=i.elem,e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++)k=i.matches[e],(p||!c.namespace&&!k.namespace||c.namespace_re&&c.namespace_re.test(k.namespace))&&(c.data=k.data,c.handleObj=k,g=(($.event.special[k.origType]||{}).handle||k.handler).apply(i.elem,o),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation())));return q.postDispatch&&q.postDispatch.call(this,c),c.result}},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,e,f,g=c.button,h=c.fromElement;return null==a.pageX&&null!=c.clientX&&(d=a.target.ownerDocument||P,e=d.documentElement,f=d.body,a.pageX=c.clientX+(e&&e.scrollLeft||f&&f.scrollLeft||0)-(e&&e.clientLeft||f&&f.clientLeft||0),a.pageY=c.clientY+(e&&e.scrollTop||f&&f.scrollTop||0)-(e&&e.clientTop||f&&f.clientTop||0)),!a.relatedTarget&&h&&(a.relatedTarget=h===a.target?c.toElement:h),a.which||g===b||(a.which=1&g?1:2&g?3:4&g?2:0),a}},fix:function(a){if(a[$.expando])return a;var b,c,d=a,e=$.event.fixHooks[a.type]||{},f=e.props?this.props.concat(e.props):this.props;for(a=$.Event(d),b=f.length;b;)c=f[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||P),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,e.filter?e.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){$.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=$.extend(new $.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?$.event.trigger(e,null,b):$.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},$.event.handle=$.event.dispatch,$.removeEvent=P.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&("undefined"==typeof a[d]&&(a[d]=null),a.detachEvent(d,c))},$.Event=function(a,b){return this instanceof $.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?g:f):this.type=a,b&&$.extend(this,b),this.timeStamp=a&&a.timeStamp||$.now(),void(this[$.expando]=!0)):new $.Event(a,b)},$.Event.prototype={preventDefault:function(){this.isDefaultPrevented=g;var a=this.originalEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=g;var a=this.originalEvent;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=g,this.stopPropagation()},isDefaultPrevented:f,isPropagationStopped:f,isImmediatePropagationStopped:f},$.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){$.event.special[a]={delegateType:b,bindType:b,handle:function(a){{var c,d=this,e=a.relatedTarget,f=a.handleObj;f.selector}return(!e||e!==d&&!$.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),$.support.submitBubbles||($.event.special.submit={setup:function(){return $.nodeName(this,"form")?!1:void $.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=$.nodeName(c,"input")||$.nodeName(c,"button")?c.form:b;d&&!$._data(d,"_submit_attached")&&($.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),$._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&$.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return $.nodeName(this,"form")?!1:void $.event.remove(this,"._submit")}}),$.support.changeBubbles||($.event.special.change={setup:function(){return Bb.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&($.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),$.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),$.event.simulate("change",this,a,!0)})),!1):void $.event.add(this,"beforeactivate._change",function(a){var b=a.target;Bb.test(b.nodeName)&&!$._data(b,"_change_attached")&&($.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||$.event.simulate("change",this.parentNode,a,!0)}),$._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return $.event.remove(this,"._change"),!Bb.test(this.nodeName)}}),$.support.focusinBubbles||$.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){$.event.simulate(b,a.target,$.event.fix(a),!0)};$.event.special[b]={setup:function(){0===c++&&P.addEventListener(a,d,!0)},teardown:function(){0===--c&&P.removeEventListener(a,d,!0)}}}),$.fn.extend({on:function(a,c,d,e,g){var h,i;if("object"==typeof a){"string"!=typeof c&&(d=d||c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}if(null==d&&null==e?(e=c,d=c=b):null==e&&("string"==typeof c?(e=d,d=b):(e=d,d=c,c=b)),e===!1)e=f;else if(!e)return this;return 1===g&&(h=e,e=function(a){return $().off(a),h.apply(this,arguments)},e.guid=h.guid||(h.guid=$.guid++)),this.each(function(){$.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,g;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,$(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if("object"==typeof a){for(g in a)this.off(g,c,a[g]);return this}return(c===!1||"function"==typeof c)&&(d=c,c=b),d===!1&&(d=f),this.each(function(){$.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return $(this.context).on(a,this.selector,b,c),this},die:function(a,b){return $(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){$.event.trigger(a,b,this)})},triggerHandler:function(a,b){return this[0]?$.event.trigger(a,b,this[0],!0):void 0},toggle:function(a){var b=arguments,c=a.guid||$.guid++,d=0,e=function(c){var e=($._data(this,"lastToggle"+a.guid)||0)%d;return $._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};for(e.guid=c;d<b.length;)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),$.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){$.fn[b]=function(a,c){return null==c&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Eb.test(b)&&($.event.fixHooks[b]=$.event.keyHooks),Fb.test(b)&&($.event.fixHooks[b]=$.event.mouseHooks)}),function(a,b){function c(a,b,c,d){c=c||[],b=b||F;var e,f,g,h,i=b.nodeType;if(!a||"string"!=typeof a)return c;if(1!==i&&9!==i)return[];if(g=v(b),!g&&!d&&(e=cb.exec(a)))if(h=e[1]){if(9===i){if(f=b.getElementById(h),!f||!f.parentNode)return c;if(f.id===h)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(h))&&w(b,f)&&f.id===h)return c.push(f),c}else{if(e[2])return K.apply(c,L.call(b.getElementsByTagName(a),0)),c;if((h=e[3])&&mb&&b.getElementsByClassName)return K.apply(c,L.call(b.getElementsByClassName(h),0)),c}return p(a.replace(Z,"$1"),b,c,d,g)}function d(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function e(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function f(a){return N(function(b){return b=+b,N(function(c,d){for(var e,f=a([],c.length,b),g=f.length;g--;)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function g(a,b,c){if(a===b)return c;for(var d=a.nextSibling;d;){if(d===b)return-1;d=d.nextSibling}return 1}function h(a,b){var d,e,f,g,h,i,j,k=Q[D][a+" "];if(k)return b?0:k.slice(0);for(h=a,i=[],j=t.preFilter;h;){(!d||(e=_.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),d=!1,(e=ab.exec(h))&&(f.push(d=new E(e.shift())),h=h.slice(d.length),d.type=e[0].replace(Z," "));for(g in t.filter)!(e=hb[g].exec(h))||j[g]&&!(e=j[g](e))||(f.push(d=new E(e.shift())),h=h.slice(d.length),d.type=g,d.matches=e);if(!d)break}return b?h.length:h?c.error(a):Q(a,i).slice(0)}function i(a,b,c){var d=b.dir,e=c&&"parentNode"===b.dir,f=I++;return b.first?function(b,c,f){for(;b=b[d];)if(e||1===b.nodeType)return a(b,c,f)}:function(b,c,g){if(g){for(;b=b[d];)if((e||1===b.nodeType)&&a(b,c,g))return b}else for(var h,i=H+" "+f+" ",j=i+r;b=b[d];)if(e||1===b.nodeType){if((h=b[D])===j)return b.sizset;if("string"==typeof h&&0===h.indexOf(i)){if(b.sizset)return b}else{if(b[D]=j,a(b,c,g))return b.sizset=!0,b;b.sizset=!1}}}}function j(a){return a.length>1?function(b,c,d){for(var e=a.length;e--;)if(!a[e](b,c,d))return!1;return!0}:a[0]}function k(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function l(a,b,c,d,e,f){return d&&!d[D]&&(d=l(d)),e&&!e[D]&&(e=l(e,f)),N(function(f,g,h,i){var j,l,m,n=[],p=[],q=g.length,r=f||o(b||"*",h.nodeType?[h]:h,[]),s=!a||!f&&b?r:k(r,n,a,h,i),t=c?e||(f?a:q||d)?[]:g:s;if(c&&c(s,t,h,i),d)for(j=k(t,p),d(j,[],h,i),l=j.length;l--;)(m=j[l])&&(t[p[l]]=!(s[p[l]]=m));if(f){if(e||a){if(e){for(j=[],l=t.length;l--;)(m=t[l])&&j.push(s[l]=m);e(null,t=[],j,i)}for(l=t.length;l--;)(m=t[l])&&(j=e?M.call(f,m):n[l])>-1&&(f[j]=!(g[j]=m))}}else t=k(t===g?t.splice(q,t.length):t),e?e(null,g,t,i):K.apply(g,t)})}function m(a){for(var b,c,d,e=a.length,f=t.relative[a[0].type],g=f||t.relative[" "],h=f?1:0,k=i(function(a){return a===b},g,!0),n=i(function(a){return M.call(b,a)>-1},g,!0),o=[function(a,c,d){return!f&&(d||c!==A)||((b=c).nodeType?k(a,c,d):n(a,c,d))}];e>h;h++)if(c=t.relative[a[h].type])o=[i(j(o),c)];else{if(c=t.filter[a[h].type].apply(null,a[h].matches),c[D]){for(d=++h;e>d&&!t.relative[a[d].type];d++);return l(h>1&&j(o),h>1&&a.slice(0,h-1).join("").replace(Z,"$1"),c,d>h&&m(a.slice(h,d)),e>d&&m(a=a.slice(d)),e>d&&a.join(""))}o.push(c)}return j(o)}function n(a,b){var d=b.length>0,e=a.length>0,f=function(g,h,i,j,l){var m,n,o,p=[],q=0,s="0",u=g&&[],v=null!=l,w=A,x=g||e&&t.find.TAG("*",l&&h.parentNode||h),y=H+=null==w?1:Math.E;for(v&&(A=h!==F&&h,r=f.el);null!=(m=x[s]);s++){if(e&&m){for(n=0;o=a[n];n++)if(o(m,h,i)){j.push(m);break}v&&(H=y,r=++f.el)}d&&((m=!o&&m)&&q--,g&&u.push(m))}if(q+=s,d&&s!==q){for(n=0;o=b[n];n++)o(u,p,h,i);if(g){if(q>0)for(;s--;)u[s]||p[s]||(p[s]=J.call(j));p=k(p)}K.apply(j,p),v&&!g&&p.length>0&&q+b.length>1&&c.uniqueSort(j)}return v&&(H=y,A=w),u};return f.el=0,d?N(f):f}function o(a,b,d){for(var e=0,f=b.length;f>e;e++)c(a,b[e],d);return d}function p(a,b,c,d,e){{var f,g,i,j,k,l=h(a);l.length}if(!d&&1===l.length){if(g=l[0]=l[0].slice(0),g.length>2&&"ID"===(i=g[0]).type&&9===b.nodeType&&!e&&t.relative[g[1].type]){if(b=t.find.ID(i.matches[0].replace(gb,""),b,e)[0],!b)return c;a=a.slice(g.shift().length)}for(f=hb.POS.test(a)?-1:g.length-1;f>=0&&(i=g[f],!t.relative[j=i.type]);f--)if((k=t.find[j])&&(d=k(i.matches[0].replace(gb,""),db.test(g[0].type)&&b.parentNode||b,e))){if(g.splice(f,1),a=d.length&&g.join(""),!a)return K.apply(c,L.call(d,0)),c;break}}return x(a,l)(d,b,e,c,db.test(a)),c}function q(){}var r,s,t,u,v,w,x,y,z,A,B=!0,C="undefined",D=("sizcache"+Math.random()).replace(".",""),E=String,F=a.document,G=F.documentElement,H=0,I=0,J=[].pop,K=[].push,L=[].slice,M=[].indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},N=function(a,b){return a[D]=null==b||b,a},O=function(){var a={},b=[];return N(function(c,d){return b.push(c)>t.cacheLength&&delete a[b.shift()],a[c+" "]=d},a)},P=O(),Q=O(),R=O(),S="[\\x20\\t\\r\\n\\f]",T="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",U=T.replace("w","w#"),V="([*^$|!~]?=)",W="\\["+S+"*("+T+")"+S+"*(?:"+V+S+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+U+")|)|)"+S+"*\\]",X=":("+T+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+W+")|[^:]|\\\\.)*|.*))\\)|)",Y=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+S+"*((?:-\\d)?\\d*)"+S+"*\\)|)(?=[^-]|$)",Z=new RegExp("^"+S+"+|((?:^|[^\\\\])(?:\\\\.)*)"+S+"+$","g"),_=new RegExp("^"+S+"*,"+S+"*"),ab=new RegExp("^"+S+"*([\\x20\\t\\r\\n\\f>+~])"+S+"*"),bb=new RegExp(X),cb=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,db=/[\x20\t\r\n\f]*[+~]/,eb=/h\d/i,fb=/input|select|textarea|button/i,gb=/\\(?!\\)/g,hb={ID:new RegExp("^#("+T+")"),CLASS:new RegExp("^\\.("+T+")"),NAME:new RegExp("^\\[name=['\"]?("+T+")['\"]?\\]"),TAG:new RegExp("^("+T.replace("w","w*")+")"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+X),POS:new RegExp(Y,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+S+"*(even|odd|(([+-]|)(\\d*)n|)"+S+"*(?:([+-]|)"+S+"*(\\d+)|))"+S+"*\\)|)","i"),needsContext:new RegExp("^"+S+"*[>+~]|"+Y,"i")},ib=function(a){var b=F.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},jb=ib(function(a){return a.appendChild(F.createComment("")),!a.getElementsByTagName("*").length}),kb=ib(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==C&&"#"===a.firstChild.getAttribute("href")}),lb=ib(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return"boolean"!==b&&"string"!==b}),mb=ib(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",a.getElementsByClassName&&a.getElementsByClassName("e").length?(a.lastChild.className="e",2===a.getElementsByClassName("e").length):!1}),nb=ib(function(a){a.id=D+0,a.innerHTML="<a name='"+D+"'></a><div name='"+D+"'></div>",G.insertBefore(a,G.firstChild);var b=F.getElementsByName&&F.getElementsByName(D).length===2+F.getElementsByName(D+0).length;return s=!F.getElementById(D),G.removeChild(a),b});try{L.call(G.childNodes,0)[0].nodeType}catch(ob){L=function(a){for(var b,c=[];b=this[a];a++)c.push(b);return c}}c.matches=function(a,b){return c(a,null,null,b)},c.matchesSelector=function(a,b){return c(b,null,null,[a]).length>0},u=c.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(1===e||9===e||11===e){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=u(a)}else if(3===e||4===e)return a.nodeValue}else for(;b=a[d];d++)c+=u(b);return c},v=c.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},w=c.contains=G.contains?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&1===d.nodeType&&c.contains&&c.contains(d))}:G.compareDocumentPosition?function(a,b){return b&&!!(16&a.compareDocumentPosition(b))}:function(a,b){for(;b=b.parentNode;)if(b===a)return!0;return!1},c.attr=function(a,b){var c,d=v(a);return d||(b=b.toLowerCase()),(c=t.attrHandle[b])?c(a):d||lb?a.getAttribute(b):(c=a.getAttributeNode(b),c?"boolean"==typeof a[b]?a[b]?b:null:c.specified?c.value:null:null)},t=c.selectors={cacheLength:50,createPseudo:N,match:hb,attrHandle:kb?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:s?function(a,b,c){if(typeof b.getElementById!==C&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==C&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==C&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:jb?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c=b.getElementsByTagName(a);if("*"===a){for(var d,e=[],f=0;d=c[f];f++)1===d.nodeType&&e.push(d);return e}return c},NAME:nb&&function(a,b){return typeof b.getElementsByName!==C?b.getElementsByName(name):void 0},CLASS:mb&&function(a,b,c){return typeof b.getElementsByClassName===C||c?void 0:b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(gb,""),a[3]=(a[4]||a[5]||"").replace(gb,""),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1]?(a[2]||c.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*("even"===a[2]||"odd"===a[2])),a[4]=+(a[6]+a[7]||"odd"===a[2])):a[2]&&c.error(a[0]),a},PSEUDO:function(a){var b,c;return hb.CHILD.test(a[0])?null:(a[3]?a[2]=a[3]:(b=a[4])&&(bb.test(b)&&(c=h(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b),a.slice(0,3))}},filter:{ID:s?function(a){return a=a.replace(gb,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(gb,""),function(b){var c=typeof b.getAttributeNode!==C&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return"*"===a?function(){return!0}:(a=a.replace(gb,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=P[D][a+" "];return b||(b=new RegExp("(^|"+S+")"+a+"("+S+"|$)"))&&P(a,function(a){return b.test(a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,d){return function(e){var f=c.attr(e,a);return null==f?"!="===b:b?(f+="","="===b?f===d:"!="===b?f!==d:"^="===b?d&&0===f.indexOf(d):"*="===b?d&&f.indexOf(d)>-1:"$="===b?d&&f.substr(f.length-d.length)===d:"~="===b?(" "+f+" ").indexOf(d)>-1:"|="===b?f===d||f.substr(0,d.length+1)===d+"-":!1):!0}},CHILD:function(a,b,c,d){return"nth"===a?function(a){var b,e,f=a.parentNode;if(1===c&&0===d)return!0;if(f)for(e=0,b=f.firstChild;b&&(1!==b.nodeType||(e++,a!==b));b=b.nextSibling);return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":for(;c=c.previousSibling;)if(1===c.nodeType)return!1;if("first"===a)return!0;c=b;case"last":for(;c=c.nextSibling;)if(1===c.nodeType)return!1;return!0}}},PSEUDO:function(a,b){var d,e=t.pseudos[a]||t.setFilters[a.toLowerCase()]||c.error("unsupported pseudo: "+a);return e[D]?e(b):e.length>1?(d=[a,a,"",b],t.setFilters.hasOwnProperty(a.toLowerCase())?N(function(a,c){for(var d,f=e(a,b),g=f.length;g--;)d=M.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,d)}):e}},pseudos:{not:N(function(a){var b=[],c=[],d=x(a.replace(Z,"$1"));return d[D]?N(function(a,b,c,e){for(var f,g=d(a,null,e,[]),h=a.length;h--;)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:N(function(a){return function(b){return c(a,b).length>0}}),contains:N(function(a){return function(b){return(b.textContent||b.innerText||u(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!t.pseudos.empty(a)},empty:function(a){var b;for(a=a.firstChild;a;){if(a.nodeName>"@"||3===(b=a.nodeType)||4===b)return!1;a=a.nextSibling}return!0},header:function(a){return eb.test(a.nodeName)},text:function(a){var b,c;return"input"===a.nodeName.toLowerCase()&&"text"===(b=a.type)&&(null==(c=a.getAttribute("type"))||c.toLowerCase()===b)},radio:d("radio"),checkbox:d("checkbox"),file:d("file"),password:d("password"),image:d("image"),submit:e("submit"),reset:e("reset"),button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},input:function(a){return fb.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},active:function(a){return a===a.ownerDocument.activeElement},first:f(function(){return[0]}),last:f(function(a,b){return[b-1]}),eq:f(function(a,b,c){return[0>c?c+b:c]}),even:f(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:f(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:f(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:f(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},y=G.compareDocumentPosition?function(a,b){return a===b?(z=!0,0):(a.compareDocumentPosition&&b.compareDocumentPosition?4&a.compareDocumentPosition(b):a.compareDocumentPosition)?-1:1}:function(a,b){if(a===b)return z=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return g(a,b);if(!h)return-1;if(!i)return 1;for(;j;)e.unshift(j),j=j.parentNode;for(j=i;j;)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;c>k&&d>k;k++)if(e[k]!==f[k])return g(e[k],f[k]);return k===c?g(a,f[k],-1):g(e[k],b,1)},[0,0].sort(y),B=!z,c.uniqueSort=function(a){var b,c=[],d=1,e=0;if(z=B,a.sort(y),z){for(;b=a[d];d++)b===a[d-1]&&(e=c.push(d));for(;e--;)a.splice(c[e],1)}return a},c.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},x=c.compile=function(a,b){var c,d=[],e=[],f=R[D][a+" "];if(!f){for(b||(b=h(a)),c=b.length;c--;)f=m(b[c]),f[D]?d.push(f):e.push(f);f=R(a,n(e,d))}return f},F.querySelectorAll&&!function(){var a,b=p,d=/'|\\/g,e=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,f=[":focus"],g=[":active"],i=G.matchesSelector||G.mozMatchesSelector||G.webkitMatchesSelector||G.oMatchesSelector||G.msMatchesSelector;ib(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||f.push("\\["+S+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||f.push(":checked")}),ib(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&f.push("[*^$]="+S+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||f.push(":enabled",":disabled")}),f=new RegExp(f.join("|")),p=function(a,c,e,g,i){if(!g&&!i&&!f.test(a)){var j,k,l=!0,m=D,n=c,o=9===c.nodeType&&a;if(1===c.nodeType&&"object"!==c.nodeName.toLowerCase()){for(j=h(a),(l=c.getAttribute("id"))?m=l.replace(d,"\\$&"):c.setAttribute("id",m),m="[id='"+m+"'] ",k=j.length;k--;)j[k]=m+j[k].join("");n=db.test(a)&&c.parentNode||c,o=j.join(",")}if(o)try{return K.apply(e,L.call(n.querySelectorAll(o),0)),e}catch(p){}finally{l||c.removeAttribute("id")}}return b(a,c,e,g,i)},i&&(ib(function(b){a=i.call(b,"div");try{i.call(b,"[test!='']:sizzle"),g.push("!=",X)}catch(c){}}),g=new RegExp(g.join("|")),c.matchesSelector=function(b,d){if(d=d.replace(e,"='$1']"),!v(b)&&!g.test(d)&&!f.test(d))try{var h=i.call(b,d);if(h||a||b.document&&11!==b.document.nodeType)return h}catch(j){}return c(d,null,null,[b]).length>0})}(),t.pseudos.nth=t.pseudos.eq,t.filters=q.prototype=t.pseudos,t.setFilters=new q,c.attr=$.attr,$.find=c,$.expr=c.selectors,$.expr[":"]=$.expr.pseudos,$.unique=c.uniqueSort,$.text=c.getText,$.isXMLDoc=c.isXML,$.contains=c.contains}(a);var Ib=/Until$/,Jb=/^(?:parents|prev(?:Until|All))/,Kb=/^.[^:#\[\.,]*$/,Lb=$.expr.match.needsContext,Mb={children:!0,contents:!0,next:!0,prev:!0};$.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if("string"!=typeof a)return $(a).filter(function(){for(b=0,c=h.length;c>b;b++)if($.contains(h[b],this))return!0});for(g=this.pushStack("","find",a),b=0,c=this.length;c>b;b++)if(d=g.length,$.find(a,this[b],g),b>0)for(e=d;e<g.length;e++)for(f=0;d>f;f++)if(g[f]===g[e]){g.splice(e--,1);break}return g},has:function(a){var b,c=$(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if($.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(j(this,a,!1),"not",a)},filter:function(a){return this.pushStack(j(this,a,!0),"filter",a)},is:function(a){return!!a&&("string"==typeof a?Lb.test(a)?$(a,this.context).index(this[0])>=0:$.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=Lb.test(a)||"string"!=typeof a?$(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c.ownerDocument&&c!==b&&11!==c.nodeType;){if(g?g.index(c)>-1:$.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}return f=f.length>1?$.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?"string"==typeof a?$.inArray(this[0],$(a)):$.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c="string"==typeof a?$(a,b):$.makeArray(a&&a.nodeType?[a]:a),d=$.merge(this.get(),c);return this.pushStack(h(c[0])||h(d[0])?d:$.unique(d))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}}),$.fn.andSelf=$.fn.addBack,$.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return $.dir(a,"parentNode")},parentsUntil:function(a,b,c){return $.dir(a,"parentNode",c)},next:function(a){return i(a,"nextSibling")},prev:function(a){return i(a,"previousSibling")},nextAll:function(a){return $.dir(a,"nextSibling")},prevAll:function(a){return $.dir(a,"previousSibling")},nextUntil:function(a,b,c){return $.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return $.dir(a,"previousSibling",c)},siblings:function(a){return $.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return $.sibling(a.firstChild)},contents:function(a){return $.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:$.merge([],a.childNodes)}},function(a,b){$.fn[a]=function(c,d){var e=$.map(this,b,c);return Ib.test(a)||(d=c),d&&"string"==typeof d&&(e=$.filter(d,e)),e=this.length>1&&!Mb[a]?$.unique(e):e,this.length>1&&Jb.test(a)&&(e=e.reverse()),this.pushStack(e,a,V.call(arguments).join(","))}}),$.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),1===b.length?$.find.matchesSelector(b[0],a)?[b[0]]:[]:$.find.matches(a,b)},dir:function(a,c,d){for(var e=[],f=a[c];f&&9!==f.nodeType&&(d===b||1!==f.nodeType||!$(f).is(d));)1===f.nodeType&&e.push(f),f=f[c];return e},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}});var Nb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Ob=/ jQuery\d+="(?:null|\d+)"/g,Pb=/^\s+/,Qb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Rb=/<([\w:]+)/,Sb=/<tbody/i,Tb=/<|&#?\w+;/,Ub=/<(?:script|style|link)/i,Vb=/<(?:script|object|embed|option|style)/i,Wb=new RegExp("<(?:"+Nb+")[\\s/>]","i"),Xb=/^(?:checkbox|radio)$/,Yb=/checked\s*(?:[^=]|=\s*.checked.)/i,Zb=/\/(java|ecma)script/i,$b=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,_b={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,"",""]},ac=k(P),bc=ac.appendChild(P.createElement("div"));_b.optgroup=_b.option,_b.tbody=_b.tfoot=_b.colgroup=_b.caption=_b.thead,_b.th=_b.td,$.support.htmlSerialize||(_b._default=[1,"X<div>","</div>"]),$.fn.extend({text:function(a){return $.access(this,function(a){return a===b?$.text(this):this.empty().append((this[0]&&this[0].ownerDocument||P).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if($.isFunction(a))return this.each(function(b){$(this).wrapAll(a.call(this,b))});if(this[0]){var b=$(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){for(var a=this;a.firstChild&&1===a.firstChild.nodeType;)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each($.isFunction(a)?function(b){$(this).wrapInner(a.call(this,b))}:function(){var b=$(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=$.isFunction(a);return this.each(function(c){$(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){$.nodeName(this,"body")||$(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(1===this.nodeType||11===this.nodeType)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(1===this.nodeType||11===this.nodeType)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!h(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=$.clean(arguments);return this.pushStack($.merge(a,this),"before",this.selector)}},after:function(){if(!h(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=$.clean(arguments);return this.pushStack($.merge(this,a),"after",this.selector)}},remove:function(a,b){for(var c,d=0;null!=(c=this[d]);d++)(!a||$.filter(a,[c]).length)&&(b||1!==c.nodeType||($.cleanData(c.getElementsByTagName("*")),$.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)for(1===a.nodeType&&$.cleanData(a.getElementsByTagName("*"));a.firstChild;)a.removeChild(a.firstChild);return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return $.clone(this,a,b)})},html:function(a){return $.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return 1===c.nodeType?c.innerHTML.replace(Ob,""):b;if(!("string"!=typeof a||Ub.test(a)||!$.support.htmlSerialize&&Wb.test(a)||!$.support.leadingWhitespace&&Pb.test(a)||_b[(Rb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(Qb,"<$1></$2>");try{for(;e>d;d++)c=this[d]||{},1===c.nodeType&&($.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return h(this[0])?this.length?this.pushStack($($.isFunction(a)?a():a),"replaceWith",a):this:$.isFunction(a)?this.each(function(b){var c=$(this),d=c.html();c.replaceWith(a.call(this,b,d))}):("string"!=typeof a&&(a=$(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;$(this).remove(),b?$(b).before(a):$(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],m=this.length;if(!$.support.checkClone&&m>1&&"string"==typeof j&&Yb.test(j))return this.each(function(){$(this).domManip(a,c,d)});if($.isFunction(j))return this.each(function(e){var f=$(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){if(e=$.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,1===g.childNodes.length&&(g=f),f)for(c=c&&$.nodeName(f,"tr"),h=e.cacheable||m-1;m>i;i++)d.call(c&&$.nodeName(this[i],"table")?l(this[i],"tbody"):this[i],i===h?g:$.clone(g,!0,!0));g=f=null,k.length&&$.each(k,function(a,b){b.src?$.ajax?$.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):$.error("no ajax"):$.globalEval((b.text||b.textContent||b.innerHTML||"").replace($b,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),$.buildFragment=function(a,c,d){var e,f,g,h=a[0];return c=c||P,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,!(1===a.length&&"string"==typeof h&&h.length<512&&c===P&&"<"===h.charAt(0))||Vb.test(h)||!$.support.checkClone&&Yb.test(h)||!$.support.html5Clone&&Wb.test(h)||(f=!0,e=$.fragments[h],g=e!==b),e||(e=c.createDocumentFragment(),$.clean(a,c,e,d),f&&($.fragments[h]=g&&e)),{fragment:e,cacheable:f} },$.fragments={},$.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){$.fn[a]=function(c){var d,e=0,f=[],g=$(c),h=g.length,i=1===this.length&&this[0].parentNode;if((null==i||i&&11===i.nodeType&&1===i.childNodes.length)&&1===h)return g[b](this[0]),this;for(;h>e;e++)d=(e>0?this.clone(!0):this).get(),$(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),$.extend({clone:function(a,b,c){var d,e,f,g;if($.support.html5Clone||$.isXMLDoc(a)||!Wb.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bc.innerHTML=a.outerHTML,bc.removeChild(g=bc.firstChild)),!($.support.noCloneEvent&&$.support.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||$.isXMLDoc(a)))for(n(a,g),d=o(a),e=o(g),f=0;d[f];++f)e[f]&&n(d[f],e[f]);if(b&&(m(a,g),c))for(d=o(a),e=o(g),f=0;d[f];++f)m(d[f],e[f]);return d=e=null,g},clean:function(a,b,c,d){var e,f,g,h,i,j,l,m,n,o,q,r=b===P&&ac,s=[];for(b&&"undefined"!=typeof b.createDocumentFragment||(b=P),e=0;null!=(g=a[e]);e++)if("number"==typeof g&&(g+=""),g){if("string"==typeof g)if(Tb.test(g)){for(r=r||k(b),l=b.createElement("div"),r.appendChild(l),g=g.replace(Qb,"<$1></$2>"),h=(Rb.exec(g)||["",""])[1].toLowerCase(),i=_b[h]||_b._default,j=i[0],l.innerHTML=i[1]+g+i[2];j--;)l=l.lastChild;if(!$.support.tbody)for(m=Sb.test(g),n="table"!==h||m?"<table>"!==i[1]||m?[]:l.childNodes:l.firstChild&&l.firstChild.childNodes,f=n.length-1;f>=0;--f)$.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f]);!$.support.leadingWhitespace&&Pb.test(g)&&l.insertBefore(b.createTextNode(Pb.exec(g)[0]),l.firstChild),g=l.childNodes,l.parentNode.removeChild(l)}else g=b.createTextNode(g);g.nodeType?s.push(g):$.merge(s,g)}if(l&&(g=l=r=null),!$.support.appendChecked)for(e=0;null!=(g=s[e]);e++)$.nodeName(g,"input")?p(g):"undefined"!=typeof g.getElementsByTagName&&$.grep(g.getElementsByTagName("input"),p);if(c)for(o=function(a){return!a.type||Zb.test(a.type)?d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a):void 0},e=0;null!=(g=s[e]);e++)$.nodeName(g,"script")&&o(g)||(c.appendChild(g),"undefined"!=typeof g.getElementsByTagName&&(q=$.grep($.merge([],g.getElementsByTagName("script")),o),s.splice.apply(s,[e+1,0].concat(q)),e+=q.length));return s},cleanData:function(a,b){for(var c,d,e,f,g=0,h=$.expando,i=$.cache,j=$.support.deleteExpando,k=$.event.special;null!=(e=a[g]);g++)if((b||$.acceptData(e))&&(d=e[h],c=d&&i[d])){if(c.events)for(f in c.events)k[f]?$.event.remove(e,f):$.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,$.deletedIds.push(d))}}}),function(){var a,b;$.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=$.uaMatch(R.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),$.browser=b,$.sub=function(){function a(b,c){return new a.fn.init(b,c)}$.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(c,d){return d&&d instanceof $&&!(d instanceof a)&&(d=a(d)),$.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(P);return a}}();var cc,dc,ec,fc=/alpha\([^)]*\)/i,gc=/opacity=([^)]*)/,hc=/^(top|right|bottom|left)$/,ic=/^(none|table(?!-c[ea]).+)/,jc=/^margin/,kc=new RegExp("^("+_+")(.*)$","i"),lc=new RegExp("^("+_+")(?!px)[a-z%]+$","i"),mc=new RegExp("^([-+])=("+_+")","i"),nc={BODY:"block"},oc={position:"absolute",visibility:"hidden",display:"block"},pc={letterSpacing:0,fontWeight:400},qc=["Top","Right","Bottom","Left"],rc=["Webkit","O","Moz","ms"],sc=$.fn.toggle;$.fn.extend({css:function(a,c){return $.access(this,function(a,c,d){return d!==b?$.style(a,c,d):$.css(a,c)},a,c,arguments.length>1)},show:function(){return s(this,!0)},hide:function(){return s(this)},toggle:function(a,b){var c="boolean"==typeof a;return $.isFunction(a)&&$.isFunction(b)?sc.apply(this,arguments):this.each(function(){(c?a:r(this))?$(this).show():$(this).hide()})}}),$.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=cc(a,"opacity");return""===c?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":$.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var f,g,h,i=$.camelCase(c),j=a.style;if(c=$.cssProps[i]||($.cssProps[i]=q(j,i)),h=$.cssHooks[c]||$.cssHooks[i],d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];if(g=typeof d,"string"===g&&(f=mc.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat($.css(a,c)),g="number"),!(null==d||"number"===g&&isNaN(d)||("number"!==g||$.cssNumber[i]||(d+="px"),h&&"set"in h&&(d=h.set(a,d,e))===b)))try{j[c]=d}catch(k){}}},css:function(a,c,d,e){var f,g,h,i=$.camelCase(c);return c=$.cssProps[i]||($.cssProps[i]=q(a.style,i)),h=$.cssHooks[c]||$.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=cc(a,c)),"normal"===f&&c in pc&&(f=pc[c]),d||e!==b?(g=parseFloat(f),d||$.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?cc=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h.getPropertyValue(c)||h[c],""!==d||$.contains(b.ownerDocument,b)||(d=$.style(b,c)),lc.test(d)&&jc.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:P.documentElement.currentStyle&&(cc=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return null==e&&f&&f[b]&&(e=f[b]),lc.test(e)&&!hc.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left="fontSize"===b?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),""===e?"auto":e}),$.each(["height","width"],function(a,b){$.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&ic.test(cc(a,"display"))?$.swap(a,oc,function(){return v(a,b,d)}):v(a,b,d):void 0},set:function(a,c,d){return t(a,c,d?u(a,b,d,$.support.boxSizing&&"border-box"===$.css(a,"boxSizing")):0)}}}),$.support.opacity||($.cssHooks.opacity={get:function(a,b){return gc.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=$.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,b>=1&&""===$.trim(f.replace(fc,""))&&c.removeAttribute&&(c.removeAttribute("filter"),d&&!d.filter)||(c.filter=fc.test(f)?f.replace(fc,e):f+" "+e)}}),$(function(){$.support.reliableMarginRight||($.cssHooks.marginRight={get:function(a,b){return $.swap(a,{display:"inline-block"},function(){return b?cc(a,"marginRight"):void 0})}}),!$.support.pixelPosition&&$.fn.position&&$.each(["top","left"],function(a,b){$.cssHooks[b]={get:function(a,c){if(c){var d=cc(a,b);return lc.test(d)?$(a).position()[b]+"px":d}}}})}),$.expr&&$.expr.filters&&($.expr.filters.hidden=function(a){return 0===a.offsetWidth&&0===a.offsetHeight||!$.support.reliableHiddenOffsets&&"none"===(a.style&&a.style.display||cc(a,"display"))},$.expr.filters.visible=function(a){return!$.expr.filters.hidden(a)}),$.each({margin:"",padding:"",border:"Width"},function(a,b){$.cssHooks[a+b]={expand:function(c){var d,e="string"==typeof c?c.split(" "):[c],f={};for(d=0;4>d;d++)f[a+qc[d]+b]=e[d]||e[d-2]||e[0];return f}},jc.test(a)||($.cssHooks[a+b].set=t)});var tc=/%20/g,uc=/\[\]$/,vc=/\r?\n/g,wc=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,xc=/^(?:select|textarea)/i;$.fn.extend({serialize:function(){return $.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?$.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||xc.test(this.nodeName)||wc.test(this.type))}).map(function(a,b){var c=$(this).val();return null==c?null:$.isArray(c)?$.map(c,function(a){return{name:b.name,value:a.replace(vc,"\r\n")}}):{name:b.name,value:c.replace(vc,"\r\n")}}).get()}}),$.param=function(a,c){var d,e=[],f=function(a,b){b=$.isFunction(b)?b():null==b?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(c===b&&(c=$.ajaxSettings&&$.ajaxSettings.traditional),$.isArray(a)||a.jquery&&!$.isPlainObject(a))$.each(a,function(){f(this.name,this.value)});else for(d in a)x(d,a[d],c,f);return e.join("&").replace(tc,"+")};var yc,zc,Ac=/#.*$/,Bc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cc=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,Dc=/^(?:GET|HEAD)$/,Ec=/^\/\//,Fc=/\?/,Gc=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,Hc=/([?&])_=[^&]*/,Ic=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Jc=$.fn.load,Kc={},Lc={},Mc=["*/"]+["*"];try{zc=Q.href}catch(Nc){zc=P.createElement("a"),zc.href="",zc=zc.href}yc=Ic.exec(zc.toLowerCase())||[],$.fn.load=function(a,c,d){if("string"!=typeof a&&Jc)return Jc.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),$.isFunction(c)?(d=c,c=b):c&&"object"==typeof c&&(f="POST"),$.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?$("<div>").append(a.replace(Gc,"")).find(e):a)}),this},$.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){$.fn[b]=function(a){return this.on(b,a)}}),$.each(["get","post"],function(a,c){$[c]=function(a,d,e,f){return $.isFunction(d)&&(f=f||e,e=d,d=b),$.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),$.extend({getScript:function(a,c){return $.get(a,b,c,"script")},getJSON:function(a,b,c){return $.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?A(a,$.ajaxSettings):(b=a,a=$.ajaxSettings),A(a,b),a},ajaxSettings:{url:zc,isLocal:Cc.test(yc[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","*":Mc},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":$.parseJSON,"text xml":$.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:y(Kc),ajaxTransport:y(Lc),ajax:function(a,c){function d(a,c,d,g){var j,l,s,t,v,x=c;2!==u&&(u=2,i&&clearTimeout(i),h=b,f=g||"",w.readyState=a>0?4:0,d&&(t=B(m,w,d)),a>=200&&300>a||304===a?(m.ifModified&&(v=w.getResponseHeader("Last-Modified"),v&&($.lastModified[e]=v),v=w.getResponseHeader("Etag"),v&&($.etag[e]=v)),304===a?(x="notmodified",j=!0):(j=C(m,t),x=j.state,l=j.data,s=j.error,j=!s)):(s=x,(!x||a)&&(x="error",0>a&&(a=0))),w.status=a,w.statusText=(c||x)+"",j?p.resolveWith(n,[l,x,w]):p.rejectWith(n,[w,x,s]),w.statusCode(r),r=b,k&&o.trigger("ajax"+(j?"Success":"Error"),[w,m,j?l:s]),q.fireWith(n,[w,x]),k&&(o.trigger("ajaxComplete",[w,m]),--$.active||$.event.trigger("ajaxStop")))}"object"==typeof a&&(c=a,a=b),c=c||{};var e,f,g,h,i,j,k,l,m=$.ajaxSetup({},c),n=m.context||m,o=n!==m&&(n.nodeType||n instanceof $)?$(n):$.event,p=$.Deferred(),q=$.Callbacks("once memory"),r=m.statusCode||{},s={},t={},u=0,v="canceled",w={readyState:0,setRequestHeader:function(a,b){if(!u){var c=a.toLowerCase();a=t[c]=t[c]||a,s[a]=b}return this},getAllResponseHeaders:function(){return 2===u?f:null},getResponseHeader:function(a){var c;if(2===u){if(!g)for(g={};c=Bc.exec(f);)g[c[1].toLowerCase()]=c[2];c=g[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return u||(m.mimeType=a),this},abort:function(a){return a=a||v,h&&h.abort(a),d(0,a),this}};if(p.promise(w),w.success=w.done,w.error=w.fail,w.complete=q.add,w.statusCode=function(a){if(a){var b;if(2>u)for(b in a)r[b]=[r[b],a[b]];else b=a[w.status],w.always(b)}return this},m.url=((a||m.url)+"").replace(Ac,"").replace(Ec,yc[1]+"//"),m.dataTypes=$.trim(m.dataType||"*").toLowerCase().split(bb),null==m.crossDomain&&(j=Ic.exec(m.url.toLowerCase()),m.crossDomain=!(!j||j[1]===yc[1]&&j[2]===yc[2]&&(j[3]||("http:"===j[1]?80:443))==(yc[3]||("http:"===yc[1]?80:443)))),m.data&&m.processData&&"string"!=typeof m.data&&(m.data=$.param(m.data,m.traditional)),z(Kc,m,c,w),2===u)return w;if(k=m.global,m.type=m.type.toUpperCase(),m.hasContent=!Dc.test(m.type),k&&0===$.active++&&$.event.trigger("ajaxStart"),!m.hasContent&&(m.data&&(m.url+=(Fc.test(m.url)?"&":"?")+m.data,delete m.data),e=m.url,m.cache===!1)){var x=$.now(),y=m.url.replace(Hc,"$1_="+x);m.url=y+(y===m.url?(Fc.test(m.url)?"&":"?")+"_="+x:"")}(m.data&&m.hasContent&&m.contentType!==!1||c.contentType)&&w.setRequestHeader("Content-Type",m.contentType),m.ifModified&&(e=e||m.url,$.lastModified[e]&&w.setRequestHeader("If-Modified-Since",$.lastModified[e]),$.etag[e]&&w.setRequestHeader("If-None-Match",$.etag[e])),w.setRequestHeader("Accept",m.dataTypes[0]&&m.accepts[m.dataTypes[0]]?m.accepts[m.dataTypes[0]]+("*"!==m.dataTypes[0]?", "+Mc+"; q=0.01":""):m.accepts["*"]);for(l in m.headers)w.setRequestHeader(l,m.headers[l]);if(m.beforeSend&&(m.beforeSend.call(n,w,m)===!1||2===u))return w.abort();v="abort";for(l in{success:1,error:1,complete:1})w[l](m[l]);if(h=z(Lc,m,c,w)){w.readyState=1,k&&o.trigger("ajaxSend",[w,m]),m.async&&m.timeout>0&&(i=setTimeout(function(){w.abort("timeout")},m.timeout));try{u=1,h.send(s,d)}catch(A){if(!(2>u))throw A;d(-1,A)}}else d(-1,"No Transport");return w},active:0,lastModified:{},etag:{}});var Oc=[],Pc=/\?/,Qc=/(=)\?(?=&|$)|\?\?/,Rc=$.now();$.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Oc.pop()||$.expando+"_"+Rc++;return this[a]=!0,a}}),$.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&Qc.test(j),m=k&&!l&&"string"==typeof i&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&Qc.test(i);return"jsonp"===c.dataTypes[0]||l||m?(f=c.jsonpCallback=$.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(Qc,"$1"+f):m?c.data=i.replace(Qc,"$1"+f):k&&(c.url+=(Pc.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||$.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,Oc.push(f)),h&&$.isFunction(g)&&g(h[0]),h=g=b}),"script"):void 0}),$.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return $.globalEval(a),a}}}),$.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),$.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=P.head||P.getElementsByTagName("head")[0]||P.documentElement;return{send:function(e,f){c=P.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){(e||!c.readyState||/loaded|complete/.test(c.readyState))&&(c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||f(200,"success"))},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var Sc,Tc=a.ActiveXObject?function(){for(var a in Sc)Sc[a](0,1)}:!1,Uc=0;$.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&D()||E()}:D,function(a){$.extend($.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}($.ajaxSettings.xhr()),$.support.ajax&&$.ajaxTransport(function(c){if(!c.crossDomain||$.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();if(c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async),c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),c.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||4===i.readyState))if(d=b,g&&(i.onreadystatechange=$.noop,Tc&&delete Sc[g]),e)4!==i.readyState&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(n){}try{j=i.statusText}catch(n){j=""}h||!c.isLocal||c.crossDomain?1223===h&&(h=204):h=l.text?200:404}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?4===i.readyState?setTimeout(d,0):(g=++Uc,Tc&&(Sc||(Sc={},$(a).unload(Tc)),Sc[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var Vc,Wc,Xc=/^(?:toggle|show|hide)$/,Yc=new RegExp("^(?:([-+])=|)("+_+")([a-z%]*)$","i"),Zc=/queueHooks$/,$c=[J],_c={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=Yc.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){if(c=+f[2],d=f[3]||($.cssNumber[a]?"":"px"),"px"!==d&&h){h=$.css(e.elem,a,!0)||c||1;do i=i||".5",h/=i,$.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&1!==i&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};$.Animation=$.extend(H,{tweener:function(a,b){$.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],_c[c]=_c[c]||[],_c[c].unshift(b)},prefilter:function(a,b){b?$c.unshift(a):$c.push(a)}}),$.Tween=K,K.prototype={constructor:K,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||($.cssNumber[c]?"":"px")},cur:function(){var a=K.propHooks[this.prop];return a&&a.get?a.get(this):K.propHooks._default.get(this)},run:function(a){var b,c=K.propHooks[this.prop];return this.pos=b=this.options.duration?$.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):K.propHooks._default.set(this),this}},K.prototype.init.prototype=K.prototype,K.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=$.css(a.elem,a.prop,!1,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){$.fx.step[a.prop]?$.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[$.cssProps[a.prop]]||$.cssHooks[a.prop])?$.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},K.propHooks.scrollTop=K.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},$.each(["toggle","show","hide"],function(a,b){var c=$.fn[b];$.fn[b]=function(d,e,f){return null==d||"boolean"==typeof d||!a&&$.isFunction(d)&&$.isFunction(e)?c.apply(this,arguments):this.animate(L(b,!0),d,e,f)}}),$.fn.extend({fadeTo:function(a,b,c,d){return this.filter(r).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=$.isEmptyObject(a),f=$.speed(b,c,d),g=function(){var b=H(this,$.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return"string"!=typeof a&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=null!=a&&a+"queueHooks",f=$.timers,g=$._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&Zc.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem!==this||null!=a&&f[c].queue!==a||(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&$.dequeue(this,a)})}}),$.each({slideDown:L("show"),slideUp:L("hide"),slideToggle:L("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){$.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),$.speed=function(a,b,c){var d=a&&"object"==typeof a?$.extend({},a):{complete:c||!c&&b||$.isFunction(a)&&a,duration:a,easing:c&&b||b&&!$.isFunction(b)&&b};return d.duration=$.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in $.fx.speeds?$.fx.speeds[d.duration]:$.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){$.isFunction(d.old)&&d.old.call(this),d.queue&&$.dequeue(this,d.queue)},d},$.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},$.timers=[],$.fx=K.prototype.init,$.fx.tick=function(){var a,c=$.timers,d=0;for(Vc=$.now();d<c.length;d++)a=c[d],a()||c[d]!==a||c.splice(d--,1);c.length||$.fx.stop(),Vc=b},$.fx.timer=function(a){a()&&$.timers.push(a)&&!Wc&&(Wc=setInterval($.fx.tick,$.fx.interval))},$.fx.interval=13,$.fx.stop=function(){clearInterval(Wc),Wc=null},$.fx.speeds={slow:600,fast:200,_default:400},$.fx.step={},$.expr&&$.expr.filters&&($.expr.filters.animated=function(a){return $.grep($.timers,function(b){return a===b.elem}).length});var ad=/^(?:body|html)$/i;$.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){$.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(l)return(d=l.body)===k?$.offset.bodyOffset(k):(c=l.documentElement,$.contains(c,k)?("undefined"!=typeof k.getBoundingClientRect&&(j=k.getBoundingClientRect()),e=M(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},$.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return $.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat($.css(a,"marginTop"))||0,c+=parseFloat($.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=$.css(a,"position");"static"===d&&(a.style.position="relative");var e,f,g=$(a),h=g.offset(),i=$.css(a,"top"),j=$.css(a,"left"),k=("absolute"===d||"fixed"===d)&&$.inArray("auto",[i,j])>-1,l={},m={};k?(m=g.position(),e=m.top,f=m.left):(e=parseFloat(i)||0,f=parseFloat(j)||0),$.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(l.top=b.top-h.top+e),null!=b.left&&(l.left=b.left-h.left+f),"using"in b?b.using.call(a,l):g.css(l)}},$.fn.extend({position:function(){if(this[0]){var a=this[0],b=this.offsetParent(),c=this.offset(),d=ad.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat($.css(a,"marginTop"))||0,c.left-=parseFloat($.css(a,"marginLeft"))||0,d.top+=parseFloat($.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat($.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||P.body;a&&!ad.test(a.nodeName)&&"static"===$.css(a,"position");)a=a.offsetParent;return a||P.body})}}),$.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);$.fn[a]=function(e){return $.access(this,function(a,e,f){var g=M(a);return f===b?g?c in g?g[c]:g.document.documentElement[e]:a[e]:void(g?g.scrollTo(d?$(g).scrollLeft():f,d?f:$(g).scrollTop()):a[e]=f)},a,e,arguments.length,null)}}),$.each({Height:"height",Width:"width"},function(a,c){$.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){$.fn[e]=function(e,f){var g=arguments.length&&(d||"boolean"!=typeof e),h=d||(e===!0||f===!0?"margin":"border");return $.access(this,function(c,d,e){var f;return $.isWindow(c)?c.document.documentElement["client"+a]:9===c.nodeType?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?$.css(c,d,e,h):$.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=$,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return $})}(window),function(a){for(var b=0,c=["webkit","moz"],d=a.requestAnimationFrame,e=a.cancelAnimationFrame,f=c.length;--f>=0&&!d;)d=a[c[f]+"RequestAnimationFrame"],e=a[c[f]+"CancelAnimationFrame"];d&&e||(d=function(a){var c=Date.now(),d=Math.max(b+16,c);return setTimeout(function(){a(b=d)},d-c)},e=clearTimeout),a.requestAnimationFrame=d,a.cancelAnimationFrame=e}(window),function(a){var b,c,d="0.3.4",e="hasOwnProperty",f=/[\.\/]/,g="*",h=function(){},i=function(a,b){return a-b},j={n:{}},k=function(a,d){var e,f=c,g=Array.prototype.slice.call(arguments,2),h=k.listeners(a),j=0,l=[],m={},n=[],o=b;b=a,c=0;for(var p=0,q=h.length;q>p;p++)"zIndex"in h[p]&&(l.push(h[p].zIndex),h[p].zIndex<0&&(m[h[p].zIndex]=h[p]));for(l.sort(i);l[j]<0;)if(e=m[l[j++]],n.push(e.apply(d,g)),c)return c=f,n;for(p=0;q>p;p++)if(e=h[p],"zIndex"in e)if(e.zIndex==l[j]){if(n.push(e.apply(d,g)),c)break;do if(j++,e=m[l[j]],e&&n.push(e.apply(d,g)),c)break;while(e)}else m[e.zIndex]=e;else if(n.push(e.apply(d,g)),c)break;return c=f,b=o,n.length?n:null};k.listeners=function(a){var b,c,d,e,h,i,k,l,m=a.split(f),n=j,o=[n],p=[];for(e=0,h=m.length;h>e;e++){for(l=[],i=0,k=o.length;k>i;i++)for(n=o[i].n,c=[n[m[e]],n[g]],d=2;d--;)b=c[d],b&&(l.push(b),p=p.concat(b.f||[]));o=l}return p},k.on=function(a,b){for(var c=a.split(f),d=j,e=0,g=c.length;g>e;e++)d=d.n,!d[c[e]]&&(d[c[e]]={n:{}}),d=d[c[e]];for(d.f=d.f||[],e=0,g=d.f.length;g>e;e++)if(d.f[e]==b)return h;return d.f.push(b),function(a){+a==+a&&(b.zIndex=+a)}},k.stop=function(){c=1},k.nt=function(a){return a?new RegExp("(?:\\.|\\/|^)"+a+"(?:\\.|\\/|$)").test(b):b},k.off=k.unbind=function(a,b){var c,d,h,i,k,l,m,n=a.split(f),o=[j];for(i=0,k=n.length;k>i;i++)for(l=0;l<o.length;l+=h.length-2){if(h=[l,1],c=o[l].n,n[i]!=g)c[n[i]]&&h.push(c[n[i]]);else for(d in c)c[e](d)&&h.push(c[d]);o.splice.apply(o,h)}for(i=0,k=o.length;k>i;i++)for(c=o[i];c.n;){if(b){if(c.f){for(l=0,m=c.f.length;m>l;l++)if(c.f[l]==b){c.f.splice(l,1);break}!c.f.length&&delete c.f}for(d in c.n)if(c.n[e](d)&&c.n[d].f){var p=c.n[d].f;for(l=0,m=p.length;m>l;l++)if(p[l]==b){p.splice(l,1);break}!p.length&&delete c.n[d].f}}else{delete c.f;for(d in c.n)c.n[e](d)&&c.n[d].f&&delete c.n[d].f}c=c.n}},k.once=function(a,b){var c=function(){var d=b.apply(this,arguments);return k.unbind(a,c),d};return k.on(a,c)},k.version=d,k.toString=function(){return"You are running Eve "+d},"undefined"!=typeof module&&module.exports?module.exports=k:"undefined"!=typeof define?define("eve",[],function(){return k}):a.eve=k}(this),window.eve||"function"!=typeof define||"function"!=typeof require||(window.eve=require("eve")),function(){function a(b){if(a.is(b,"function"))return s?b():eve.on("raphael.DOMload",b);if(a.is(b,T))return a._engine.create[B](a,b.splice(0,3+a.is(b[0],R))).add(b);var c=Array.prototype.slice.call(arguments,0);if(a.is(c[c.length-1],"function")){var d=c.pop();return s?d.call(a._engine.create[B](a,c)):eve.on("raphael.DOMload",function(){d.call(a._engine.create[B](a,c))})}return a._engine.create[B](a,arguments)}function b(a){if(Object(a)!==a)return a;var c=new a.constructor;for(var d in a)a[x](d)&&(c[d]=b(a[d]));return c}function c(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return a.push(a.splice(c,1)[0])}function d(a,b,d){function e(){var f=Array.prototype.slice.call(arguments,0),g=f.join("\u2400"),h=e.cache=e.cache||{},i=e.count=e.count||[];return h[x](g)?(c(i,g),d?d(h[g]):h[g]):(i.length>=1e3&&delete h[i.shift()],i.push(g),h[g]=a[B](b,f),d?d(h[g]):h[g])}return e}function e(){return this.hex}function f(a,b){for(var c=[],d=0,e=a.length;e-2*!b>d;d+=2){var f=[{x:+a[d-2],y:+a[d-1]},{x:+a[d],y:+a[d+1]},{x:+a[d+2],y:+a[d+3]},{x:+a[d+4],y:+a[d+5]}];b?d?e-4==d?f[3]={x:+a[0],y:+a[1]}:e-2==d&&(f[2]={x:+a[0],y:+a[1]},f[3]={x:+a[2],y:+a[3]}):f[0]={x:+a[e-2],y:+a[e-1]}:e-4==d?f[3]=f[2]:d||(f[0]={x:+a[d],y:+a[d+1]}),c.push(["C",(-f[0].x+6*f[1].x+f[2].x)/6,(-f[0].y+6*f[1].y+f[2].y)/6,(f[1].x+6*f[2].x-f[3].x)/6,(f[1].y+6*f[2].y-f[3].y)/6,f[2].x,f[2].y])}return c}function g(a,b,c,d,e){var f=-3*b+9*c-9*d+3*e,g=a*f+6*b-12*c+6*d;return a*g-3*b+3*c}function h(a,b,c,d,e,f,h,i,j){null==j&&(j=1),j=j>1?1:0>j?0:j;for(var k=j/2,l=12,m=[-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816],n=[.2491,.2491,.2335,.2335,.2032,.2032,.1601,.1601,.1069,.1069,.0472,.0472],o=0,p=0;l>p;p++){var q=k*m[p]+k,r=g(q,a,c,e,h),s=g(q,b,d,f,i),t=r*r+s*s;o+=n[p]*L.sqrt(t)}return k*o}function i(a,b,c,d,e,f,g,i,j){if(!(0>j||h(a,b,c,d,e,f,g,i)<j)){var k,l=1,m=l/2,n=l-m,o=.01;for(k=h(a,b,c,d,e,f,g,i,n);O(k-j)>o;)m/=2,n+=(j>k?1:-1)*m,k=h(a,b,c,d,e,f,g,i,n);return n}}function j(a,b,c,d,e,f,g,h){if(!(M(a,c)<N(e,g)||N(a,c)>M(e,g)||M(b,d)<N(f,h)||N(b,d)>M(f,h))){var i=(a*d-b*c)*(e-g)-(a-c)*(e*h-f*g),j=(a*d-b*c)*(f-h)-(b-d)*(e*h-f*g),k=(a-c)*(f-h)-(b-d)*(e-g);if(k){var l=i/k,m=j/k,n=+l.toFixed(2),o=+m.toFixed(2);if(!(n<+N(a,c).toFixed(2)||n>+M(a,c).toFixed(2)||n<+N(e,g).toFixed(2)||n>+M(e,g).toFixed(2)||o<+N(b,d).toFixed(2)||o>+M(b,d).toFixed(2)||o<+N(f,h).toFixed(2)||o>+M(f,h).toFixed(2)))return{x:l,y:m}}}}function k(b,c,d){var e=a.bezierBBox(b),f=a.bezierBBox(c);if(!a.isBBoxIntersect(e,f))return d?0:[];for(var g=h.apply(0,b),i=h.apply(0,c),k=~~(g/5),l=~~(i/5),m=[],n=[],o={},p=d?0:[],q=0;k+1>q;q++){var r=a.findDotsAtSegment.apply(a,b.concat(q/k));m.push({x:r.x,y:r.y,t:q/k})}for(q=0;l+1>q;q++)r=a.findDotsAtSegment.apply(a,c.concat(q/l)),n.push({x:r.x,y:r.y,t:q/l});for(q=0;k>q;q++)for(var s=0;l>s;s++){var t=m[q],u=m[q+1],v=n[s],w=n[s+1],x=O(u.x-t.x)<.001?"y":"x",y=O(w.x-v.x)<.001?"y":"x",z=j(t.x,t.y,u.x,u.y,v.x,v.y,w.x,w.y);if(z){if(o[z.x.toFixed(4)]==z.y.toFixed(4))continue;o[z.x.toFixed(4)]=z.y.toFixed(4);var A=t.t+O((z[x]-t[x])/(u[x]-t[x]))*(u.t-t.t),B=v.t+O((z[y]-v[y])/(w[y]-v[y]))*(w.t-v.t);A>=0&&1>=A&&B>=0&&1>=B&&(d?p++:p.push({x:z.x,y:z.y,t1:A,t2:B}))}}return p}function l(b,c,d){b=a._path2curve(b),c=a._path2curve(c);for(var e,f,g,h,i,j,l,m,n,o,p=d?0:[],q=0,r=b.length;r>q;q++){var s=b[q];if("M"==s[0])e=i=s[1],f=j=s[2];else{"C"==s[0]?(n=[e,f].concat(s.slice(1)),e=n[6],f=n[7]):(n=[e,f,e,f,i,j,i,j],e=i,f=j);for(var t=0,u=c.length;u>t;t++){var v=c[t];if("M"==v[0])g=l=v[1],h=m=v[2];else{"C"==v[0]?(o=[g,h].concat(v.slice(1)),g=o[6],h=o[7]):(o=[g,h,g,h,l,m,l,m],g=l,h=m);var w=k(n,o,d);if(d)p+=w;else{for(var x=0,y=w.length;y>x;x++)w[x].segment1=q,w[x].segment2=t,w[x].bez1=n,w[x].bez2=o;p=p.concat(w)}}}}}return p}function m(a,b,c,d,e,f){null!=a?(this.a=+a,this.b=+b,this.c=+c,this.d=+d,this.e=+e,this.f=+f):(this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0)}function n(){return this.x+F+this.y+F+this.width+" \xd7 "+this.height}function o(a,b,c,d,e,f){function g(a){return((l*a+k)*a+j)*a}function h(a,b){var c=i(a,b);return((o*c+n)*c+m)*c}function i(a,b){var c,d,e,f,h,i;for(e=a,i=0;8>i;i++){if(f=g(e)-a,O(f)<b)return e;if(h=(3*l*e+2*k)*e+j,O(h)<1e-6)break;e-=f/h}if(c=0,d=1,e=a,c>e)return c;if(e>d)return d;for(;d>c;){if(f=g(e),O(f-a)<b)return e;a>f?c=e:d=e,e=(d-c)/2+c}return e}var j=3*b,k=3*(d-b)-j,l=1-j-k,m=3*c,n=3*(e-c)-m,o=1-m-n;return h(a,1/(200*f))}function p(a,b){var c=[],d={};if(this.ms=b,this.times=1,a){for(var e in a)a[x](e)&&(d[Z(e)]=a[e],c.push(Z(e)));c.sort(jb)}this.anim=d,this.top=c[c.length-1],this.percents=c}function q(b,c,d,e,f,g){d=Z(d);var h,i,j,k,l,n,p=b.ms,q={},r={},s={};if(e)for(v=0,w=fc.length;w>v;v++){var t=fc[v];if(t.el.id==c.id&&t.anim==b){t.percent!=d?(fc.splice(v,1),j=1):i=t,c.attr(t.totalOrigin);break}}else e=+r;for(var v=0,w=b.percents.length;w>v;v++){if(b.percents[v]==d||b.percents[v]>e*b.top){d=b.percents[v],l=b.percents[v-1]||0,p=p/b.top*(d-l),k=b.percents[v+1],h=b.anim[d];break}e&&c.attr(b.anim[b.percents[v]])}if(h){if(i)i.initstatus=e,i.start=new Date-i.ms*e;else{for(var y in h)if(h[x](y)&&(bb[x](y)||c.paper.customAttributes[x](y)))switch(q[y]=c.attr(y),null==q[y]&&(q[y]=ab[y]),r[y]=h[y],bb[y]){case R:s[y]=(r[y]-q[y])/p;break;case"colour":q[y]=a.getRGB(q[y]);var z=a.getRGB(r[y]);s[y]={r:(z.r-q[y].r)/p,g:(z.g-q[y].g)/p,b:(z.b-q[y].b)/p};break;case"path":var A=Ib(q[y],r[y]),B=A[1];for(q[y]=A[0],s[y]=[],v=0,w=q[y].length;w>v;v++){s[y][v]=[0];for(var D=1,E=q[y][v].length;E>D;D++)s[y][v][D]=(B[v][D]-q[y][v][D])/p}break;case"transform":var F=c._,I=Nb(F[y],r[y]);if(I)for(q[y]=I.from,r[y]=I.to,s[y]=[],s[y].real=!0,v=0,w=q[y].length;w>v;v++)for(s[y][v]=[q[y][v][0]],D=1,E=q[y][v].length;E>D;D++)s[y][v][D]=(r[y][v][D]-q[y][v][D])/p;else{var J=c.matrix||new m,K={_:{transform:F.transform},getBBox:function(){return c.getBBox(1)}};q[y]=[J.a,J.b,J.c,J.d,J.e,J.f],Lb(K,r[y]),r[y]=K._.transform,s[y]=[(K.matrix.a-J.a)/p,(K.matrix.b-J.b)/p,(K.matrix.c-J.c)/p,(K.matrix.d-J.d)/p,(K.matrix.e-J.e)/p,(K.matrix.f-J.f)/p] }break;case"csv":var L=G(h[y])[H](u),M=G(q[y])[H](u);if("clip-rect"==y)for(q[y]=M,s[y]=[],v=M.length;v--;)s[y][v]=(L[v]-q[y][v])/p;r[y]=L;break;default:for(L=[][C](h[y]),M=[][C](q[y]),s[y]=[],v=c.paper.customAttributes[y].length;v--;)s[y][v]=((L[v]||0)-(M[v]||0))/p}var N=h.easing,O=a.easing_formulas[N];if(!O)if(O=G(N).match(X),O&&5==O.length){var P=O;O=function(a){return o(a,+P[1],+P[2],+P[3],+P[4],p)}}else O=lb;if(n=h.start||b.start||+new Date,t={anim:b,percent:d,timestamp:n,start:n+(b.del||0),status:0,initstatus:e||0,stop:!1,ms:p,easing:O,from:q,diff:s,to:r,el:c,callback:h.callback,prev:l,next:k,repeat:g||b.times,origin:c.attr(),totalOrigin:f},fc.push(t),e&&!i&&!j&&(t.stop=!0,t.start=new Date-p*e,1==fc.length))return hc();j&&(t.start=new Date-t.ms*e),1==fc.length&&gc(hc)}eve("raphael.anim.start."+c.id,c,b)}}function r(a){for(var b=0;b<fc.length;b++)fc[b].el.paper==a&&fc.splice(b--,1)}a.version="2.1.0",a.eve=eve;var s,t,u=/[, ]+/,v={circle:1,rect:1,path:1,ellipse:1,text:1,image:1},w=/\{(\d+)\}/g,x="hasOwnProperty",y={doc:document,win:window},z={was:Object.prototype[x].call(y.win,"Raphael"),is:y.win.Raphael},A=function(){this.ca=this.customAttributes={}},B="apply",C="concat",D="createTouch"in y.doc,E="",F=" ",G=String,H="split",I="click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[H](F),J={mousedown:"touchstart",mousemove:"touchmove",mouseup:"touchend"},K=G.prototype.toLowerCase,L=Math,M=L.max,N=L.min,O=L.abs,P=L.pow,Q=L.PI,R="number",S="string",T="array",U=Object.prototype.toString,V=(a._ISURL=/^url\(['"]?([^\)]+?)['"]?\)$/i,/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i),W={NaN:1,Infinity:1,"-Infinity":1},X=/^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,Y=L.round,Z=parseFloat,$=parseInt,_=G.prototype.toUpperCase,ab=a._availableAttrs={"arrow-end":"none","arrow-start":"none",blur:0,"clip-rect":"0 0 1e9 1e9",cursor:"default",cx:0,cy:0,fill:"#fff","fill-opacity":1,font:'10px "Arial"',"font-family":'"Arial"',"font-size":"10","font-style":"normal","font-weight":400,gradient:0,height:0,href:"http://raphaeljs.com/","letter-spacing":0,opacity:1,path:"M0,0",r:0,rx:0,ry:0,src:"",stroke:"#000","stroke-dasharray":"","stroke-linecap":"butt","stroke-linejoin":"butt","stroke-miterlimit":0,"stroke-opacity":1,"stroke-width":1,target:"_blank","text-anchor":"middle",title:"Raphael",transform:"",width:0,x:0,y:0},bb=a._availableAnimAttrs={blur:R,"clip-rect":"csv",cx:R,cy:R,fill:"colour","fill-opacity":R,"font-size":R,height:R,opacity:R,path:"path",r:R,rx:R,ry:R,stroke:"colour","stroke-opacity":R,"stroke-width":R,transform:"transform",width:R,x:R,y:R},cb=/[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/,db={hs:1,rg:1},eb=/,?([achlmqrstvxz]),?/gi,fb=/([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/gi,gb=/([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/gi,hb=/(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/gi,ib=(a._radial_gradient=/^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/,{}),jb=function(a,b){return Z(a)-Z(b)},kb=function(){},lb=function(a){return a},mb=a._rectPath=function(a,b,c,d,e){return e?[["M",a+e,b],["l",c-2*e,0],["a",e,e,0,0,1,e,e],["l",0,d-2*e],["a",e,e,0,0,1,-e,e],["l",2*e-c,0],["a",e,e,0,0,1,-e,-e],["l",0,2*e-d],["a",e,e,0,0,1,e,-e],["z"]]:[["M",a,b],["l",c,0],["l",0,d],["l",-c,0],["z"]]},nb=function(a,b,c,d){return null==d&&(d=c),[["M",a,b],["m",0,-d],["a",c,d,0,1,1,0,2*d],["a",c,d,0,1,1,0,-2*d],["z"]]},ob=a._getPath={path:function(a){return a.attr("path")},circle:function(a){var b=a.attrs;return nb(b.cx,b.cy,b.r)},ellipse:function(a){var b=a.attrs;return nb(b.cx,b.cy,b.rx,b.ry)},rect:function(a){var b=a.attrs;return mb(b.x,b.y,b.width,b.height,b.r)},image:function(a){var b=a.attrs;return mb(b.x,b.y,b.width,b.height)},text:function(a){var b=a._getBBox();return mb(b.x,b.y,b.width,b.height)}},pb=a.mapPath=function(a,b){if(!b)return a;var c,d,e,f,g,h,i;for(a=Ib(a),e=0,g=a.length;g>e;e++)for(i=a[e],f=1,h=i.length;h>f;f+=2)c=b.x(i[f],i[f+1]),d=b.y(i[f],i[f+1]),i[f]=c,i[f+1]=d;return a};if(a._g=y,a.type=y.win.SVGAngle||y.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML","VML"==a.type){var qb,rb=y.doc.createElement("div");if(rb.innerHTML='<v:shape adj="1"/>',qb=rb.firstChild,qb.style.behavior="url(#default#VML)",!qb||"object"!=typeof qb.adj)return a.type=E;rb=null}a.svg=!(a.vml="VML"==a.type),a._Paper=A,a.fn=t=A.prototype=a.prototype,a._id=0,a._oid=0,a.is=function(a,b){return b=K.call(b),"finite"==b?!W[x](+a):"array"==b?a instanceof Array:"null"==b&&null===a||b==typeof a&&null!==a||"object"==b&&a===Object(a)||"array"==b&&Array.isArray&&Array.isArray(a)||U.call(a).slice(8,-1).toLowerCase()==b},a.angle=function(b,c,d,e,f,g){if(null==f){var h=b-d,i=c-e;return h||i?(180+180*L.atan2(-i,-h)/Q+360)%360:0}return a.angle(b,c,f,g)-a.angle(d,e,f,g)},a.rad=function(a){return a%360*Q/180},a.deg=function(a){return 180*a/Q%360},a.snapTo=function(b,c,d){if(d=a.is(d,"finite")?d:10,a.is(b,T)){for(var e=b.length;e--;)if(O(b[e]-c)<=d)return b[e]}else{b=+b;var f=c%b;if(d>f)return c-f;if(f>b-d)return c-f+b}return c};a.createUUID=function(a,b){return function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(a,b).toUpperCase()}}(/[xy]/g,function(a){var b=16*L.random()|0,c="x"==a?b:3&b|8;return c.toString(16)});a.setWindow=function(b){eve("raphael.setWindow",a,y.win,b),y.win=b,y.doc=y.win.document,a._engine.initWin&&a._engine.initWin(y.win)};var sb=function(b){if(a.vml){var c,e=/^\s+|\s+$/g;try{var f=new ActiveXObject("htmlfile");f.write("<body>"),f.close(),c=f.body}catch(g){c=createPopup().document.body}var h=c.createTextRange();sb=d(function(a){try{c.style.color=G(a).replace(e,E);var b=h.queryCommandValue("ForeColor");return b=(255&b)<<16|65280&b|(16711680&b)>>>16,"#"+("000000"+b.toString(16)).slice(-6)}catch(d){return"none"}})}else{var i=y.doc.createElement("i");i.title="Rapha\xebl Colour Picker",i.style.display="none",y.doc.body.appendChild(i),sb=d(function(a){return i.style.color=a,y.doc.defaultView.getComputedStyle(i,E).getPropertyValue("color")})}return sb(b)},tb=function(){return"hsb("+[this.h,this.s,this.b]+")"},ub=function(){return"hsl("+[this.h,this.s,this.l]+")"},vb=function(){return this.hex},wb=function(b,c,d){if(null==c&&a.is(b,"object")&&"r"in b&&"g"in b&&"b"in b&&(d=b.b,c=b.g,b=b.r),null==c&&a.is(b,S)){var e=a.getRGB(b);b=e.r,c=e.g,d=e.b}return(b>1||c>1||d>1)&&(b/=255,c/=255,d/=255),[b,c,d]},xb=function(b,c,d,e){b*=255,c*=255,d*=255;var f={r:b,g:c,b:d,hex:a.rgb(b,c,d),toString:vb};return a.is(e,"finite")&&(f.opacity=e),f};a.color=function(b){var c;return a.is(b,"object")&&"h"in b&&"s"in b&&"b"in b?(c=a.hsb2rgb(b),b.r=c.r,b.g=c.g,b.b=c.b,b.hex=c.hex):a.is(b,"object")&&"h"in b&&"s"in b&&"l"in b?(c=a.hsl2rgb(b),b.r=c.r,b.g=c.g,b.b=c.b,b.hex=c.hex):(a.is(b,"string")&&(b=a.getRGB(b)),a.is(b,"object")&&"r"in b&&"g"in b&&"b"in b?(c=a.rgb2hsl(b),b.h=c.h,b.s=c.s,b.l=c.l,c=a.rgb2hsb(b),b.v=c.b):(b={hex:"none"},b.r=b.g=b.b=b.h=b.s=b.v=b.l=-1)),b.toString=vb,b},a.hsb2rgb=function(a,b,c,d){this.is(a,"object")&&"h"in a&&"s"in a&&"b"in a&&(c=a.b,b=a.s,a=a.h,d=a.o),a*=360;var e,f,g,h,i;return a=a%360/60,i=c*b,h=i*(1-O(a%2-1)),e=f=g=c-i,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a],xb(e,f,g,d)},a.hsl2rgb=function(a,b,c,d){this.is(a,"object")&&"h"in a&&"s"in a&&"l"in a&&(c=a.l,b=a.s,a=a.h),(a>1||b>1||c>1)&&(a/=360,b/=100,c/=100),a*=360;var e,f,g,h,i;return a=a%360/60,i=2*b*(.5>c?c:1-c),h=i*(1-O(a%2-1)),e=f=g=c-i/2,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a],xb(e,f,g,d)},a.rgb2hsb=function(a,b,c){c=wb(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g;return f=M(a,b,c),g=f-N(a,b,c),d=0==g?null:f==a?(b-c)/g:f==b?(c-a)/g+2:(a-b)/g+4,d=(d+360)%6*60/360,e=0==g?0:g/f,{h:d,s:e,b:f,toString:tb}},a.rgb2hsl=function(a,b,c){c=wb(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g,h,i;return g=M(a,b,c),h=N(a,b,c),i=g-h,d=0==i?null:g==a?(b-c)/i:g==b?(c-a)/i+2:(a-b)/i+4,d=(d+360)%6*60/360,f=(g+h)/2,e=0==i?0:.5>f?i/(2*f):i/(2-2*f),{h:d,s:e,l:f,toString:ub}},a._path2string=function(){return this.join(",").replace(eb,"$1")};a._preload=function(a,b){var c=y.doc.createElement("img");c.style.cssText="position:absolute;left:-9999em;top:-9999em",c.onload=function(){b.call(this),this.onload=null,y.doc.body.removeChild(this)},c.onerror=function(){y.doc.body.removeChild(this)},y.doc.body.appendChild(c),c.src=a};a.getRGB=d(function(b){if(!b||(b=G(b)).indexOf("-")+1)return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:e};if("none"==b)return{r:-1,g:-1,b:-1,hex:"none",toString:e};!(db[x](b.toLowerCase().substring(0,2))||"#"==b.charAt())&&(b=sb(b));var c,d,f,g,h,i,j=b.match(V);return j?(j[2]&&(f=$(j[2].substring(5),16),d=$(j[2].substring(3,5),16),c=$(j[2].substring(1,3),16)),j[3]&&(f=$((h=j[3].charAt(3))+h,16),d=$((h=j[3].charAt(2))+h,16),c=$((h=j[3].charAt(1))+h,16)),j[4]&&(i=j[4][H](cb),c=Z(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=Z(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),f=Z(i[2]),"%"==i[2].slice(-1)&&(f*=2.55),"rgba"==j[1].toLowerCase().slice(0,4)&&(g=Z(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100)),j[5]?(i=j[5][H](cb),c=Z(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=Z(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),f=Z(i[2]),"%"==i[2].slice(-1)&&(f*=2.55),("deg"==i[0].slice(-3)||"\xb0"==i[0].slice(-1))&&(c/=360),"hsba"==j[1].toLowerCase().slice(0,4)&&(g=Z(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100),a.hsb2rgb(c,d,f,g)):j[6]?(i=j[6][H](cb),c=Z(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=Z(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),f=Z(i[2]),"%"==i[2].slice(-1)&&(f*=2.55),("deg"==i[0].slice(-3)||"\xb0"==i[0].slice(-1))&&(c/=360),"hsla"==j[1].toLowerCase().slice(0,4)&&(g=Z(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100),a.hsl2rgb(c,d,f,g)):(j={r:c,g:d,b:f,toString:e},j.hex="#"+(16777216|f|d<<8|c<<16).toString(16).slice(1),a.is(g,"finite")&&(j.opacity=g),j)):{r:-1,g:-1,b:-1,hex:"none",error:1,toString:e}},a),a.hsb=d(function(b,c,d){return a.hsb2rgb(b,c,d).hex}),a.hsl=d(function(b,c,d){return a.hsl2rgb(b,c,d).hex}),a.rgb=d(function(a,b,c){return"#"+(16777216|c|b<<8|a<<16).toString(16).slice(1)}),a.getColor=function(a){var b=this.getColor.start=this.getColor.start||{h:0,s:1,b:a||.75},c=this.hsb2rgb(b.h,b.s,b.b);return b.h+=.075,b.h>1&&(b.h=0,b.s-=.2,b.s<=0&&(this.getColor.start={h:0,s:1,b:b.b})),c.hex},a.getColor.reset=function(){delete this.start},a.parsePathString=function(b){if(!b)return null;var c=yb(b);if(c.arr)return Ab(c.arr);var d={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},e=[];return a.is(b,T)&&a.is(b[0],T)&&(e=Ab(b)),e.length||G(b).replace(fb,function(a,b,c){var f=[],g=b.toLowerCase();if(c.replace(hb,function(a,b){b&&f.push(+b)}),"m"==g&&f.length>2&&(e.push([b][C](f.splice(0,2))),g="l",b="m"==b?"l":"L"),"r"==g)e.push([b][C](f));else for(;f.length>=d[g]&&(e.push([b][C](f.splice(0,d[g]))),d[g]););}),e.toString=a._path2string,c.arr=Ab(e),e},a.parseTransformString=d(function(b){if(!b)return null;var c=[];return a.is(b,T)&&a.is(b[0],T)&&(c=Ab(b)),c.length||G(b).replace(gb,function(a,b,d){{var e=[];K.call(b)}d.replace(hb,function(a,b){b&&e.push(+b)}),c.push([b][C](e))}),c.toString=a._path2string,c});var yb=function(a){var b=yb.ps=yb.ps||{};return b[a]?b[a].sleep=100:b[a]={sleep:100},setTimeout(function(){for(var c in b)b[x](c)&&c!=a&&(b[c].sleep--,!b[c].sleep&&delete b[c])}),b[a]};a.findDotsAtSegment=function(a,b,c,d,e,f,g,h,i){var j=1-i,k=P(j,3),l=P(j,2),m=i*i,n=m*i,o=k*a+3*l*i*c+3*j*i*i*e+n*g,p=k*b+3*l*i*d+3*j*i*i*f+n*h,q=a+2*i*(c-a)+m*(e-2*c+a),r=b+2*i*(d-b)+m*(f-2*d+b),s=c+2*i*(e-c)+m*(g-2*e+c),t=d+2*i*(f-d)+m*(h-2*f+d),u=j*a+i*c,v=j*b+i*d,w=j*e+i*g,x=j*f+i*h,y=90-180*L.atan2(q-s,r-t)/Q;return(q>s||t>r)&&(y+=180),{x:o,y:p,m:{x:q,y:r},n:{x:s,y:t},start:{x:u,y:v},end:{x:w,y:x},alpha:y}},a.bezierBBox=function(b,c,d,e,f,g,h,i){a.is(b,"array")||(b=[b,c,d,e,f,g,h,i]);var j=Hb.apply(null,b);return{x:j.min.x,y:j.min.y,x2:j.max.x,y2:j.max.y,width:j.max.x-j.min.x,height:j.max.y-j.min.y}},a.isPointInsideBBox=function(a,b,c){return b>=a.x&&b<=a.x2&&c>=a.y&&c<=a.y2},a.isBBoxIntersect=function(b,c){var d=a.isPointInsideBBox;return d(c,b.x,b.y)||d(c,b.x2,b.y)||d(c,b.x,b.y2)||d(c,b.x2,b.y2)||d(b,c.x,c.y)||d(b,c.x2,c.y)||d(b,c.x,c.y2)||d(b,c.x2,c.y2)||(b.x<c.x2&&b.x>c.x||c.x<b.x2&&c.x>b.x)&&(b.y<c.y2&&b.y>c.y||c.y<b.y2&&c.y>b.y)},a.pathIntersection=function(a,b){return l(a,b)},a.pathIntersectionNumber=function(a,b){return l(a,b,1)},a.isPointInsidePath=function(b,c,d){var e=a.pathBBox(b);return a.isPointInsideBBox(e,c,d)&&l(b,[["M",c,d],["H",e.x2+10]],1)%2==1},a._removedFactory=function(a){return function(){eve("raphael.log",null,"Rapha\xebl: you are calling to method \u201c"+a+"\u201d of removed object",a)}};var zb=a.pathBBox=function(a){var c=yb(a);if(c.bbox)return c.bbox;if(!a)return{x:0,y:0,width:0,height:0,x2:0,y2:0};a=Ib(a);for(var d,e=0,f=0,g=[],h=[],i=0,j=a.length;j>i;i++)if(d=a[i],"M"==d[0])e=d[1],f=d[2],g.push(e),h.push(f);else{var k=Hb(e,f,d[1],d[2],d[3],d[4],d[5],d[6]);g=g[C](k.min.x,k.max.x),h=h[C](k.min.y,k.max.y),e=d[5],f=d[6]}var l=N[B](0,g),m=N[B](0,h),n=M[B](0,g),o=M[B](0,h),p={x:l,y:m,x2:n,y2:o,width:n-l,height:o-m};return c.bbox=b(p),p},Ab=function(c){var d=b(c);return d.toString=a._path2string,d},Bb=a._pathToRelative=function(b){var c=yb(b);if(c.rel)return Ab(c.rel);a.is(b,T)&&a.is(b&&b[0],T)||(b=a.parsePathString(b));var d=[],e=0,f=0,g=0,h=0,i=0;"M"==b[0][0]&&(e=b[0][1],f=b[0][2],g=e,h=f,i++,d.push(["M",e,f]));for(var j=i,k=b.length;k>j;j++){var l=d[j]=[],m=b[j];if(m[0]!=K.call(m[0]))switch(l[0]=K.call(m[0]),l[0]){case"a":l[1]=m[1],l[2]=m[2],l[3]=m[3],l[4]=m[4],l[5]=m[5],l[6]=+(m[6]-e).toFixed(3),l[7]=+(m[7]-f).toFixed(3);break;case"v":l[1]=+(m[1]-f).toFixed(3);break;case"m":g=m[1],h=m[2];default:for(var n=1,o=m.length;o>n;n++)l[n]=+(m[n]-(n%2?e:f)).toFixed(3)}else{l=d[j]=[],"m"==m[0]&&(g=m[1]+e,h=m[2]+f);for(var p=0,q=m.length;q>p;p++)d[j][p]=m[p]}var r=d[j].length;switch(d[j][0]){case"z":e=g,f=h;break;case"h":e+=+d[j][r-1];break;case"v":f+=+d[j][r-1];break;default:e+=+d[j][r-2],f+=+d[j][r-1]}}return d.toString=a._path2string,c.rel=Ab(d),d},Cb=a._pathToAbsolute=function(b){var c=yb(b);if(c.abs)return Ab(c.abs);if(a.is(b,T)&&a.is(b&&b[0],T)||(b=a.parsePathString(b)),!b||!b.length)return[["M",0,0]];var d=[],e=0,g=0,h=0,i=0,j=0;"M"==b[0][0]&&(e=+b[0][1],g=+b[0][2],h=e,i=g,j++,d[0]=["M",e,g]);for(var k,l,m=3==b.length&&"M"==b[0][0]&&"R"==b[1][0].toUpperCase()&&"Z"==b[2][0].toUpperCase(),n=j,o=b.length;o>n;n++){if(d.push(k=[]),l=b[n],l[0]!=_.call(l[0]))switch(k[0]=_.call(l[0]),k[0]){case"A":k[1]=l[1],k[2]=l[2],k[3]=l[3],k[4]=l[4],k[5]=l[5],k[6]=+(l[6]+e),k[7]=+(l[7]+g);break;case"V":k[1]=+l[1]+g;break;case"H":k[1]=+l[1]+e;break;case"R":for(var p=[e,g][C](l.slice(1)),q=2,r=p.length;r>q;q++)p[q]=+p[q]+e,p[++q]=+p[q]+g;d.pop(),d=d[C](f(p,m));break;case"M":h=+l[1]+e,i=+l[2]+g;default:for(q=1,r=l.length;r>q;q++)k[q]=+l[q]+(q%2?e:g)}else if("R"==l[0])p=[e,g][C](l.slice(1)),d.pop(),d=d[C](f(p,m)),k=["R"][C](l.slice(-2));else for(var s=0,t=l.length;t>s;s++)k[s]=l[s];switch(k[0]){case"Z":e=h,g=i;break;case"H":e=k[1];break;case"V":g=k[1];break;case"M":h=k[k.length-2],i=k[k.length-1];default:e=k[k.length-2],g=k[k.length-1]}}return d.toString=a._path2string,c.abs=Ab(d),d},Db=function(a,b,c,d){return[a,b,c,d,c,d]},Eb=function(a,b,c,d,e,f){var g=1/3,h=2/3;return[g*a+h*c,g*b+h*d,g*e+h*c,g*f+h*d,e,f]},Fb=function(a,b,c,e,f,g,h,i,j,k){var l,m=120*Q/180,n=Q/180*(+f||0),o=[],p=d(function(a,b,c){var d=a*L.cos(c)-b*L.sin(c),e=a*L.sin(c)+b*L.cos(c);return{x:d,y:e}});if(k)y=k[0],z=k[1],w=k[2],x=k[3];else{l=p(a,b,-n),a=l.x,b=l.y,l=p(i,j,-n),i=l.x,j=l.y;var q=(L.cos(Q/180*f),L.sin(Q/180*f),(a-i)/2),r=(b-j)/2,s=q*q/(c*c)+r*r/(e*e);s>1&&(s=L.sqrt(s),c=s*c,e=s*e);var t=c*c,u=e*e,v=(g==h?-1:1)*L.sqrt(O((t*u-t*r*r-u*q*q)/(t*r*r+u*q*q))),w=v*c*r/e+(a+i)/2,x=v*-e*q/c+(b+j)/2,y=L.asin(((b-x)/e).toFixed(9)),z=L.asin(((j-x)/e).toFixed(9));y=w>a?Q-y:y,z=w>i?Q-z:z,0>y&&(y=2*Q+y),0>z&&(z=2*Q+z),h&&y>z&&(y-=2*Q),!h&&z>y&&(z-=2*Q)}var A=z-y;if(O(A)>m){var B=z,D=i,E=j;z=y+m*(h&&z>y?1:-1),i=w+c*L.cos(z),j=x+e*L.sin(z),o=Fb(i,j,c,e,f,0,h,D,E,[z,B,w,x])}A=z-y;var F=L.cos(y),G=L.sin(y),I=L.cos(z),J=L.sin(z),K=L.tan(A/4),M=4/3*c*K,N=4/3*e*K,P=[a,b],R=[a+M*G,b-N*F],S=[i+M*J,j-N*I],T=[i,j];if(R[0]=2*P[0]-R[0],R[1]=2*P[1]-R[1],k)return[R,S,T][C](o);o=[R,S,T][C](o).join()[H](",");for(var U=[],V=0,W=o.length;W>V;V++)U[V]=V%2?p(o[V-1],o[V],n).y:p(o[V],o[V+1],n).x;return U},Gb=function(a,b,c,d,e,f,g,h,i){var j=1-i;return{x:P(j,3)*a+3*P(j,2)*i*c+3*j*i*i*e+P(i,3)*g,y:P(j,3)*b+3*P(j,2)*i*d+3*j*i*i*f+P(i,3)*h}},Hb=d(function(a,b,c,d,e,f,g,h){var i,j=e-2*c+a-(g-2*e+c),k=2*(c-a)-2*(e-c),l=a-c,m=(-k+L.sqrt(k*k-4*j*l))/2/j,n=(-k-L.sqrt(k*k-4*j*l))/2/j,o=[b,h],p=[a,g];return O(m)>"1e12"&&(m=.5),O(n)>"1e12"&&(n=.5),m>0&&1>m&&(i=Gb(a,b,c,d,e,f,g,h,m),p.push(i.x),o.push(i.y)),n>0&&1>n&&(i=Gb(a,b,c,d,e,f,g,h,n),p.push(i.x),o.push(i.y)),j=f-2*d+b-(h-2*f+d),k=2*(d-b)-2*(f-d),l=b-d,m=(-k+L.sqrt(k*k-4*j*l))/2/j,n=(-k-L.sqrt(k*k-4*j*l))/2/j,O(m)>"1e12"&&(m=.5),O(n)>"1e12"&&(n=.5),m>0&&1>m&&(i=Gb(a,b,c,d,e,f,g,h,m),p.push(i.x),o.push(i.y)),n>0&&1>n&&(i=Gb(a,b,c,d,e,f,g,h,n),p.push(i.x),o.push(i.y)),{min:{x:N[B](0,p),y:N[B](0,o)},max:{x:M[B](0,p),y:M[B](0,o)}}}),Ib=a._path2curve=d(function(a,b){var c=!b&&yb(a);if(!b&&c.curve)return Ab(c.curve);for(var d=Cb(a),e=b&&Cb(b),f={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},g={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},h=(function(a,b){var c,d;if(!a)return["C",b.x,b.y,b.x,b.y,b.x,b.y];switch(!(a[0]in{T:1,Q:1})&&(b.qx=b.qy=null),a[0]){case"M":b.X=a[1],b.Y=a[2];break;case"A":a=["C"][C](Fb[B](0,[b.x,b.y][C](a.slice(1))));break;case"S":c=b.x+(b.x-(b.bx||b.x)),d=b.y+(b.y-(b.by||b.y)),a=["C",c,d][C](a.slice(1));break;case"T":b.qx=b.x+(b.x-(b.qx||b.x)),b.qy=b.y+(b.y-(b.qy||b.y)),a=["C"][C](Eb(b.x,b.y,b.qx,b.qy,a[1],a[2]));break;case"Q":b.qx=a[1],b.qy=a[2],a=["C"][C](Eb(b.x,b.y,a[1],a[2],a[3],a[4]));break;case"L":a=["C"][C](Db(b.x,b.y,a[1],a[2]));break;case"H":a=["C"][C](Db(b.x,b.y,a[1],b.y));break;case"V":a=["C"][C](Db(b.x,b.y,b.x,a[1]));break;case"Z":a=["C"][C](Db(b.x,b.y,b.X,b.Y))}return a}),i=function(a,b){if(a[b].length>7){a[b].shift();for(var c=a[b];c.length;)a.splice(b++,0,["C"][C](c.splice(0,6)));a.splice(b,1),l=M(d.length,e&&e.length||0)}},j=function(a,b,c,f,g){a&&b&&"M"==a[g][0]&&"M"!=b[g][0]&&(b.splice(g,0,["M",f.x,f.y]),c.bx=0,c.by=0,c.x=a[g][1],c.y=a[g][2],l=M(d.length,e&&e.length||0))},k=0,l=M(d.length,e&&e.length||0);l>k;k++){d[k]=h(d[k],f),i(d,k),e&&(e[k]=h(e[k],g)),e&&i(e,k),j(d,e,f,g,k),j(e,d,g,f,k);var m=d[k],n=e&&e[k],o=m.length,p=e&&n.length;f.x=m[o-2],f.y=m[o-1],f.bx=Z(m[o-4])||f.x,f.by=Z(m[o-3])||f.y,g.bx=e&&(Z(n[p-4])||g.x),g.by=e&&(Z(n[p-3])||g.y),g.x=e&&n[p-2],g.y=e&&n[p-1]}return e||(c.curve=Ab(d)),e?[d,e]:d},null,Ab),Jb=(a._parseDots=d(function(b){for(var c=[],d=0,e=b.length;e>d;d++){var f={},g=b[d].match(/^([^:]*):?([\d\.]*)/);if(f.color=a.getRGB(g[1]),f.color.error)return null;f.color=f.color.hex,g[2]&&(f.offset=g[2]+"%"),c.push(f)}for(d=1,e=c.length-1;e>d;d++)if(!c[d].offset){for(var h=Z(c[d-1].offset||0),i=0,j=d+1;e>j;j++)if(c[j].offset){i=c[j].offset;break}i||(i=100,j=e),i=Z(i);for(var k=(i-h)/(j-d+1);j>d;d++)h+=k,c[d].offset=h+"%"}return c}),a._tear=function(a,b){a==b.top&&(b.top=a.prev),a==b.bottom&&(b.bottom=a.next),a.next&&(a.next.prev=a.prev),a.prev&&(a.prev.next=a.next)}),Kb=(a._tofront=function(a,b){b.top!==a&&(Jb(a,b),a.next=null,a.prev=b.top,b.top.next=a,b.top=a)},a._toback=function(a,b){b.bottom!==a&&(Jb(a,b),a.next=b.bottom,a.prev=null,b.bottom.prev=a,b.bottom=a)},a._insertafter=function(a,b,c){Jb(a,c),b==c.top&&(c.top=a),b.next&&(b.next.prev=a),a.next=b.next,a.prev=b,b.next=a},a._insertbefore=function(a,b,c){Jb(a,c),b==c.bottom&&(c.bottom=a),b.prev&&(b.prev.next=a),a.prev=b.prev,b.prev=a,a.next=b},a.toMatrix=function(a,b){var c=zb(a),d={_:{transform:E},getBBox:function(){return c}};return Lb(d,b),d.matrix}),Lb=(a.transformPath=function(a,b){return pb(a,Kb(a,b))},a._extractTransform=function(b,c){if(null==c)return b._.transform;c=G(c).replace(/\.{3}|\u2026/g,b._.transform||E);var d=a.parseTransformString(c),e=0,f=0,g=0,h=1,i=1,j=b._,k=new m;if(j.transform=d||[],d)for(var l=0,n=d.length;n>l;l++){var o,p,q,r,s,t=d[l],u=t.length,v=G(t[0]).toLowerCase(),w=t[0]!=v,x=w?k.invert():0;"t"==v&&3==u?w?(o=x.x(0,0),p=x.y(0,0),q=x.x(t[1],t[2]),r=x.y(t[1],t[2]),k.translate(q-o,r-p)):k.translate(t[1],t[2]):"r"==v?2==u?(s=s||b.getBBox(1),k.rotate(t[1],s.x+s.width/2,s.y+s.height/2),e+=t[1]):4==u&&(w?(q=x.x(t[2],t[3]),r=x.y(t[2],t[3]),k.rotate(t[1],q,r)):k.rotate(t[1],t[2],t[3]),e+=t[1]):"s"==v?2==u||3==u?(s=s||b.getBBox(1),k.scale(t[1],t[u-1],s.x+s.width/2,s.y+s.height/2),h*=t[1],i*=t[u-1]):5==u&&(w?(q=x.x(t[3],t[4]),r=x.y(t[3],t[4]),k.scale(t[1],t[2],q,r)):k.scale(t[1],t[2],t[3],t[4]),h*=t[1],i*=t[2]):"m"==v&&7==u&&k.add(t[1],t[2],t[3],t[4],t[5],t[6]),j.dirtyT=1,b.matrix=k}b.matrix=k,j.sx=h,j.sy=i,j.deg=e,j.dx=f=k.e,j.dy=g=k.f,1==h&&1==i&&!e&&j.bbox?(j.bbox.x+=+f,j.bbox.y+=+g):j.dirtyT=1}),Mb=function(a){var b=a[0];switch(b.toLowerCase()){case"t":return[b,0,0];case"m":return[b,1,0,0,1,0,0];case"r":return 4==a.length?[b,0,a[2],a[3]]:[b,0];case"s":return 5==a.length?[b,1,1,a[3],a[4]]:3==a.length?[b,1,1]:[b,1]}},Nb=a._equaliseTransform=function(b,c){c=G(c).replace(/\.{3}|\u2026/g,b),b=a.parseTransformString(b)||[],c=a.parseTransformString(c)||[];for(var d,e,f,g,h=M(b.length,c.length),i=[],j=[],k=0;h>k;k++){if(f=b[k]||Mb(c[k]),g=c[k]||Mb(f),f[0]!=g[0]||"r"==f[0].toLowerCase()&&(f[2]!=g[2]||f[3]!=g[3])||"s"==f[0].toLowerCase()&&(f[3]!=g[3]||f[4]!=g[4]))return;for(i[k]=[],j[k]=[],d=0,e=M(f.length,g.length);e>d;d++)d in f&&(i[k][d]=f[d]),d in g&&(j[k][d]=g[d])}return{from:i,to:j}};a._getContainer=function(b,c,d,e){var f;return f=null!=e||a.is(b,"object")?b:y.doc.getElementById(b),null!=f?f.tagName?null==c?{container:f,width:f.style.pixelWidth||f.offsetWidth,height:f.style.pixelHeight||f.offsetHeight}:{container:f,width:c,height:d}:{container:1,x:b,y:c,width:d,height:e}:void 0},a.pathToRelative=Bb,a._engine={},a.path2curve=Ib,a.matrix=function(a,b,c,d,e,f){return new m(a,b,c,d,e,f)},function(b){function c(a){return a[0]*a[0]+a[1]*a[1]}function d(a){var b=L.sqrt(c(a));a[0]&&(a[0]/=b),a[1]&&(a[1]/=b)}b.add=function(a,b,c,d,e,f){var g,h,i,j,k=[[],[],[]],l=[[this.a,this.c,this.e],[this.b,this.d,this.f],[0,0,1]],n=[[a,c,e],[b,d,f],[0,0,1]];for(a&&a instanceof m&&(n=[[a.a,a.c,a.e],[a.b,a.d,a.f],[0,0,1]]),g=0;3>g;g++)for(h=0;3>h;h++){for(j=0,i=0;3>i;i++)j+=l[g][i]*n[i][h];k[g][h]=j}this.a=k[0][0],this.b=k[1][0],this.c=k[0][1],this.d=k[1][1],this.e=k[0][2],this.f=k[1][2]},b.invert=function(){var a=this,b=a.a*a.d-a.b*a.c;return new m(a.d/b,-a.b/b,-a.c/b,a.a/b,(a.c*a.f-a.d*a.e)/b,(a.b*a.e-a.a*a.f)/b)},b.clone=function(){return new m(this.a,this.b,this.c,this.d,this.e,this.f)},b.translate=function(a,b){this.add(1,0,0,1,a,b)},b.scale=function(a,b,c,d){null==b&&(b=a),(c||d)&&this.add(1,0,0,1,c,d),this.add(a,0,0,b,0,0),(c||d)&&this.add(1,0,0,1,-c,-d)},b.rotate=function(b,c,d){b=a.rad(b),c=c||0,d=d||0;var e=+L.cos(b).toFixed(9),f=+L.sin(b).toFixed(9);this.add(e,f,-f,e,c,d),this.add(1,0,0,1,-c,-d)},b.x=function(a,b){return a*this.a+b*this.c+this.e},b.y=function(a,b){return a*this.b+b*this.d+this.f},b.get=function(a){return+this[G.fromCharCode(97+a)].toFixed(4)},b.toString=function(){return a.svg?"matrix("+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)].join()+")":[this.get(0),this.get(2),this.get(1),this.get(3),0,0].join()},b.toFilter=function(){return"progid:DXImageTransform.Microsoft.Matrix(M11="+this.get(0)+", M12="+this.get(2)+", M21="+this.get(1)+", M22="+this.get(3)+", Dx="+this.get(4)+", Dy="+this.get(5)+", sizingmethod='auto expand')"},b.offset=function(){return[this.e.toFixed(4),this.f.toFixed(4)]},b.split=function(){var b={};b.dx=this.e,b.dy=this.f;var e=[[this.a,this.c],[this.b,this.d]];b.scalex=L.sqrt(c(e[0])),d(e[0]),b.shear=e[0][0]*e[1][0]+e[0][1]*e[1][1],e[1]=[e[1][0]-e[0][0]*b.shear,e[1][1]-e[0][1]*b.shear],b.scaley=L.sqrt(c(e[1])),d(e[1]),b.shear/=b.scaley;var f=-e[0][1],g=e[1][1];return 0>g?(b.rotate=a.deg(L.acos(g)),0>f&&(b.rotate=360-b.rotate)):b.rotate=a.deg(L.asin(f)),b.isSimple=!(+b.shear.toFixed(9)||b.scalex.toFixed(9)!=b.scaley.toFixed(9)&&b.rotate),b.isSuperSimple=!+b.shear.toFixed(9)&&b.scalex.toFixed(9)==b.scaley.toFixed(9)&&!b.rotate,b.noRotation=!+b.shear.toFixed(9)&&!b.rotate,b},b.toTransformString=function(a){var b=a||this[H]();return b.isSimple?(b.scalex=+b.scalex.toFixed(4),b.scaley=+b.scaley.toFixed(4),b.rotate=+b.rotate.toFixed(4),(b.dx||b.dy?"t"+[b.dx,b.dy]:E)+(1!=b.scalex||1!=b.scaley?"s"+[b.scalex,b.scaley,0,0]:E)+(b.rotate?"r"+[b.rotate,0,0]:E)):"m"+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)]}}(m.prototype);var Ob=navigator.userAgent.match(/Version\/(.*?)\s/)||navigator.userAgent.match(/Chrome\/(\d+)/);t.safari="Apple Computer, Inc."==navigator.vendor&&(Ob&&Ob[1]<4||"iP"==navigator.platform.slice(0,2))||"Google Inc."==navigator.vendor&&Ob&&Ob[1]<8?function(){var a=this.rect(-99,-99,this.width+99,this.height+99).attr({stroke:"none"});setTimeout(function(){a.remove()})}:kb;for(var Pb=function(){this.returnValue=!1},Qb=function(){return this.originalEvent.preventDefault()},Rb=function(){this.cancelBubble=!0},Sb=function(){return this.originalEvent.stopPropagation()},Tb=function(){return y.doc.addEventListener?function(a,b,c,d){var e=D&&J[b]?J[b]:b,f=function(e){var f=y.doc.documentElement.scrollTop||y.doc.body.scrollTop,g=y.doc.documentElement.scrollLeft||y.doc.body.scrollLeft,h=e.clientX+g,i=e.clientY+f;if(D&&J[x](b))for(var j=0,k=e.targetTouches&&e.targetTouches.length;k>j;j++)if(e.targetTouches[j].target==a){var l=e;e=e.targetTouches[j],e.originalEvent=l,e.preventDefault=Qb,e.stopPropagation=Sb;break}return c.call(d,e,h,i)};return a.addEventListener(e,f,!1),function(){return a.removeEventListener(e,f,!1),!0}}:y.doc.attachEvent?function(a,b,c,d){var e=function(a){a=a||y.win.event;var b=y.doc.documentElement.scrollTop||y.doc.body.scrollTop,e=y.doc.documentElement.scrollLeft||y.doc.body.scrollLeft,f=a.clientX+e,g=a.clientY+b;return a.preventDefault=a.preventDefault||Pb,a.stopPropagation=a.stopPropagation||Rb,c.call(d,a,f,g)};a.attachEvent("on"+b,e);var f=function(){return a.detachEvent("on"+b,e),!0};return f}:void 0}(),Ub=[],Vb=function(a){for(var b,c=a.clientX,d=a.clientY,e=y.doc.documentElement.scrollTop||y.doc.body.scrollTop,f=y.doc.documentElement.scrollLeft||y.doc.body.scrollLeft,g=Ub.length;g--;){if(b=Ub[g],D){for(var h,i=a.touches.length;i--;)if(h=a.touches[i],h.identifier==b.el._drag.id){c=h.clientX,d=h.clientY,(a.originalEvent?a.originalEvent:a).preventDefault();break}}else a.preventDefault();var j,k=b.el.node,l=k.nextSibling,m=k.parentNode,n=k.style.display;y.win.opera&&m.removeChild(k),k.style.display="none",j=b.el.paper.getElementByPoint(c,d),k.style.display=n,y.win.opera&&(l?m.insertBefore(k,l):m.appendChild(k)),j&&eve("raphael.drag.over."+b.el.id,b.el,j),c+=f,d+=e,eve("raphael.drag.move."+b.el.id,b.move_scope||b.el,c-b.el._drag.x,d-b.el._drag.y,c,d,a)}},Wb=function(b){a.unmousemove(Vb).unmouseup(Wb);for(var c,d=Ub.length;d--;)c=Ub[d],c.el._drag={},eve("raphael.drag.end."+c.el.id,c.end_scope||c.start_scope||c.move_scope||c.el,b);Ub=[]},Xb=a.el={},Yb=I.length;Yb--;)!function(b){a[b]=Xb[b]=function(c,d){return a.is(c,"function")&&(this.events=this.events||[],this.events.push({name:b,f:c,unbind:Tb(this.shape||this.node||y.doc,b,c,d||this)})),this},a["un"+b]=Xb["un"+b]=function(a){for(var c=this.events||[],d=c.length;d--;)if(c[d].name==b&&c[d].f==a)return c[d].unbind(),c.splice(d,1),!c.length&&delete this.events,this;return this}}(I[Yb]);Xb.data=function(b,c){var d=ib[this.id]=ib[this.id]||{};if(1==arguments.length){if(a.is(b,"object")){for(var e in b)b[x](e)&&this.data(e,b[e]);return this}return eve("raphael.data.get."+this.id,this,d[b],b),d[b]}return d[b]=c,eve("raphael.data.set."+this.id,this,c,b),this},Xb.removeData=function(a){return null==a?ib[this.id]={}:ib[this.id]&&delete ib[this.id][a],this},Xb.hover=function(a,b,c,d){return this.mouseover(a,c).mouseout(b,d||c)},Xb.unhover=function(a,b){return this.unmouseover(a).unmouseout(b)};var Zb=[];Xb.drag=function(b,c,d,e,f,g){function h(h){(h.originalEvent||h).preventDefault();var i=y.doc.documentElement.scrollTop||y.doc.body.scrollTop,j=y.doc.documentElement.scrollLeft||y.doc.body.scrollLeft;this._drag.x=h.clientX+j,this._drag.y=h.clientY+i,this._drag.id=h.identifier,!Ub.length&&a.mousemove(Vb).mouseup(Wb),Ub.push({el:this,move_scope:e,start_scope:f,end_scope:g}),c&&eve.on("raphael.drag.start."+this.id,c),b&&eve.on("raphael.drag.move."+this.id,b),d&&eve.on("raphael.drag.end."+this.id,d),eve("raphael.drag.start."+this.id,f||e||this,h.clientX+j,h.clientY+i,h)}return this._drag={},Zb.push({el:this,start:h}),this.mousedown(h),this},Xb.onDragOver=function(a){a?eve.on("raphael.drag.over."+this.id,a):eve.unbind("raphael.drag.over."+this.id)},Xb.undrag=function(){for(var b=Zb.length;b--;)Zb[b].el==this&&(this.unmousedown(Zb[b].start),Zb.splice(b,1),eve.unbind("raphael.drag.*."+this.id));!Zb.length&&a.unmousemove(Vb).unmouseup(Wb)},t.circle=function(b,c,d){var e=a._engine.circle(this,b||0,c||0,d||0);return this.__set__&&this.__set__.push(e),e},t.rect=function(b,c,d,e,f){var g=a._engine.rect(this,b||0,c||0,d||0,e||0,f||0);return this.__set__&&this.__set__.push(g),g},t.ellipse=function(b,c,d,e){var f=a._engine.ellipse(this,b||0,c||0,d||0,e||0);return this.__set__&&this.__set__.push(f),f},t.path=function(b){b&&!a.is(b,S)&&!a.is(b[0],T)&&(b+=E);var c=a._engine.path(a.format[B](a,arguments),this);return this.__set__&&this.__set__.push(c),c},t.image=function(b,c,d,e,f){var g=a._engine.image(this,b||"about:blank",c||0,d||0,e||0,f||0);return this.__set__&&this.__set__.push(g),g},t.text=function(b,c,d){var e=a._engine.text(this,b||0,c||0,G(d));return this.__set__&&this.__set__.push(e),e},t.set=function(b){!a.is(b,"array")&&(b=Array.prototype.splice.call(arguments,0,arguments.length));var c=new jc(b);return this.__set__&&this.__set__.push(c),c},t.setStart=function(a){this.__set__=a||this.set()},t.setFinish=function(){var a=this.__set__;return delete this.__set__,a},t.setSize=function(b,c){return a._engine.setSize.call(this,b,c)},t.setViewBox=function(b,c,d,e,f){return a._engine.setViewBox.call(this,b,c,d,e,f)},t.top=t.bottom=null,t.raphael=a; var $b=function(a){var b=a.getBoundingClientRect(),c=a.ownerDocument,d=c.body,e=c.documentElement,f=e.clientTop||d.clientTop||0,g=e.clientLeft||d.clientLeft||0,h=b.top+(y.win.pageYOffset||e.scrollTop||d.scrollTop)-f,i=b.left+(y.win.pageXOffset||e.scrollLeft||d.scrollLeft)-g;return{y:h,x:i}};t.getElementByPoint=function(a,b){var c=this,d=c.canvas,e=y.doc.elementFromPoint(a,b);if(y.win.opera&&"svg"==e.tagName){var f=$b(d),g=d.createSVGRect();g.x=a-f.x,g.y=b-f.y,g.width=g.height=1;var h=d.getIntersectionList(g,null);h.length&&(e=h[h.length-1])}if(!e)return null;for(;e.parentNode&&e!=d.parentNode&&!e.raphael;)e=e.parentNode;return e==c.canvas.parentNode&&(e=d),e=e&&e.raphael?c.getById(e.raphaelid):null},t.getById=function(a){for(var b=this.bottom;b;){if(b.id==a)return b;b=b.next}return null},t.forEach=function(a,b){for(var c=this.bottom;c;){if(a.call(b,c)===!1)return this;c=c.next}return this},t.getElementsByPoint=function(a,b){var c=this.set();return this.forEach(function(d){d.isPointInside(a,b)&&c.push(d)}),c},Xb.isPointInside=function(b,c){var d=this.realPath=this.realPath||ob[this.type](this);return a.isPointInsidePath(d,b,c)},Xb.getBBox=function(a){if(this.removed)return{};var b=this._;return a?((b.dirty||!b.bboxwt)&&(this.realPath=ob[this.type](this),b.bboxwt=zb(this.realPath),b.bboxwt.toString=n,b.dirty=0),b.bboxwt):((b.dirty||b.dirtyT||!b.bbox)&&((b.dirty||!this.realPath)&&(b.bboxwt=0,this.realPath=ob[this.type](this)),b.bbox=zb(pb(this.realPath,this.matrix)),b.bbox.toString=n,b.dirty=b.dirtyT=0),b.bbox)},Xb.clone=function(){if(this.removed)return null;var a=this.paper[this.type]().attr(this.attr());return this.__set__&&this.__set__.push(a),a},Xb.glow=function(a){if("text"==this.type)return null;a=a||{};var b={width:(a.width||10)+(+this.attr("stroke-width")||1),fill:a.fill||!1,opacity:a.opacity||.5,offsetx:a.offsetx||0,offsety:a.offsety||0,color:a.color||"#000"},c=b.width/2,d=this.paper,e=d.set(),f=this.realPath||ob[this.type](this);f=this.matrix?pb(f,this.matrix):f;for(var g=1;c+1>g;g++)e.push(d.path(f).attr({stroke:b.color,fill:b.fill?b.color:"none","stroke-linejoin":"round","stroke-linecap":"round","stroke-width":+(b.width/c*g).toFixed(3),opacity:+(b.opacity/c).toFixed(3)}));return e.insertBefore(this).translate(b.offsetx,b.offsety)};var _b=function(b,c,d,e,f,g,j,k,l){return null==l?h(b,c,d,e,f,g,j,k):a.findDotsAtSegment(b,c,d,e,f,g,j,k,i(b,c,d,e,f,g,j,k,l))},ac=function(b,c){return function(d,e,f){d=Ib(d);for(var g,h,i,j,k,l="",m={},n=0,o=0,p=d.length;p>o;o++){if(i=d[o],"M"==i[0])g=+i[1],h=+i[2];else{if(j=_b(g,h,i[1],i[2],i[3],i[4],i[5],i[6]),n+j>e){if(c&&!m.start){if(k=_b(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n),l+=["C"+k.start.x,k.start.y,k.m.x,k.m.y,k.x,k.y],f)return l;m.start=l,l=["M"+k.x,k.y+"C"+k.n.x,k.n.y,k.end.x,k.end.y,i[5],i[6]].join(),n+=j,g=+i[5],h=+i[6];continue}if(!b&&!c)return k=_b(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n),{x:k.x,y:k.y,alpha:k.alpha}}n+=j,g=+i[5],h=+i[6]}l+=i.shift()+i}return m.end=l,k=b?n:c?m:a.findDotsAtSegment(g,h,i[0],i[1],i[2],i[3],i[4],i[5],1),k.alpha&&(k={x:k.x,y:k.y,alpha:k.alpha}),k}},bc=ac(1),cc=ac(),dc=ac(0,1);a.getTotalLength=bc,a.getPointAtLength=cc,a.getSubpath=function(a,b,c){if(this.getTotalLength(a)-c<1e-6)return dc(a,b).end;var d=dc(a,c,1);return b?dc(d,b).end:d},Xb.getTotalLength=function(){return"path"==this.type?this.node.getTotalLength?this.node.getTotalLength():bc(this.attrs.path):void 0},Xb.getPointAtLength=function(a){return"path"==this.type?cc(this.attrs.path,a):void 0},Xb.getSubpath=function(b,c){return"path"==this.type?a.getSubpath(this.attrs.path,b,c):void 0};var ec=a.easing_formulas={linear:function(a){return a},"<":function(a){return P(a,1.7)},">":function(a){return P(a,.48)},"<>":function(a){var b=.48-a/1.04,c=L.sqrt(.1734+b*b),d=c-b,e=P(O(d),1/3)*(0>d?-1:1),f=-c-b,g=P(O(f),1/3)*(0>f?-1:1),h=e+g+.5;return 3*(1-h)*h*h+h*h*h},backIn:function(a){var b=1.70158;return a*a*((b+1)*a-b)},backOut:function(a){a-=1;var b=1.70158;return a*a*((b+1)*a+b)+1},elastic:function(a){return a==!!a?a:P(2,-10*a)*L.sin(2*(a-.075)*Q/.3)+1},bounce:function(a){var b,c=7.5625,d=2.75;return 1/d>a?b=c*a*a:2/d>a?(a-=1.5/d,b=c*a*a+.75):2.5/d>a?(a-=2.25/d,b=c*a*a+.9375):(a-=2.625/d,b=c*a*a+.984375),b}};ec.easeIn=ec["ease-in"]=ec["<"],ec.easeOut=ec["ease-out"]=ec[">"],ec.easeInOut=ec["ease-in-out"]=ec["<>"],ec["back-in"]=ec.backIn,ec["back-out"]=ec.backOut;var fc=[],gc=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,16)},hc=function(){for(var b=+new Date,c=0;c<fc.length;c++){var d=fc[c];if(!d.el.removed&&!d.paused){var e,f,g=b-d.start,h=d.ms,i=d.easing,j=d.from,k=d.diff,l=d.to,m=(d.t,d.el),n={},o={};if(d.initstatus?(g=(d.initstatus*d.anim.top-d.prev)/(d.percent-d.prev)*h,d.status=d.initstatus,delete d.initstatus,d.stop&&fc.splice(c--,1)):d.status=(d.prev+(d.percent-d.prev)*(g/h))/d.anim.top,!(0>g))if(h>g){var p=i(g/h);for(var r in j)if(j[x](r)){switch(bb[r]){case R:e=+j[r]+p*h*k[r];break;case"colour":e="rgb("+[ic(Y(j[r].r+p*h*k[r].r)),ic(Y(j[r].g+p*h*k[r].g)),ic(Y(j[r].b+p*h*k[r].b))].join(",")+")";break;case"path":e=[];for(var s=0,t=j[r].length;t>s;s++){e[s]=[j[r][s][0]];for(var u=1,v=j[r][s].length;v>u;u++)e[s][u]=+j[r][s][u]+p*h*k[r][s][u];e[s]=e[s].join(F)}e=e.join(F);break;case"transform":if(k[r].real)for(e=[],s=0,t=j[r].length;t>s;s++)for(e[s]=[j[r][s][0]],u=1,v=j[r][s].length;v>u;u++)e[s][u]=j[r][s][u]+p*h*k[r][s][u];else{var w=function(a){return+j[r][a]+p*h*k[r][a]};e=[["m",w(0),w(1),w(2),w(3),w(4),w(5)]]}break;case"csv":if("clip-rect"==r)for(e=[],s=4;s--;)e[s]=+j[r][s]+p*h*k[r][s];break;default:var y=[][C](j[r]);for(e=[],s=m.paper.customAttributes[r].length;s--;)e[s]=+y[s]+p*h*k[r][s]}n[r]=e}m.attr(n),function(a,b,c){setTimeout(function(){eve("raphael.anim.frame."+a,b,c)})}(m.id,m,d.anim)}else{if(function(b,c,d){setTimeout(function(){eve("raphael.anim.frame."+c.id,c,d),eve("raphael.anim.finish."+c.id,c,d),a.is(b,"function")&&b.call(c)})}(d.callback,m,d.anim),m.attr(l),fc.splice(c--,1),d.repeat>1&&!d.next){for(f in l)l[x](f)&&(o[f]=d.totalOrigin[f]);d.el.attr(o),q(d.anim,d.el,d.anim.percents[0],null,d.totalOrigin,d.repeat-1)}d.next&&!d.stop&&q(d.anim,d.el,d.next,null,d.totalOrigin,d.repeat)}}}a.svg&&m&&m.paper&&m.paper.safari(),fc.length&&gc(hc)},ic=function(a){return a>255?255:0>a?0:a};Xb.animateWith=function(b,c,d,e,f,g){var h=this;if(h.removed)return g&&g.call(h),h;var i=d instanceof p?d:a.animation(d,e,f,g);q(i,h,i.percents[0],null,h.attr());for(var j=0,k=fc.length;k>j;j++)if(fc[j].anim==c&&fc[j].el==b){fc[k-1].start=fc[j].start;break}return h},Xb.onAnimation=function(a){return a?eve.on("raphael.anim.frame."+this.id,a):eve.unbind("raphael.anim.frame."+this.id),this},p.prototype.delay=function(a){var b=new p(this.anim,this.ms);return b.times=this.times,b.del=+a||0,b},p.prototype.repeat=function(a){var b=new p(this.anim,this.ms);return b.del=this.del,b.times=L.floor(M(a,0))||1,b},a.animation=function(b,c,d,e){if(b instanceof p)return b;(a.is(d,"function")||!d)&&(e=e||d||null,d=null),b=Object(b),c=+c||0;var f,g,h={};for(g in b)b[x](g)&&Z(g)!=g&&Z(g)+"%"!=g&&(f=!0,h[g]=b[g]);return f?(d&&(h.easing=d),e&&(h.callback=e),new p({100:h},c)):new p(b,c)},Xb.animate=function(b,c,d,e){var f=this;if(f.removed)return e&&e.call(f),f;var g=b instanceof p?b:a.animation(b,c,d,e);return q(g,f,g.percents[0],null,f.attr()),f},Xb.setTime=function(a,b){return a&&null!=b&&this.status(a,N(b,a.ms)/a.ms),this},Xb.status=function(a,b){var c,d,e=[],f=0;if(null!=b)return q(a,this,-1,N(b,1)),this;for(c=fc.length;c>f;f++)if(d=fc[f],d.el.id==this.id&&(!a||d.anim==a)){if(a)return d.status;e.push({anim:d.anim,status:d.status})}return a?0:e},Xb.pause=function(a){for(var b=0;b<fc.length;b++)fc[b].el.id!=this.id||a&&fc[b].anim!=a||eve("raphael.anim.pause."+this.id,this,fc[b].anim)!==!1&&(fc[b].paused=!0);return this},Xb.resume=function(a){for(var b=0;b<fc.length;b++)if(fc[b].el.id==this.id&&(!a||fc[b].anim==a)){var c=fc[b];eve("raphael.anim.resume."+this.id,this,c.anim)!==!1&&(delete c.paused,this.status(c.anim,c.status))}return this},Xb.stop=function(a){for(var b=0;b<fc.length;b++)fc[b].el.id!=this.id||a&&fc[b].anim!=a||eve("raphael.anim.stop."+this.id,this,fc[b].anim)!==!1&&fc.splice(b--,1);return this},eve.on("raphael.remove",r),eve.on("raphael.clear",r),Xb.toString=function(){return"Rapha\xebl\u2019s object"};var jc=function(a){if(this.items=[],this.length=0,this.type="set",a)for(var b=0,c=a.length;c>b;b++)!a[b]||a[b].constructor!=Xb.constructor&&a[b].constructor!=jc||(this[this.items.length]=this.items[this.items.length]=a[b],this.length++)},kc=jc.prototype;kc.push=function(){for(var a,b,c=0,d=arguments.length;d>c;c++)a=arguments[c],!a||a.constructor!=Xb.constructor&&a.constructor!=jc||(b=this.items.length,this[b]=this.items[b]=a,this.length++);return this},kc.pop=function(){return this.length&&delete this[this.length--],this.items.pop()},kc.forEach=function(a,b){for(var c=0,d=this.items.length;d>c;c++)if(a.call(b,this.items[c],c)===!1)return this;return this};for(var lc in Xb)Xb[x](lc)&&(kc[lc]=function(a){return function(){var b=arguments;return this.forEach(function(c){c[a][B](c,b)})}}(lc));kc.attr=function(b,c){if(b&&a.is(b,T)&&a.is(b[0],"object"))for(var d=0,e=b.length;e>d;d++)this.items[d].attr(b[d]);else for(var f=0,g=this.items.length;g>f;f++)this.items[f].attr(b,c);return this},kc.clear=function(){for(;this.length;)this.pop()},kc.splice=function(a,b){a=0>a?M(this.length+a,0):a,b=M(0,N(this.length-a,b));var c,d=[],e=[],f=[];for(c=2;c<arguments.length;c++)f.push(arguments[c]);for(c=0;b>c;c++)e.push(this[a+c]);for(;c<this.length-a;c++)d.push(this[a+c]);var g=f.length;for(c=0;c<g+d.length;c++)this.items[a+c]=this[a+c]=g>c?f[c]:d[c-g];for(c=this.items.length=this.length-=b-g;this[c];)delete this[c++];return new jc(e)},kc.exclude=function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]==a)return this.splice(b,1),!0},kc.animate=function(b,c,d,e){(a.is(d,"function")||!d)&&(e=d||null);var f,g,h=this.items.length,i=h,j=this;if(!h)return this;e&&(g=function(){!--h&&e.call(j)}),d=a.is(d,S)?d:g;var k=a.animation(b,c,d,g);for(f=this.items[--i].animate(k);i--;)this.items[i]&&!this.items[i].removed&&this.items[i].animateWith(f,k,k);return this},kc.insertAfter=function(a){for(var b=this.items.length;b--;)this.items[b].insertAfter(a);return this},kc.getBBox=function(){for(var a=[],b=[],c=[],d=[],e=this.items.length;e--;)if(!this.items[e].removed){var f=this.items[e].getBBox();a.push(f.x),b.push(f.y),c.push(f.x+f.width),d.push(f.y+f.height)}return a=N[B](0,a),b=N[B](0,b),c=M[B](0,c),d=M[B](0,d),{x:a,y:b,x2:c,y2:d,width:c-a,height:d-b}},kc.clone=function(a){a=new jc;for(var b=0,c=this.items.length;c>b;b++)a.push(this.items[b].clone());return a},kc.toString=function(){return"Rapha\xebl\u2018s set"},a.registerFont=function(a){if(!a.face)return a;this.fonts=this.fonts||{};var b={w:a.w,face:{},glyphs:{}},c=a.face["font-family"];for(var d in a.face)a.face[x](d)&&(b.face[d]=a.face[d]);if(this.fonts[c]?this.fonts[c].push(b):this.fonts[c]=[b],!a.svg){b.face["units-per-em"]=$(a.face["units-per-em"],10);for(var e in a.glyphs)if(a.glyphs[x](e)){var f=a.glyphs[e];if(b.glyphs[e]={w:f.w,k:{},d:f.d&&"M"+f.d.replace(/[mlcxtrv]/g,function(a){return{l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"}[a]||"M"})+"z"},f.k)for(var g in f.k)f[x](g)&&(b.glyphs[e].k[g]=f.k[g])}}return a},t.getFont=function(b,c,d,e){if(e=e||"normal",d=d||"normal",c=+c||{normal:400,bold:700,lighter:300,bolder:800}[c]||400,a.fonts){var f=a.fonts[b];if(!f){var g=new RegExp("(^|\\s)"+b.replace(/[^\w\d\s+!~.:_-]/g,E)+"(\\s|$)","i");for(var h in a.fonts)if(a.fonts[x](h)&&g.test(h)){f=a.fonts[h];break}}var i;if(f)for(var j=0,k=f.length;k>j&&(i=f[j],i.face["font-weight"]!=c||i.face["font-style"]!=d&&i.face["font-style"]||i.face["font-stretch"]!=e);j++);return i}},t.print=function(b,c,d,e,f,g,h){g=g||"middle",h=M(N(h||0,1),-1);var i,j=G(d)[H](E),k=0,l=0,m=E;if(a.is(e,d)&&(e=this.getFont(e)),e){i=(f||16)/e.face["units-per-em"];for(var n=e.face.bbox[H](u),o=+n[0],p=n[3]-n[1],q=0,r=+n[1]+("baseline"==g?p+ +e.face.descent:p/2),s=0,t=j.length;t>s;s++){if("\n"==j[s])k=0,w=0,l=0,q+=p;else{var v=l&&e.glyphs[j[s-1]]||{},w=e.glyphs[j[s]];k+=l?(v.w||e.w)+(v.k&&v.k[j[s]]||0)+e.w*h:0,l=1}w&&w.d&&(m+=a.transformPath(w.d,["t",k*i,q*i,"s",i,i,o,r,"t",(b-o)/i,(c-r)/i]))}}return this.path(m).attr({fill:"#000",stroke:"none"})},t.add=function(b){if(a.is(b,"array"))for(var c,d=this.set(),e=0,f=b.length;f>e;e++)c=b[e]||{},v[x](c.type)&&d.push(this[c.type]().attr(c));return d},a.format=function(b,c){var d=a.is(c,T)?[0][C](c):arguments;return b&&a.is(b,S)&&d.length-1&&(b=b.replace(w,function(a,b){return null==d[++b]?E:d[b]})),b||E},a.fullfill=function(){var a=/\{([^\}]+)\}/g,b=/(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g,c=function(a,c,d){var e=d;return c.replace(b,function(a,b,c,d,f){b=b||d,e&&(b in e&&(e=e[b]),"function"==typeof e&&f&&(e=e()))}),e=(null==e||e==d?a:e)+""};return function(b,d){return String(b).replace(a,function(a,b){return c(a,b,d)})}}(),a.ninja=function(){return z.was?y.win.Raphael=z.is:delete Raphael,a},a.st=kc,function(b,c,d){function e(){/in/.test(b.readyState)?setTimeout(e,9):a.eve("raphael.DOMload")}null==b.readyState&&b.addEventListener&&(b.addEventListener(c,d=function(){b.removeEventListener(c,d,!1),b.readyState="complete"},!1),b.readyState="loading"),e()}(document,"DOMContentLoaded"),z.was?y.win.Raphael=a:Raphael=a,eve.on("raphael.DOMload",function(){s=!0})}(),window.Raphael&&window.Raphael.svg&&function(a){var b="hasOwnProperty",c=String,d=parseFloat,e=parseInt,f=Math,g=f.max,h=f.abs,i=f.pow,j=/[, ]+/,k=a.eve,l="",m=" ",n="http://www.w3.org/1999/xlink",o={block:"M5,0 0,2.5 5,5z",classic:"M5,0 0,2.5 5,5 3.5,3 3.5,2z",diamond:"M2.5,0 5,2.5 2.5,5 0,2.5z",open:"M6,1 1,3.5 6,6",oval:"M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"},p={};a.toString=function(){return"Your browser supports SVG.\nYou are running Rapha\xebl "+this.version};var q=function(d,e){if(e){"string"==typeof d&&(d=q(d));for(var f in e)e[b](f)&&("xlink:"==f.substring(0,6)?d.setAttributeNS(n,f.substring(6),c(e[f])):d.setAttribute(f,c(e[f])))}else d=a._g.doc.createElementNS("http://www.w3.org/2000/svg",d),d.style&&(d.style.webkitTapHighlightColor="rgba(0,0,0,0)");return d},r=function(b,e){var j="linear",k=b.id+e,m=.5,n=.5,o=b.node,p=b.paper,r=o.style,s=a._g.doc.getElementById(k);if(!s){if(e=c(e).replace(a._radial_gradient,function(a,b,c){if(j="radial",b&&c){m=d(b),n=d(c);var e=2*(n>.5)-1;i(m-.5,2)+i(n-.5,2)>.25&&(n=f.sqrt(.25-i(m-.5,2))*e+.5)&&.5!=n&&(n=n.toFixed(5)-1e-5*e)}return l}),e=e.split(/\s*\-\s*/),"linear"==j){var t=e.shift();if(t=-d(t),isNaN(t))return null;var u=[0,0,f.cos(a.rad(t)),f.sin(a.rad(t))],v=1/(g(h(u[2]),h(u[3]))||1);u[2]*=v,u[3]*=v,u[2]<0&&(u[0]=-u[2],u[2]=0),u[3]<0&&(u[1]=-u[3],u[3]=0)}var w=a._parseDots(e);if(!w)return null;if(k=k.replace(/[\(\)\s,\xb0#]/g,"_"),b.gradient&&k!=b.gradient.id&&(p.defs.removeChild(b.gradient),delete b.gradient),!b.gradient){s=q(j+"Gradient",{id:k}),b.gradient=s,q(s,"radial"==j?{fx:m,fy:n}:{x1:u[0],y1:u[1],x2:u[2],y2:u[3],gradientTransform:b.matrix.invert()}),p.defs.appendChild(s);for(var x=0,y=w.length;y>x;x++)s.appendChild(q("stop",{offset:w[x].offset?w[x].offset:x?"100%":"0%","stop-color":w[x].color||"#fff"}))}}return q(o,{fill:"url(#"+k+")",opacity:1,"fill-opacity":1}),r.fill=l,r.opacity=1,r.fillOpacity=1,1},s=function(a){var b=a.getBBox(1);q(a.pattern,{patternTransform:a.matrix.invert()+" translate("+b.x+","+b.y+")"})},t=function(d,e,f){if("path"==d.type){for(var g,h,i,j,k,m=c(e).toLowerCase().split("-"),n=d.paper,r=f?"end":"start",s=d.node,t=d.attrs,u=t["stroke-width"],v=m.length,w="classic",x=3,y=3,z=5;v--;)switch(m[v]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":w=m[v];break;case"wide":y=5;break;case"narrow":y=2;break;case"long":x=5;break;case"short":x=2}if("open"==w?(x+=2,y+=2,z+=2,i=1,j=f?4:1,k={fill:"none",stroke:t.stroke}):(j=i=x/2,k={fill:t.stroke,stroke:"none"}),d._.arrows?f?(d._.arrows.endPath&&p[d._.arrows.endPath]--,d._.arrows.endMarker&&p[d._.arrows.endMarker]--):(d._.arrows.startPath&&p[d._.arrows.startPath]--,d._.arrows.startMarker&&p[d._.arrows.startMarker]--):d._.arrows={},"none"!=w){var A="raphael-marker-"+w,B="raphael-marker-"+r+w+x+y;a._g.doc.getElementById(A)?p[A]++:(n.defs.appendChild(q(q("path"),{"stroke-linecap":"round",d:o[w],id:A})),p[A]=1);var C,D=a._g.doc.getElementById(B);D?(p[B]++,C=D.getElementsByTagName("use")[0]):(D=q(q("marker"),{id:B,markerHeight:y,markerWidth:x,orient:"auto",refX:j,refY:y/2}),C=q(q("use"),{"xlink:href":"#"+A,transform:(f?"rotate(180 "+x/2+" "+y/2+") ":l)+"scale("+x/z+","+y/z+")","stroke-width":(1/((x/z+y/z)/2)).toFixed(4)}),D.appendChild(C),n.defs.appendChild(D),p[B]=1),q(C,k);var E=i*("diamond"!=w&&"oval"!=w);f?(g=d._.arrows.startdx*u||0,h=a.getTotalLength(t.path)-E*u):(g=E*u,h=a.getTotalLength(t.path)-(d._.arrows.enddx*u||0)),k={},k["marker-"+r]="url(#"+B+")",(h||g)&&(k.d=Raphael.getSubpath(t.path,g,h)),q(s,k),d._.arrows[r+"Path"]=A,d._.arrows[r+"Marker"]=B,d._.arrows[r+"dx"]=E,d._.arrows[r+"Type"]=w,d._.arrows[r+"String"]=e}else f?(g=d._.arrows.startdx*u||0,h=a.getTotalLength(t.path)-g):(g=0,h=a.getTotalLength(t.path)-(d._.arrows.enddx*u||0)),d._.arrows[r+"Path"]&&q(s,{d:Raphael.getSubpath(t.path,g,h)}),delete d._.arrows[r+"Path"],delete d._.arrows[r+"Marker"],delete d._.arrows[r+"dx"],delete d._.arrows[r+"Type"],delete d._.arrows[r+"String"];for(k in p)if(p[b](k)&&!p[k]){var F=a._g.doc.getElementById(k);F&&F.parentNode.removeChild(F)}}},u={"":[0],none:[0],"-":[3,1],".":[1,1],"-.":[3,1,1,1],"-..":[3,1,1,1,1,1],". ":[1,3],"- ":[4,3],"--":[8,3],"- .":[4,3,1,3],"--.":[8,3,1,3],"--..":[8,3,1,3,1,3]},v=function(a,b,d){if(b=u[c(b).toLowerCase()]){for(var e=a.attrs["stroke-width"]||"1",f={round:e,square:e,butt:0}[a.attrs["stroke-linecap"]||d["stroke-linecap"]]||0,g=[],h=b.length;h--;)g[h]=b[h]*e+(h%2?1:-1)*f;q(a.node,{"stroke-dasharray":g.join(",")})}},w=function(d,f){var i=d.node,k=d.attrs,m=i.style.visibility;i.style.visibility="hidden";for(var o in f)if(f[b](o)){if(!a._availableAttrs[b](o))continue;var p=f[o];switch(k[o]=p,o){case"blur":d.blur(p);break;case"href":case"title":case"target":var u=i.parentNode;if("a"!=u.tagName.toLowerCase()){var w=q("a");u.insertBefore(w,i),w.appendChild(i),u=w}"target"==o?u.setAttributeNS(n,"show","blank"==p?"new":p):u.setAttributeNS(n,o,p);break;case"cursor":i.style.cursor=p;break;case"transform":d.transform(p);break;case"arrow-start":t(d,p);break;case"arrow-end":t(d,p,1);break;case"clip-rect":var x=c(p).split(j);if(4==x.length){d.clip&&d.clip.parentNode.parentNode.removeChild(d.clip.parentNode);var z=q("clipPath"),A=q("rect");z.id=a.createUUID(),q(A,{x:x[0],y:x[1],width:x[2],height:x[3]}),z.appendChild(A),d.paper.defs.appendChild(z),q(i,{"clip-path":"url(#"+z.id+")"}),d.clip=A}if(!p){var B=i.getAttribute("clip-path");if(B){var C=a._g.doc.getElementById(B.replace(/(^url\(#|\)$)/g,l));C&&C.parentNode.removeChild(C),q(i,{"clip-path":l}),delete d.clip}}break;case"path":"path"==d.type&&(q(i,{d:p?k.path=a._pathToAbsolute(p):"M0,0"}),d._.dirty=1,d._.arrows&&("startString"in d._.arrows&&t(d,d._.arrows.startString),"endString"in d._.arrows&&t(d,d._.arrows.endString,1)));break;case"width":if(i.setAttribute(o,p),d._.dirty=1,!k.fx)break;o="x",p=k.x;case"x":k.fx&&(p=-k.x-(k.width||0));case"rx":if("rx"==o&&"rect"==d.type)break;case"cx":i.setAttribute(o,p),d.pattern&&s(d),d._.dirty=1;break;case"height":if(i.setAttribute(o,p),d._.dirty=1,!k.fy)break;o="y",p=k.y;case"y":k.fy&&(p=-k.y-(k.height||0));case"ry":if("ry"==o&&"rect"==d.type)break;case"cy":i.setAttribute(o,p),d.pattern&&s(d),d._.dirty=1;break;case"r":"rect"==d.type?q(i,{rx:p,ry:p}):i.setAttribute(o,p),d._.dirty=1;break;case"src":"image"==d.type&&i.setAttributeNS(n,"href",p);break;case"stroke-width":(1!=d._.sx||1!=d._.sy)&&(p/=g(h(d._.sx),h(d._.sy))||1),d.paper._vbSize&&(p*=d.paper._vbSize),i.setAttribute(o,p),k["stroke-dasharray"]&&v(d,k["stroke-dasharray"],f),d._.arrows&&("startString"in d._.arrows&&t(d,d._.arrows.startString),"endString"in d._.arrows&&t(d,d._.arrows.endString,1));break;case"stroke-dasharray":v(d,p,f);break;case"fill":var D=c(p).match(a._ISURL);if(D){z=q("pattern");var E=q("image");z.id=a.createUUID(),q(z,{x:0,y:0,patternUnits:"userSpaceOnUse",height:1,width:1}),q(E,{x:0,y:0,"xlink:href":D[1]}),z.appendChild(E),function(b){a._preload(D[1],function(){var a=this.offsetWidth,c=this.offsetHeight;q(b,{width:a,height:c}),q(E,{width:a,height:c}),d.paper.safari()})}(z),d.paper.defs.appendChild(z),q(i,{fill:"url(#"+z.id+")"}),d.pattern=z,d.pattern&&s(d);break}var F=a.getRGB(p);if(F.error){if(("circle"==d.type||"ellipse"==d.type||"r"!=c(p).charAt())&&r(d,p)){if("opacity"in k||"fill-opacity"in k){var G=a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g,l));if(G){var H=G.getElementsByTagName("stop");q(H[H.length-1],{"stop-opacity":("opacity"in k?k.opacity:1)*("fill-opacity"in k?k["fill-opacity"]:1)})}}k.gradient=p,k.fill="none";break}}else delete f.gradient,delete k.gradient,!a.is(k.opacity,"undefined")&&a.is(f.opacity,"undefined")&&q(i,{opacity:k.opacity}),!a.is(k["fill-opacity"],"undefined")&&a.is(f["fill-opacity"],"undefined")&&q(i,{"fill-opacity":k["fill-opacity"]});F[b]("opacity")&&q(i,{"fill-opacity":F.opacity>1?F.opacity/100:F.opacity});case"stroke":F=a.getRGB(p),i.setAttribute(o,F.hex),"stroke"==o&&F[b]("opacity")&&q(i,{"stroke-opacity":F.opacity>1?F.opacity/100:F.opacity}),"stroke"==o&&d._.arrows&&("startString"in d._.arrows&&t(d,d._.arrows.startString),"endString"in d._.arrows&&t(d,d._.arrows.endString,1));break;case"gradient":("circle"==d.type||"ellipse"==d.type||"r"!=c(p).charAt())&&r(d,p);break;case"opacity":k.gradient&&!k[b]("stroke-opacity")&&q(i,{"stroke-opacity":p>1?p/100:p});case"fill-opacity":if(k.gradient){G=a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g,l)),G&&(H=G.getElementsByTagName("stop"),q(H[H.length-1],{"stop-opacity":p}));break}default:"font-size"==o&&(p=e(p,10)+"px");var I=o.replace(/(\-.)/g,function(a){return a.substring(1).toUpperCase()});i.style[I]=p,d._.dirty=1,i.setAttribute(o,p)}}y(d,f),i.style.visibility=m},x=1.2,y=function(d,f){if("text"==d.type&&(f[b]("text")||f[b]("font")||f[b]("font-size")||f[b]("x")||f[b]("y"))){var g=d.attrs,h=d.node,i=h.firstChild?e(a._g.doc.defaultView.getComputedStyle(h.firstChild,l).getPropertyValue("font-size"),10):10;if(f[b]("text")){for(g.text=f.text;h.firstChild;)h.removeChild(h.firstChild);for(var j,k=c(f.text).split("\n"),m=[],n=0,o=k.length;o>n;n++)j=q("tspan"),n&&q(j,{dy:i*x,x:g.x}),j.appendChild(a._g.doc.createTextNode(k[n])),h.appendChild(j),m[n]=j}else for(m=h.getElementsByTagName("tspan"),n=0,o=m.length;o>n;n++)n?q(m[n],{dy:i*x,x:g.x}):q(m[0],{dy:0});q(h,{x:g.x,y:g.y}),d._.dirty=1;var p=d._getBBox(),r=g.y-(p.y+p.height/2);r&&a.is(r,"finite")&&q(m[0],{dy:r})}},z=function(b,c){this[0]=this.node=b,b.raphael=!0,this.id=a._oid++,b.raphaelid=this.id,this.matrix=a.matrix(),this.realPath=null,this.paper=c,this.attrs=this.attrs||{},this._={transform:[],sx:1,sy:1,deg:0,dx:0,dy:0,dirty:1},!c.bottom&&(c.bottom=this),this.prev=c.top,c.top&&(c.top.next=this),c.top=this,this.next=null},A=a.el;z.prototype=A,A.constructor=z,a._engine.path=function(a,b){var c=q("path");b.canvas&&b.canvas.appendChild(c);var d=new z(c,b);return d.type="path",w(d,{fill:"none",stroke:"#000",path:a}),d},A.rotate=function(a,b,e){if(this.removed)return this;if(a=c(a).split(j),a.length-1&&(b=d(a[1]),e=d(a[2])),a=d(a[0]),null==e&&(b=e),null==b||null==e){var f=this.getBBox(1);b=f.x+f.width/2,e=f.y+f.height/2}return this.transform(this._.transform.concat([["r",a,b,e]])),this},A.scale=function(a,b,e,f){if(this.removed)return this;if(a=c(a).split(j),a.length-1&&(b=d(a[1]),e=d(a[2]),f=d(a[3])),a=d(a[0]),null==b&&(b=a),null==f&&(e=f),null==e||null==f)var g=this.getBBox(1);return e=null==e?g.x+g.width/2:e,f=null==f?g.y+g.height/2:f,this.transform(this._.transform.concat([["s",a,b,e,f]])),this},A.translate=function(a,b){return this.removed?this:(a=c(a).split(j),a.length-1&&(b=d(a[1])),a=d(a[0])||0,b=+b||0,this.transform(this._.transform.concat([["t",a,b]])),this)},A.transform=function(c){var d=this._;if(null==c)return d.transform;if(a._extractTransform(this,c),this.clip&&q(this.clip,{transform:this.matrix.invert()}),this.pattern&&s(this),this.node&&q(this.node,{transform:this.matrix}),1!=d.sx||1!=d.sy){var e=this.attrs[b]("stroke-width")?this.attrs["stroke-width"]:1;this.attr({"stroke-width":e})}return this},A.hide=function(){return!this.removed&&this.paper.safari(this.node.style.display="none"),this},A.show=function(){return!this.removed&&this.paper.safari(this.node.style.display=""),this},A.remove=function(){if(!this.removed&&this.node.parentNode){var b=this.paper;b.__set__&&b.__set__.exclude(this),k.unbind("raphael.*.*."+this.id),this.gradient&&b.defs.removeChild(this.gradient),a._tear(this,b),"a"==this.node.parentNode.tagName.toLowerCase()?this.node.parentNode.parentNode.removeChild(this.node.parentNode):this.node.parentNode.removeChild(this.node);for(var c in this)this[c]="function"==typeof this[c]?a._removedFactory(c):null;this.removed=!0}},A._getBBox=function(){if("none"==this.node.style.display){this.show();var a=!0}var b={};try{b=this.node.getBBox()}catch(c){}finally{b=b||{}}return a&&this.hide(),b},A.attr=function(c,d){if(this.removed)return this;if(null==c){var e={};for(var f in this.attrs)this.attrs[b](f)&&(e[f]=this.attrs[f]);return e.gradient&&"none"==e.fill&&(e.fill=e.gradient)&&delete e.gradient,e.transform=this._.transform,e}if(null==d&&a.is(c,"string")){if("fill"==c&&"none"==this.attrs.fill&&this.attrs.gradient)return this.attrs.gradient;if("transform"==c)return this._.transform;for(var g=c.split(j),h={},i=0,l=g.length;l>i;i++)c=g[i],h[c]=c in this.attrs?this.attrs[c]:a.is(this.paper.customAttributes[c],"function")?this.paper.customAttributes[c].def:a._availableAttrs[c];return l-1?h:h[g[0]]}if(null==d&&a.is(c,"array")){for(h={},i=0,l=c.length;l>i;i++)h[c[i]]=this.attr(c[i]);return h}if(null!=d){var m={};m[c]=d}else null!=c&&a.is(c,"object")&&(m=c);for(var n in m)k("raphael.attr."+n+"."+this.id,this,m[n]);for(n in this.paper.customAttributes)if(this.paper.customAttributes[b](n)&&m[b](n)&&a.is(this.paper.customAttributes[n],"function")){var o=this.paper.customAttributes[n].apply(this,[].concat(m[n]));this.attrs[n]=m[n];for(var p in o)o[b](p)&&(m[p]=o[p])}return w(this,m),this},A.toFront=function(){if(this.removed)return this;"a"==this.node.parentNode.tagName.toLowerCase()?this.node.parentNode.parentNode.appendChild(this.node.parentNode):this.node.parentNode.appendChild(this.node);var b=this.paper;return b.top!=this&&a._tofront(this,b),this},A.toBack=function(){if(this.removed)return this;var b=this.node.parentNode;"a"==b.tagName.toLowerCase()?b.parentNode.insertBefore(this.node.parentNode,this.node.parentNode.parentNode.firstChild):b.firstChild!=this.node&&b.insertBefore(this.node,this.node.parentNode.firstChild),a._toback(this,this.paper);this.paper;return this},A.insertAfter=function(b){if(this.removed)return this;var c=b.node||b[b.length-1].node;return c.nextSibling?c.parentNode.insertBefore(this.node,c.nextSibling):c.parentNode.appendChild(this.node),a._insertafter(this,b,this.paper),this},A.insertBefore=function(b){if(this.removed)return this;var c=b.node||b[0].node;return c.parentNode.insertBefore(this.node,c),a._insertbefore(this,b,this.paper),this},A.blur=function(b){var c=this;if(0!==+b){var d=q("filter"),e=q("feGaussianBlur");c.attrs.blur=b,d.id=a.createUUID(),q(e,{stdDeviation:+b||1.5}),d.appendChild(e),c.paper.defs.appendChild(d),c._blur=d,q(c.node,{filter:"url(#"+d.id+")"})}else c._blur&&(c._blur.parentNode.removeChild(c._blur),delete c._blur,delete c.attrs.blur),c.node.removeAttribute("filter")},a._engine.circle=function(a,b,c,d){var e=q("circle");a.canvas&&a.canvas.appendChild(e);var f=new z(e,a);return f.attrs={cx:b,cy:c,r:d,fill:"none",stroke:"#000"},f.type="circle",q(e,f.attrs),f},a._engine.rect=function(a,b,c,d,e,f){var g=q("rect");a.canvas&&a.canvas.appendChild(g);var h=new z(g,a);return h.attrs={x:b,y:c,width:d,height:e,r:f||0,rx:f||0,ry:f||0,fill:"none",stroke:"#000"},h.type="rect",q(g,h.attrs),h},a._engine.ellipse=function(a,b,c,d,e){var f=q("ellipse");a.canvas&&a.canvas.appendChild(f);var g=new z(f,a);return g.attrs={cx:b,cy:c,rx:d,ry:e,fill:"none",stroke:"#000"},g.type="ellipse",q(f,g.attrs),g},a._engine.image=function(a,b,c,d,e,f){var g=q("image");q(g,{x:c,y:d,width:e,height:f,preserveAspectRatio:"none"}),g.setAttributeNS(n,"href",b),a.canvas&&a.canvas.appendChild(g);var h=new z(g,a);return h.attrs={x:c,y:d,width:e,height:f,src:b},h.type="image",h},a._engine.text=function(b,c,d,e){var f=q("text");b.canvas&&b.canvas.appendChild(f);var g=new z(f,b);return g.attrs={x:c,y:d,"text-anchor":"middle",text:e,font:a._availableAttrs.font,stroke:"none",fill:"#000"},g.type="text",w(g,g.attrs),g},a._engine.setSize=function(a,b){return this.width=a||this.width,this.height=b||this.height,this.canvas.setAttribute("width",this.width),this.canvas.setAttribute("height",this.height),this._viewBox&&this.setViewBox.apply(this,this._viewBox),this},a._engine.create=function(){var b=a._getContainer.apply(0,arguments),c=b&&b.container,d=b.x,e=b.y,f=b.width,g=b.height;if(!c)throw new Error("SVG container not found.");var h,i=q("svg"),j="overflow:hidden;";return d=d||0,e=e||0,f=f||512,g=g||342,q(i,{height:g,version:1.1,width:f,xmlns:"http://www.w3.org/2000/svg"}),1==c?(i.style.cssText=j+"position:absolute;left:"+d+"px;top:"+e+"px",a._g.doc.body.appendChild(i),h=1):(i.style.cssText=j+"position:relative",c.firstChild?c.insertBefore(i,c.firstChild):c.appendChild(i)),c=new a._Paper,c.width=f,c.height=g,c.canvas=i,c.clear(),c._left=c._top=0,h&&(c.renderfix=function(){}),c.renderfix(),c},a._engine.setViewBox=function(a,b,c,d,e){k("raphael.setViewBox",this,this._viewBox,[a,b,c,d,e]);var f,h,i=g(c/this.width,d/this.height),j=this.top,l=e?"meet":"xMinYMin";for(null==a?(this._vbSize&&(i=1),delete this._vbSize,f="0 0 "+this.width+m+this.height):(this._vbSize=i,f=a+m+b+m+c+m+d),q(this.canvas,{viewBox:f,preserveAspectRatio:l});i&&j;)h="stroke-width"in j.attrs?j.attrs["stroke-width"]:1,j.attr({"stroke-width":h}),j._.dirty=1,j._.dirtyT=1,j=j.prev;return this._viewBox=[a,b,c,d,!!e],this},a.prototype.renderfix=function(){var a,b=this.canvas,c=b.style;try{a=b.getScreenCTM()||b.createSVGMatrix()}catch(d){a=b.createSVGMatrix()}var e=-a.e%1,f=-a.f%1;(e||f)&&(e&&(this._left=(this._left+e)%1,c.left=this._left+"px"),f&&(this._top=(this._top+f)%1,c.top=this._top+"px"))},a.prototype.clear=function(){a.eve("raphael.clear",this);for(var b=this.canvas;b.firstChild;)b.removeChild(b.firstChild);this.bottom=this.top=null,(this.desc=q("desc")).appendChild(a._g.doc.createTextNode("Created with Rapha\xebl "+a.version)),b.appendChild(this.desc),b.appendChild(this.defs=q("defs"))},a.prototype.remove=function(){k("raphael.remove",this),this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas);for(var b in this)this[b]="function"==typeof this[b]?a._removedFactory(b):null};var B=a.st;for(var C in A)A[b](C)&&!B[b](C)&&(B[C]=function(a){return function(){var b=arguments;return this.forEach(function(c){c[a].apply(c,b)})}}(C))}(window.Raphael),window.Raphael&&window.Raphael.vml&&function(a){var b="hasOwnProperty",c=String,d=parseFloat,e=Math,f=e.round,g=e.max,h=e.min,i=e.abs,j="fill",k=/[, ]+/,l=a.eve,m=" progid:DXImageTransform.Microsoft",n=" ",o="",p={M:"m",L:"l",C:"c",Z:"x",m:"t",l:"r",c:"v",z:"x"},q=/([clmz]),?([^clmz]*)/gi,r=/ progid:\S+Blur\([^\)]+\)/g,s=/-?[^,\s-]+/g,t="position:absolute;left:0;top:0;width:1px;height:1px",u=21600,v={path:1,rect:1,image:1},w={circle:1,ellipse:1},x=function(b){var d=/[ahqstv]/gi,e=a._pathToAbsolute;if(c(b).match(d)&&(e=a._path2curve),d=/[clmz]/g,e==a._pathToAbsolute&&!c(b).match(d)){var g=c(b).replace(q,function(a,b,c){var d=[],e="m"==b.toLowerCase(),g=p[b];return c.replace(s,function(a){e&&2==d.length&&(g+=d+p["m"==b?"l":"L"],d=[]),d.push(f(a*u)) }),g+d});return g}var h,i,j=e(b);g=[];for(var k=0,l=j.length;l>k;k++){h=j[k],i=j[k][0].toLowerCase(),"z"==i&&(i="x");for(var m=1,r=h.length;r>m;m++)i+=f(h[m]*u)+(m!=r-1?",":o);g.push(i)}return g.join(n)},y=function(b,c,d){var e=a.matrix();return e.rotate(-b,.5,.5),{dx:e.x(c,d),dy:e.y(c,d)}},z=function(a,b,c,d,e,f){var g=a._,h=a.matrix,k=g.fillpos,l=a.node,m=l.style,o=1,p="",q=u/b,r=u/c;if(m.visibility="hidden",b&&c){if(l.coordsize=i(q)+n+i(r),m.rotation=f*(0>b*c?-1:1),f){var s=y(f,d,e);d=s.dx,e=s.dy}if(0>b&&(p+="x"),0>c&&(p+=" y")&&(o=-1),m.flip=p,l.coordorigin=d*-q+n+e*-r,k||g.fillsize){var t=l.getElementsByTagName(j);t=t&&t[0],l.removeChild(t),k&&(s=y(f,h.x(k[0],k[1]),h.y(k[0],k[1])),t.position=s.dx*o+n+s.dy*o),g.fillsize&&(t.size=g.fillsize[0]*i(b)+n+g.fillsize[1]*i(c)),l.appendChild(t)}m.visibility="visible"}};a.toString=function(){return"Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl "+this.version};var A=function(a,b,d){for(var e=c(b).toLowerCase().split("-"),f=d?"end":"start",g=e.length,h="classic",i="medium",j="medium";g--;)switch(e[g]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":h=e[g];break;case"wide":case"narrow":j=e[g];break;case"long":case"short":i=e[g]}var k=a.node.getElementsByTagName("stroke")[0];k[f+"arrow"]=h,k[f+"arrowlength"]=i,k[f+"arrowwidth"]=j},B=function(e,i){e.attrs=e.attrs||{};var l=e.node,m=e.attrs,p=l.style,q=v[e.type]&&(i.x!=m.x||i.y!=m.y||i.width!=m.width||i.height!=m.height||i.cx!=m.cx||i.cy!=m.cy||i.rx!=m.rx||i.ry!=m.ry||i.r!=m.r),r=w[e.type]&&(m.cx!=i.cx||m.cy!=i.cy||m.r!=i.r||m.rx!=i.rx||m.ry!=i.ry),s=e;for(var t in i)i[b](t)&&(m[t]=i[t]);if(q&&(m.path=a._getPath[e.type](e),e._.dirty=1),i.href&&(l.href=i.href),i.title&&(l.title=i.title),i.target&&(l.target=i.target),i.cursor&&(p.cursor=i.cursor),"blur"in i&&e.blur(i.blur),(i.path&&"path"==e.type||q)&&(l.path=x(~c(m.path).toLowerCase().indexOf("r")?a._pathToAbsolute(m.path):m.path),"image"==e.type&&(e._.fillpos=[m.x,m.y],e._.fillsize=[m.width,m.height],z(e,1,1,0,0,0))),"transform"in i&&e.transform(i.transform),r){var y=+m.cx,B=+m.cy,D=+m.rx||+m.r||0,E=+m.ry||+m.r||0;l.path=a.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x",f((y-D)*u),f((B-E)*u),f((y+D)*u),f((B+E)*u),f(y*u))}if("clip-rect"in i){var G=c(i["clip-rect"]).split(k);if(4==G.length){G[2]=+G[2]+ +G[0],G[3]=+G[3]+ +G[1];var H=l.clipRect||a._g.doc.createElement("div"),I=H.style;I.clip=a.format("rect({1}px {2}px {3}px {0}px)",G),l.clipRect||(I.position="absolute",I.top=0,I.left=0,I.width=e.paper.width+"px",I.height=e.paper.height+"px",l.parentNode.insertBefore(H,l),H.appendChild(l),l.clipRect=H)}i["clip-rect"]||l.clipRect&&(l.clipRect.style.clip="auto")}if(e.textpath){var J=e.textpath.style;i.font&&(J.font=i.font),i["font-family"]&&(J.fontFamily='"'+i["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g,o)+'"'),i["font-size"]&&(J.fontSize=i["font-size"]),i["font-weight"]&&(J.fontWeight=i["font-weight"]),i["font-style"]&&(J.fontStyle=i["font-style"])}if("arrow-start"in i&&A(s,i["arrow-start"]),"arrow-end"in i&&A(s,i["arrow-end"],1),null!=i.opacity||null!=i["stroke-width"]||null!=i.fill||null!=i.src||null!=i.stroke||null!=i["stroke-width"]||null!=i["stroke-opacity"]||null!=i["fill-opacity"]||null!=i["stroke-dasharray"]||null!=i["stroke-miterlimit"]||null!=i["stroke-linejoin"]||null!=i["stroke-linecap"]){var K=l.getElementsByTagName(j),L=!1;if(K=K&&K[0],!K&&(L=K=F(j)),"image"==e.type&&i.src&&(K.src=i.src),i.fill&&(K.on=!0),(null==K.on||"none"==i.fill||null===i.fill)&&(K.on=!1),K.on&&i.fill){var M=c(i.fill).match(a._ISURL);if(M){K.parentNode==l&&l.removeChild(K),K.rotate=!0,K.src=M[1],K.type="tile";var N=e.getBBox(1);K.position=N.x+n+N.y,e._.fillpos=[N.x,N.y],a._preload(M[1],function(){e._.fillsize=[this.offsetWidth,this.offsetHeight]})}else K.color=a.getRGB(i.fill).hex,K.src=o,K.type="solid",a.getRGB(i.fill).error&&(s.type in{circle:1,ellipse:1}||"r"!=c(i.fill).charAt())&&C(s,i.fill,K)&&(m.fill="none",m.gradient=i.fill,K.rotate=!1)}if("fill-opacity"in i||"opacity"in i){var O=((+m["fill-opacity"]+1||2)-1)*((+m.opacity+1||2)-1)*((+a.getRGB(i.fill).o+1||2)-1);O=h(g(O,0),1),K.opacity=O,K.src&&(K.color="none")}l.appendChild(K);var P=l.getElementsByTagName("stroke")&&l.getElementsByTagName("stroke")[0],Q=!1;!P&&(Q=P=F("stroke")),(i.stroke&&"none"!=i.stroke||i["stroke-width"]||null!=i["stroke-opacity"]||i["stroke-dasharray"]||i["stroke-miterlimit"]||i["stroke-linejoin"]||i["stroke-linecap"])&&(P.on=!0),("none"==i.stroke||null===i.stroke||null==P.on||0==i.stroke||0==i["stroke-width"])&&(P.on=!1);var R=a.getRGB(i.stroke);P.on&&i.stroke&&(P.color=R.hex),O=((+m["stroke-opacity"]+1||2)-1)*((+m.opacity+1||2)-1)*((+R.o+1||2)-1);var S=.75*(d(i["stroke-width"])||1);if(O=h(g(O,0),1),null==i["stroke-width"]&&(S=m["stroke-width"]),i["stroke-width"]&&(P.weight=S),S&&1>S&&(O*=S)&&(P.weight=1),P.opacity=O,i["stroke-linejoin"]&&(P.joinstyle=i["stroke-linejoin"]||"miter"),P.miterlimit=i["stroke-miterlimit"]||8,i["stroke-linecap"]&&(P.endcap="butt"==i["stroke-linecap"]?"flat":"square"==i["stroke-linecap"]?"square":"round"),i["stroke-dasharray"]){var T={"-":"shortdash",".":"shortdot","-.":"shortdashdot","-..":"shortdashdotdot",". ":"dot","- ":"dash","--":"longdash","- .":"dashdot","--.":"longdashdot","--..":"longdashdotdot"};P.dashstyle=T[b](i["stroke-dasharray"])?T[i["stroke-dasharray"]]:o}Q&&l.appendChild(P)}if("text"==s.type){s.paper.canvas.style.display=o;var U=s.paper.span,V=100,W=m.font&&m.font.match(/\d+(?:\.\d*)?(?=px)/);p=U.style,m.font&&(p.font=m.font),m["font-family"]&&(p.fontFamily=m["font-family"]),m["font-weight"]&&(p.fontWeight=m["font-weight"]),m["font-style"]&&(p.fontStyle=m["font-style"]),W=d(m["font-size"]||W&&W[0])||10,p.fontSize=W*V+"px",s.textpath.string&&(U.innerHTML=c(s.textpath.string).replace(/</g,"&#60;").replace(/&/g,"&#38;").replace(/\n/g,"<br>"));var X=U.getBoundingClientRect();s.W=m.w=(X.right-X.left)/V,s.H=m.h=(X.bottom-X.top)/V,s.X=m.x,s.Y=m.y+s.H/2,("x"in i||"y"in i)&&(s.path.v=a.format("m{0},{1}l{2},{1}",f(m.x*u),f(m.y*u),f(m.x*u)+1));for(var Y=["x","y","text","font","font-family","font-weight","font-style","font-size"],Z=0,$=Y.length;$>Z;Z++)if(Y[Z]in i){s._.dirty=1;break}switch(m["text-anchor"]){case"start":s.textpath.style["v-text-align"]="left",s.bbx=s.W/2;break;case"end":s.textpath.style["v-text-align"]="right",s.bbx=-s.W/2;break;default:s.textpath.style["v-text-align"]="center",s.bbx=0}s.textpath.style["v-text-kern"]=!0}},C=function(b,f,g){b.attrs=b.attrs||{};var h=(b.attrs,Math.pow),i="linear",j=".5 .5";if(b.attrs.gradient=f,f=c(f).replace(a._radial_gradient,function(a,b,c){return i="radial",b&&c&&(b=d(b),c=d(c),h(b-.5,2)+h(c-.5,2)>.25&&(c=e.sqrt(.25-h(b-.5,2))*(2*(c>.5)-1)+.5),j=b+n+c),o}),f=f.split(/\s*\-\s*/),"linear"==i){var k=f.shift();if(k=-d(k),isNaN(k))return null}var l=a._parseDots(f);if(!l)return null;if(b=b.shape||b.node,l.length){b.removeChild(g),g.on=!0,g.method="none",g.color=l[0].color,g.color2=l[l.length-1].color;for(var m=[],p=0,q=l.length;q>p;p++)l[p].offset&&m.push(l[p].offset+n+l[p].color);g.colors=m.length?m.join():"0% "+g.color,"radial"==i?(g.type="gradientTitle",g.focus="100%",g.focussize="0 0",g.focusposition=j,g.angle=0):(g.type="gradient",g.angle=(270-k)%360),b.appendChild(g)}return 1},D=function(b,c){this[0]=this.node=b,b.raphael=!0,this.id=a._oid++,b.raphaelid=this.id,this.X=0,this.Y=0,this.attrs={},this.paper=c,this.matrix=a.matrix(),this._={transform:[],sx:1,sy:1,dx:0,dy:0,deg:0,dirty:1,dirtyT:1},!c.bottom&&(c.bottom=this),this.prev=c.top,c.top&&(c.top.next=this),c.top=this,this.next=null},E=a.el;D.prototype=E,E.constructor=D,E.transform=function(b){if(null==b)return this._.transform;var d,e=this.paper._viewBoxShift,f=e?"s"+[e.scale,e.scale]+"-1-1t"+[e.dx,e.dy]:o;e&&(d=b=c(b).replace(/\.{3}|\u2026/g,this._.transform||o)),a._extractTransform(this,f+b);var g,h=this.matrix.clone(),i=this.skew,j=this.node,k=~c(this.attrs.fill).indexOf("-"),l=!c(this.attrs.fill).indexOf("url(");if(h.translate(-.5,-.5),l||k||"image"==this.type)if(i.matrix="1 0 0 1",i.offset="0 0",g=h.split(),k&&g.noRotation||!g.isSimple){j.style.filter=h.toFilter();var m=this.getBBox(),p=this.getBBox(1),q=m.x-p.x,r=m.y-p.y;j.coordorigin=q*-u+n+r*-u,z(this,1,1,q,r,0)}else j.style.filter=o,z(this,g.scalex,g.scaley,g.dx,g.dy,g.rotate);else j.style.filter=o,i.matrix=c(h),i.offset=h.offset();return d&&(this._.transform=d),this},E.rotate=function(a,b,e){if(this.removed)return this;if(null!=a){if(a=c(a).split(k),a.length-1&&(b=d(a[1]),e=d(a[2])),a=d(a[0]),null==e&&(b=e),null==b||null==e){var f=this.getBBox(1);b=f.x+f.width/2,e=f.y+f.height/2}return this._.dirtyT=1,this.transform(this._.transform.concat([["r",a,b,e]])),this}},E.translate=function(a,b){return this.removed?this:(a=c(a).split(k),a.length-1&&(b=d(a[1])),a=d(a[0])||0,b=+b||0,this._.bbox&&(this._.bbox.x+=a,this._.bbox.y+=b),this.transform(this._.transform.concat([["t",a,b]])),this)},E.scale=function(a,b,e,f){if(this.removed)return this;if(a=c(a).split(k),a.length-1&&(b=d(a[1]),e=d(a[2]),f=d(a[3]),isNaN(e)&&(e=null),isNaN(f)&&(f=null)),a=d(a[0]),null==b&&(b=a),null==f&&(e=f),null==e||null==f)var g=this.getBBox(1);return e=null==e?g.x+g.width/2:e,f=null==f?g.y+g.height/2:f,this.transform(this._.transform.concat([["s",a,b,e,f]])),this._.dirtyT=1,this},E.hide=function(){return!this.removed&&(this.node.style.display="none"),this},E.show=function(){return!this.removed&&(this.node.style.display=o),this},E._getBBox=function(){return this.removed?{}:{x:this.X+(this.bbx||0)-this.W/2,y:this.Y-this.H,width:this.W,height:this.H}},E.remove=function(){if(!this.removed&&this.node.parentNode){this.paper.__set__&&this.paper.__set__.exclude(this),a.eve.unbind("raphael.*.*."+this.id),a._tear(this,this.paper),this.node.parentNode.removeChild(this.node),this.shape&&this.shape.parentNode.removeChild(this.shape);for(var b in this)this[b]="function"==typeof this[b]?a._removedFactory(b):null;this.removed=!0}},E.attr=function(c,d){if(this.removed)return this;if(null==c){var e={};for(var f in this.attrs)this.attrs[b](f)&&(e[f]=this.attrs[f]);return e.gradient&&"none"==e.fill&&(e.fill=e.gradient)&&delete e.gradient,e.transform=this._.transform,e}if(null==d&&a.is(c,"string")){if(c==j&&"none"==this.attrs.fill&&this.attrs.gradient)return this.attrs.gradient;for(var g=c.split(k),h={},i=0,m=g.length;m>i;i++)c=g[i],h[c]=c in this.attrs?this.attrs[c]:a.is(this.paper.customAttributes[c],"function")?this.paper.customAttributes[c].def:a._availableAttrs[c];return m-1?h:h[g[0]]}if(this.attrs&&null==d&&a.is(c,"array")){for(h={},i=0,m=c.length;m>i;i++)h[c[i]]=this.attr(c[i]);return h}var n;null!=d&&(n={},n[c]=d),null==d&&a.is(c,"object")&&(n=c);for(var o in n)l("raphael.attr."+o+"."+this.id,this,n[o]);if(n){for(o in this.paper.customAttributes)if(this.paper.customAttributes[b](o)&&n[b](o)&&a.is(this.paper.customAttributes[o],"function")){var p=this.paper.customAttributes[o].apply(this,[].concat(n[o]));this.attrs[o]=n[o];for(var q in p)p[b](q)&&(n[q]=p[q])}n.text&&"text"==this.type&&(this.textpath.string=n.text),B(this,n)}return this},E.toFront=function(){return!this.removed&&this.node.parentNode.appendChild(this.node),this.paper&&this.paper.top!=this&&a._tofront(this,this.paper),this},E.toBack=function(){return this.removed?this:(this.node.parentNode.firstChild!=this.node&&(this.node.parentNode.insertBefore(this.node,this.node.parentNode.firstChild),a._toback(this,this.paper)),this)},E.insertAfter=function(b){return this.removed?this:(b.constructor==a.st.constructor&&(b=b[b.length-1]),b.node.nextSibling?b.node.parentNode.insertBefore(this.node,b.node.nextSibling):b.node.parentNode.appendChild(this.node),a._insertafter(this,b,this.paper),this)},E.insertBefore=function(b){return this.removed?this:(b.constructor==a.st.constructor&&(b=b[0]),b.node.parentNode.insertBefore(this.node,b.node),a._insertbefore(this,b,this.paper),this)},E.blur=function(b){var c=this.node.runtimeStyle,d=c.filter;d=d.replace(r,o),0!==+b?(this.attrs.blur=b,c.filter=d+n+m+".Blur(pixelradius="+(+b||1.5)+")",c.margin=a.format("-{0}px 0 0 -{0}px",f(+b||1.5))):(c.filter=d,c.margin=0,delete this.attrs.blur)},a._engine.path=function(a,b){var c=F("shape");c.style.cssText=t,c.coordsize=u+n+u,c.coordorigin=b.coordorigin;var d=new D(c,b),e={fill:"none",stroke:"#000"};a&&(e.path=a),d.type="path",d.path=[],d.Path=o,B(d,e),b.canvas.appendChild(c);var f=F("skew");return f.on=!0,c.appendChild(f),d.skew=f,d.transform(o),d},a._engine.rect=function(b,c,d,e,f,g){var h=a._rectPath(c,d,e,f,g),i=b.path(h),j=i.attrs;return i.X=j.x=c,i.Y=j.y=d,i.W=j.width=e,i.H=j.height=f,j.r=g,j.path=h,i.type="rect",i},a._engine.ellipse=function(a,b,c,d,e){{var f=a.path();f.attrs}return f.X=b-d,f.Y=c-e,f.W=2*d,f.H=2*e,f.type="ellipse",B(f,{cx:b,cy:c,rx:d,ry:e}),f},a._engine.circle=function(a,b,c,d){{var e=a.path();e.attrs}return e.X=b-d,e.Y=c-d,e.W=e.H=2*d,e.type="circle",B(e,{cx:b,cy:c,r:d}),e},a._engine.image=function(b,c,d,e,f,g){var h=a._rectPath(d,e,f,g),i=b.path(h).attr({stroke:"none"}),k=i.attrs,l=i.node,m=l.getElementsByTagName(j)[0];return k.src=c,i.X=k.x=d,i.Y=k.y=e,i.W=k.width=f,i.H=k.height=g,k.path=h,i.type="image",m.parentNode==l&&l.removeChild(m),m.rotate=!0,m.src=c,m.type="tile",i._.fillpos=[d,e],i._.fillsize=[f,g],l.appendChild(m),z(i,1,1,0,0,0),i},a._engine.text=function(b,d,e,g){var h=F("shape"),i=F("path"),j=F("textpath");d=d||0,e=e||0,g=g||"",i.v=a.format("m{0},{1}l{2},{1}",f(d*u),f(e*u),f(d*u)+1),i.textpathok=!0,j.string=c(g),j.on=!0,h.style.cssText=t,h.coordsize=u+n+u,h.coordorigin="0 0";var k=new D(h,b),l={fill:"#000",stroke:"none",font:a._availableAttrs.font,text:g};k.shape=h,k.path=i,k.textpath=j,k.type="text",k.attrs.text=c(g),k.attrs.x=d,k.attrs.y=e,k.attrs.w=1,k.attrs.h=1,B(k,l),h.appendChild(j),h.appendChild(i),b.canvas.appendChild(h);var m=F("skew");return m.on=!0,h.appendChild(m),k.skew=m,k.transform(o),k},a._engine.setSize=function(b,c){var d=this.canvas.style;return this.width=b,this.height=c,b==+b&&(b+="px"),c==+c&&(c+="px"),d.width=b,d.height=c,d.clip="rect(0 "+b+" "+c+" 0)",this._viewBox&&a._engine.setViewBox.apply(this,this._viewBox),this},a._engine.setViewBox=function(b,c,d,e,f){a.eve("raphael.setViewBox",this,this._viewBox,[b,c,d,e,f]);var h,i,j=this.width,k=this.height,l=1/g(d/j,e/k);return f&&(h=k/e,i=j/d,j>d*h&&(b-=(j-d*h)/2/h),k>e*i&&(c-=(k-e*i)/2/i)),this._viewBox=[b,c,d,e,!!f],this._viewBoxShift={dx:-b,dy:-c,scale:l},this.forEach(function(a){a.transform("...")}),this};var F;a._engine.initWin=function(a){var b=a.document;b.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{!b.namespaces.rvml&&b.namespaces.add("rvml","urn:schemas-microsoft-com:vml"),F=function(a){return b.createElement("<rvml:"+a+' class="rvml">')}}catch(c){F=function(a){return b.createElement("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}},a._engine.initWin(a._g.win),a._engine.create=function(){var b=a._getContainer.apply(0,arguments),c=b.container,d=b.height,e=b.width,f=b.x,g=b.y;if(!c)throw new Error("VML container not found.");var h=new a._Paper,i=h.canvas=a._g.doc.createElement("div"),j=i.style;return f=f||0,g=g||0,e=e||512,d=d||342,h.width=e,h.height=d,e==+e&&(e+="px"),d==+d&&(d+="px"),h.coordsize=1e3*u+n+1e3*u,h.coordorigin="0 0",h.span=a._g.doc.createElement("span"),h.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;",i.appendChild(h.span),j.cssText=a.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",e,d),1==c?(a._g.doc.body.appendChild(i),j.left=f+"px",j.top=g+"px",j.position="absolute"):c.firstChild?c.insertBefore(i,c.firstChild):c.appendChild(i),h.renderfix=function(){},h},a.prototype.clear=function(){a.eve("raphael.clear",this),this.canvas.innerHTML=o,this.span=a._g.doc.createElement("span"),this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;",this.canvas.appendChild(this.span),this.bottom=this.top=null},a.prototype.remove=function(){a.eve("raphael.remove",this),this.canvas.parentNode.removeChild(this.canvas);for(var b in this)this[b]="function"==typeof this[b]?a._removedFactory(b):null;return!0};var G=a.st;for(var H in E)E[b](H)&&!G[b](H)&&(G[H]=function(a){return function(){var b=arguments;return this.forEach(function(c){c[a].apply(c,b)})}}(H))}(window.Raphael),function(a,b){function c(b,c){var e=b.nodeName.toLowerCase();if("area"===e){var f,g=b.parentNode,h=g.name;return b.href&&h&&"map"===g.nodeName.toLowerCase()?(f=a("img[usemap=#"+h+"]")[0],!!f&&d(f)):!1}return(/input|select|textarea|button|object/.test(e)?!b.disabled:"a"==e?b.href||c:c)&&d(b)}function d(b){return!a(b).parents().andSelf().filter(function(){return"hidden"===a.curCSS(this,"visibility")||a.expr.filters.hidden(this)}).length}a.ui=a.ui||{},a.ui.version||(a.extend(a.ui,{version:"1.8.24",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(b,c){return"number"==typeof b?this.each(function(){var d=this;setTimeout(function(){a(d).focus(),c&&c.call(d)},b)}):this._focus.apply(this,arguments)},scrollParent:function(){var b;return b=a.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.curCSS(this,"position",1))&&/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0),/fixed/.test(this.css("position"))||!b.length?a(document):b},zIndex:function(c){if(c!==b)return this.css("zIndex",c);if(this.length)for(var d,e,f=a(this[0]);f.length&&f[0]!==document;){if(d=f.css("position"),("absolute"===d||"relative"===d||"fixed"===d)&&(e=parseInt(f.css("zIndex"),10),!isNaN(e)&&0!==e))return e;f=f.parent()}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),a("<a>").outerWidth(1).jquery||a.each(["Width","Height"],function(c,d){function e(b,c,d,e){return a.each(f,function(){c-=parseFloat(a.curCSS(b,"padding"+this,!0))||0,d&&(c-=parseFloat(a.curCSS(b,"border"+this+"Width",!0))||0),e&&(c-=parseFloat(a.curCSS(b,"margin"+this,!0))||0)}),c}var f="Width"===d?["Left","Right"]:["Top","Bottom"],g=d.toLowerCase(),h={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){return c===b?h["inner"+d].call(this):this.each(function(){a(this).css(g,e(this,c)+"px")})},a.fn["outer"+d]=function(b,c){return"number"!=typeof b?h["outer"+d].call(this,b):this.each(function(){a(this).css(g,e(this,b,!0,c)+"px")})}}),a.extend(a.expr[":"],{data:a.expr.createPseudo?a.expr.createPseudo(function(b){return function(c){return!!a.data(c,b)}}):function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return c(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var d=a.attr(b,"tabindex"),e=isNaN(d);return(e||d>=0)&&c(b,!e)}}),a(function(){var b=document.body,c=b.appendChild(c=document.createElement("div"));c.offsetHeight,a.extend(c.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),a.support.minHeight=100===c.offsetHeight,a.support.selectstart="onselectstart"in c,b.removeChild(c).style.display="none"}),a.curCSS||(a.curCSS=a.css),a.extend(a.ui,{plugin:{add:function(b,c,d){var e=a.ui[b].prototype;for(var f in d)e.plugins[f]=e.plugins[f]||[],e.plugins[f].push([c,d[f]])},call:function(a,b,c){var d=a.plugins[b];if(d&&a.element[0].parentNode)for(var e=0;e<d.length;e++)a.options[d[e][0]]&&d[e][1].apply(a.element,c)}},contains:function(a,b){return document.compareDocumentPosition?16&a.compareDocumentPosition(b):a!==b&&a.contains(b)},hasScroll:function(b,c){if("hidden"===a(b).css("overflow"))return!1;var d=c&&"left"===c?"scrollLeft":"scrollTop",e=!1;return b[d]>0?!0:(b[d]=1,e=b[d]>0,b[d]=0,e)},isOverAxis:function(a,b,c){return a>b&&b+c>a},isOver:function(b,c,d,e,f,g){return a.ui.isOverAxis(b,d,f)&&a.ui.isOverAxis(c,e,g)}}))}(jQuery),function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d,e=0;null!=(d=b[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e,f=b.split(".")[0];b=b.split(".")[1],e=f+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][e]=function(c){return!!a.data(c,b)},a[f]=a[f]||{},a[f][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[f][b].prototype=a.extend(!0,g,{namespace:f,widgetName:b,widgetEventPrefix:a[f][b].prototype.widgetEventPrefix||b,widgetBaseClass:e},d),a.widget.bridge(b,a[f][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f="string"==typeof e,g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&"_"===e.charAt(0)?h:(this.each(f?function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;return f!==d&&f!==b?(h=f,!1):void 0}:function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(0===arguments.length)return a.extend({},this.options);if("string"==typeof c){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,"disabled"===a&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];if(d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}}(jQuery),function(a){var b=!1;a(document).mouseup(function(){b=!1}),a.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var b=this;this.element.bind("mousedown."+this.widgetName,function(a){return b._mouseDown(a)}).bind("click."+this.widgetName,function(c){return!0===a.data(c.target,b.widgetName+".preventClickEvent")?(a.removeData(c.target,b.widgetName+".preventClickEvent"),c.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(c){if(!b){this._mouseStarted&&this._mouseUp(c),this._mouseDownEvent=c;var d=this,e=1==c.which,f="string"==typeof this.options.cancel&&c.target.nodeName?a(c.target).closest(this.options.cancel).length:!1;return e&&!f&&this._mouseCapture(c)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){d.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(c)&&this._mouseDelayMet(c)&&(this._mouseStarted=this._mouseStart(c)!==!1,!this._mouseStarted)?(c.preventDefault(),!0):(!0===a.data(c.target,this.widgetName+".preventClickEvent")&&a.removeData(c.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(a){return d._mouseMove(a)},this._mouseUpDelegate=function(a){return d._mouseUp(a)},a(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),c.preventDefault(),b=!0,!0)):!0}},_mouseMove:function(b){return!a.browser.msie||document.documentMode>=9||b.button?this._mouseStarted?(this._mouseDrag(b),b.preventDefault()):(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,b)!==!1,this._mouseStarted?this._mouseDrag(b):this._mouseUp(b)),!this._mouseStarted):this._mouseUp(b)},_mouseUp:function(b){return a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,b.target==this._mouseDownEvent.target&&a.data(b.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(b)),!1},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})}(jQuery),function(a){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){"original"!=this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},destroy:function(){return this.element.data("draggable")?(this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy(),this):void 0},_mouseCapture:function(b){var c=this.options;return this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(b),this.handle?(c.iframeFix&&a(c.iframeFix===!0?"iframe":c.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(a(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(b){var c=this.options;return this.helper=this._createHelper(b),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),a.ui.ddmanager&&(a.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,c.cursorAt&&this._adjustOffsetFromHelper(c.cursorAt),c.containment&&this._setContainment(),this._trigger("start",b)===!1?(this._clear(),!1):(this._cacheHelperProportions(),a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this._mouseDrag(b,!0),a.ui.ddmanager&&a.ui.ddmanager.dragStart(this,b),!0)},_mouseDrag:function(b,c){if(this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute"),!c){var d=this._uiHash();if(this._trigger("drag",b,d)===!1)return this._mouseUp({}),!1;this.position=d.position}return this.options.axis&&"y"==this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"==this.options.axis||(this.helper[0].style.top=this.position.top+"px"),a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),!1},_mouseStop:function(b){var c=!1;a.ui.ddmanager&&!this.options.dropBehaviour&&(c=a.ui.ddmanager.drop(this,b)),this.dropped&&(c=this.dropped,this.dropped=!1);for(var d=this.element[0],e=!1;d&&(d=d.parentNode);)d==document&&(e=!0);if(!e&&"original"===this.options.helper)return!1;if("invalid"==this.options.revert&&!c||"valid"==this.options.revert&&c||this.options.revert===!0||a.isFunction(this.options.revert)&&this.options.revert.call(this.element,c)){var f=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){f._trigger("stop",b)!==!1&&f._clear()})}else this._trigger("stop",b)!==!1&&this._clear();return!1},_mouseUp:function(b){return a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),a.ui.ddmanager&&a.ui.ddmanager.dragStop(this,b),a.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(b){var c=this.options.handle&&a(this.options.handle,this.element).length?!1:!0;return a(this.options.handle,this.element).find("*").andSelf().each(function(){this==b.target&&(c=!0)}),c},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b])):"clone"==c.helper?this.element.clone().removeAttr("id"):this.element;return d.parents("body").length||d.appendTo("parent"==c.appendTo?this.element[0].parentNode:c.appendTo),d[0]==this.element[0]||/(fixed|absolute)/.test(d.css("position"))||d.css("position","absolute"),d},_adjustOffsetFromHelper:function(b){"string"==typeof b&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();return"absolute"==this.cssPosition&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&"html"==this.offsetParent[0].tagName.toLowerCase()&&a.browser.msie)&&(b={top:0,left:0}),{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"==this.cssPosition){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()} }return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;if("parent"==b.containment&&(b.containment=this.helper[0].parentNode),("document"==b.containment||"window"==b.containment)&&(this.containment=["document"==b.containment?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,"document"==b.containment?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,("document"==b.containment?0:a(window).scrollLeft())+a("document"==b.containment?document:window).width()-this.helperProportions.width-this.margins.left,("document"==b.containment?0:a(window).scrollTop())+(a("document"==b.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(b.containment)||b.containment.constructor==Array)b.containment.constructor==Array&&(this.containment=b.containment);else{var c=a(b.containment),d=c[0];if(!d)return;var e=(c.offset(),"hidden"!=a(d).css("overflow"));this.containment=[(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0),(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0),(e?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=c}},_convertPositionTo:function(b,c){c||(c=this.position);var d="absolute"==b?1:-1,e=(this.options,"absolute"!=this.cssPosition||this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent),f=/(html|body)/i.test(e[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&a.browser.version<526&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollTop():f?0:e.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&a.browser.version<526&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollLeft():f?0:e.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d="absolute"!=this.cssPosition||this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,e=/(html|body)/i.test(d[0].tagName),f=b.pageX,g=b.pageY;if(this.originalPosition){var h;if(this.containment){if(this.relative_container){var i=this.relative_container.offset();h=[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]}else h=this.containment;b.pageX-this.offset.click.left<h[0]&&(f=h[0]+this.offset.click.left),b.pageY-this.offset.click.top<h[1]&&(g=h[1]+this.offset.click.top),b.pageX-this.offset.click.left>h[2]&&(f=h[2]+this.offset.click.left),b.pageY-this.offset.click.top>h[3]&&(g=h[3]+this.offset.click.top)}if(c.grid){var j=c.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1]:this.originalPageY;g=h&&(j-this.offset.click.top<h[1]||j-this.offset.click.top>h[3])?j-this.offset.click.top<h[1]?j+c.grid[1]:j-c.grid[1]:j;var k=c.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0]:this.originalPageX;f=h&&(k-this.offset.click.left<h[0]||k-this.offset.click.left>h[2])?k-this.offset.click.left<h[0]?k+c.grid[0]:k-c.grid[0]:k}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]==this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(b,c,d){return d=d||this._uiHash(),a.ui.plugin.call(this,b,[c,d]),"drag"==b&&(this.positionAbs=this._convertPositionTo("absolute")),a.Widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),a.extend(a.ui.draggable,{version:"1.8.24"}),a.ui.plugin.add("draggable","connectToSortable",{start:function(b,c){var d=a(this).data("draggable"),e=d.options,f=a.extend({},c,{item:d.element});d.sortables=[],a(e.connectToSortable).each(function(){var c=a.data(this,"sortable");c&&!c.options.disabled&&(d.sortables.push({instance:c,shouldRevert:c.options.revert}),c.refreshPositions(),c._trigger("activate",b,f))})},stop:function(b,c){var d=a(this).data("draggable"),e=a.extend({},c,{item:d.element});a.each(d.sortables,function(){this.instance.isOver?(this.instance.isOver=0,d.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(b),this.instance.options.helper=this.instance.options._helper,"original"==d.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",b,e))})},drag:function(b,c){var d=a(this).data("draggable"),e=this;a.each(d.sortables,function(){this.instance.positionAbs=d.positionAbs,this.instance.helperProportions=d.helperProportions,this.instance.offset.click=d.offset.click,this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=a(e).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return c.helper[0]},b.target=this.instance.currentItem[0],this.instance._mouseCapture(b,!0),this.instance._mouseStart(b,!0,!0),this.instance.offset.click.top=d.offset.click.top,this.instance.offset.click.left=d.offset.click.left,this.instance.offset.parent.left-=d.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=d.offset.parent.top-this.instance.offset.parent.top,d._trigger("toSortable",b),d.dropped=this.instance.element,d.currentItem=d.element,this.instance.fromOutside=d),this.instance.currentItem&&this.instance._mouseDrag(b)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",b,this.instance._uiHash(this.instance)),this.instance._mouseStop(b,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),d._trigger("fromSortable",b),d.dropped=!1)})}}),a.ui.plugin.add("draggable","cursor",{start:function(){var b=a("body"),c=a(this).data("draggable").options;b.css("cursor")&&(c._cursor=b.css("cursor")),b.css("cursor",c.cursor)},stop:function(){var b=a(this).data("draggable").options;b._cursor&&a("body").css("cursor",b._cursor)}}),a.ui.plugin.add("draggable","opacity",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("opacity")&&(e._opacity=d.css("opacity")),d.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;d._opacity&&a(c.helper).css("opacity",d._opacity)}}),a.ui.plugin.add("draggable","scroll",{start:function(){var b=a(this).data("draggable");b.scrollParent[0]!=document&&"HTML"!=b.scrollParent[0].tagName&&(b.overflowOffset=b.scrollParent.offset())},drag:function(b){var c=a(this).data("draggable"),d=c.options,e=!1;c.scrollParent[0]!=document&&"HTML"!=c.scrollParent[0].tagName?(d.axis&&"x"==d.axis||(c.overflowOffset.top+c.scrollParent[0].offsetHeight-b.pageY<d.scrollSensitivity?c.scrollParent[0].scrollTop=e=c.scrollParent[0].scrollTop+d.scrollSpeed:b.pageY-c.overflowOffset.top<d.scrollSensitivity&&(c.scrollParent[0].scrollTop=e=c.scrollParent[0].scrollTop-d.scrollSpeed)),d.axis&&"y"==d.axis||(c.overflowOffset.left+c.scrollParent[0].offsetWidth-b.pageX<d.scrollSensitivity?c.scrollParent[0].scrollLeft=e=c.scrollParent[0].scrollLeft+d.scrollSpeed:b.pageX-c.overflowOffset.left<d.scrollSensitivity&&(c.scrollParent[0].scrollLeft=e=c.scrollParent[0].scrollLeft-d.scrollSpeed))):(d.axis&&"x"==d.axis||(b.pageY-a(document).scrollTop()<d.scrollSensitivity?e=a(document).scrollTop(a(document).scrollTop()-d.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<d.scrollSensitivity&&(e=a(document).scrollTop(a(document).scrollTop()+d.scrollSpeed))),d.axis&&"y"==d.axis||(b.pageX-a(document).scrollLeft()<d.scrollSensitivity?e=a(document).scrollLeft(a(document).scrollLeft()-d.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<d.scrollSensitivity&&(e=a(document).scrollLeft(a(document).scrollLeft()+d.scrollSpeed)))),e!==!1&&a.ui.ddmanager&&!d.dropBehaviour&&a.ui.ddmanager.prepareOffsets(c,b)}}),a.ui.plugin.add("draggable","snap",{start:function(){var b=a(this).data("draggable"),c=b.options;b.snapElements=[],a(c.snap.constructor!=String?c.snap.items||":data(draggable)":c.snap).each(function(){var c=a(this),d=c.offset();this!=b.element[0]&&b.snapElements.push({item:this,width:c.outerWidth(),height:c.outerHeight(),top:d.top,left:d.left})})},drag:function(b,c){for(var d=a(this).data("draggable"),e=d.options,f=e.snapTolerance,g=c.offset.left,h=g+d.helperProportions.width,i=c.offset.top,j=i+d.helperProportions.height,k=d.snapElements.length-1;k>=0;k--){var l=d.snapElements[k].left,m=l+d.snapElements[k].width,n=d.snapElements[k].top,o=n+d.snapElements[k].height;if(g>l-f&&m+f>g&&i>n-f&&o+f>i||g>l-f&&m+f>g&&j>n-f&&o+f>j||h>l-f&&m+f>h&&i>n-f&&o+f>i||h>l-f&&m+f>h&&j>n-f&&o+f>j){if("inner"!=e.snapMode){var p=Math.abs(n-j)<=f,q=Math.abs(o-i)<=f,r=Math.abs(l-h)<=f,s=Math.abs(m-g)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n-d.helperProportions.height,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l-d.helperProportions.width}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m}).left-d.margins.left)}var t=p||q||r||s;if("outer"!=e.snapMode){var p=Math.abs(n-i)<=f,q=Math.abs(o-j)<=f,r=Math.abs(l-g)<=f,s=Math.abs(m-h)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o-d.helperProportions.height,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m-d.helperProportions.width}).left-d.margins.left)}!d.snapElements[k].snapping&&(p||q||r||s||t)&&d.options.snap.snap&&d.options.snap.snap.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=p||q||r||s||t}else d.snapElements[k].snapping&&d.options.snap.release&&d.options.snap.release.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=!1}}}),a.ui.plugin.add("draggable","stack",{start:function(){var b=a(this).data("draggable").options,c=a.makeArray(a(b.stack)).sort(function(b,c){return(parseInt(a(b).css("zIndex"),10)||0)-(parseInt(a(c).css("zIndex"),10)||0)});if(c.length){var d=parseInt(c[0].style.zIndex)||0;a(c).each(function(a){this.style.zIndex=d+a}),this[0].style.zIndex=d+c.length}}}),a.ui.plugin.add("draggable","zIndex",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("zIndex")&&(e._zIndex=d.css("zIndex")),d.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;d._zIndex&&a(c.helper).css("zIndex",d._zIndex)}})}(jQuery),function(a){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var a=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===a.axis||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},destroy:function(){a.Widget.prototype.destroy.call(this),this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--)this.items[b].item.removeData(this.widgetName+"-item");return this},_setOption:function(b,c){"disabled"===b?(this.options[b]=c,this.widget()[c?"addClass":"removeClass"]("ui-sortable-disabled")):a.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(b,c){var d=this;if(this.reverting)return!1;if(this.options.disabled||"static"==this.options.type)return!1;this._refreshItems(b);{var e=null,f=this;a(b.target).parents().each(function(){return a.data(this,d.widgetName+"-item")==f?(e=a(this),!1):void 0})}if(a.data(b.target,d.widgetName+"-item")==f&&(e=a(b.target)),!e)return!1;if(this.options.handle&&!c){var g=!1;if(a(this.options.handle,e).find("*").andSelf().each(function(){this==b.target&&(g=!0)}),!g)return!1}return this.currentItem=e,this._removeCurrentsFromItems(),!0},_mouseStart:function(b,c,d){var e=this.options,f=this;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(b),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),e.containment&&this._setContainment(),e.cursor&&(a("body").css("cursor")&&(this._storedCursor=a("body").css("cursor")),a("body").css("cursor",e.cursor)),e.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",e.opacity)),e.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",e.zIndex)),this.scrollParent[0]!=document&&"HTML"!=this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",b,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!d)for(var g=this.containers.length-1;g>=0;g--)this.containers[g]._trigger("activate",b,f._uiHash(this));return a.ui.ddmanager&&(a.ui.ddmanager.current=this),a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(b),!0},_mouseDrag:function(b){if(this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll){var c=this.options,d=!1;this.scrollParent[0]!=document&&"HTML"!=this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-b.pageY<c.scrollSensitivity?this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop+c.scrollSpeed:b.pageY-this.overflowOffset.top<c.scrollSensitivity&&(this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop-c.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-b.pageX<c.scrollSensitivity?this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft+c.scrollSpeed:b.pageX-this.overflowOffset.left<c.scrollSensitivity&&(this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft-c.scrollSpeed)):(b.pageY-a(document).scrollTop()<c.scrollSensitivity?d=a(document).scrollTop(a(document).scrollTop()-c.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<c.scrollSensitivity&&(d=a(document).scrollTop(a(document).scrollTop()+c.scrollSpeed)),b.pageX-a(document).scrollLeft()<c.scrollSensitivity?d=a(document).scrollLeft(a(document).scrollLeft()-c.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<c.scrollSensitivity&&(d=a(document).scrollLeft(a(document).scrollLeft()+c.scrollSpeed))),d!==!1&&a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b)}this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"==this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"==this.options.axis||(this.helper[0].style.top=this.position.top+"px");for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],g=f.item[0],h=this._intersectsWithPointer(f);if(h&&f.instance===this.currentContainer&&g!=this.currentItem[0]&&this.placeholder[1==h?"next":"prev"]()[0]!=g&&!a.ui.contains(this.placeholder[0],g)&&("semi-dynamic"==this.options.type?!a.ui.contains(this.element[0],g):!0)){if(this.direction=1==h?"down":"up","pointer"!=this.options.tolerance&&!this._intersectsWithSides(f))break;this._rearrange(b,f),this._trigger("change",b,this._uiHash());break}}return this._contactContainers(b),a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),this._trigger("sort",b,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(b,c){if(b){if(a.ui.ddmanager&&!this.options.dropBehaviour&&a.ui.ddmanager.drop(this,b),this.options.revert){var d=this,e=d.placeholder.offset();d.reverting=!0,a(this.helper).animate({left:e.left-this.offset.parent.left-d.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-d.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){d._clear(b)})}else this._clear(b,c);return!1}},cancel:function(){var b=this;if(this.dragging){this._mouseUp({target:null}),"original"==this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("deactivate",null,b._uiHash(this)),this.containers[c].containerCache.over&&(this.containers[c]._trigger("out",null,b._uiHash(this)),this.containers[c].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!=this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),a.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?a(this.domPosition.prev).after(this.currentItem):a(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},a(c).each(function(){var c=(a(b.item||this).attr(b.attribute||"id")||"").match(b.expression||/(.+)[-=_](.+)/);c&&d.push((b.key||c[1]+"[]")+"="+(b.key&&b.expression?c[1]:c[2]))}),!d.length&&b.key&&d.push(b.key+"="),d.join("&")},toArray:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},c.each(function(){d.push(a(b.item||this).attr(b.attribute||"id")||"")}),d},_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,d=this.positionAbs.top,e=d+this.helperProportions.height,f=a.left,g=f+a.width,h=a.top,i=h+a.height,j=this.offset.click.top,k=this.offset.click.left,l=d+j>h&&i>d+j&&b+k>f&&g>b+k;return"pointer"==this.options.tolerance||this.options.forcePointerForContainers||"pointer"!=this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?l:f<b+this.helperProportions.width/2&&c-this.helperProportions.width/2<g&&h<d+this.helperProportions.height/2&&e-this.helperProportions.height/2<i},_intersectsWithPointer:function(b){var c="x"===this.options.axis||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top,b.height),d="y"===this.options.axis||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left,b.width),e=c&&d,f=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();return e?this.floating?g&&"right"==g||"down"==f?2:1:f&&("down"==f?2:1):!1},_intersectsWithSides:function(b){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top+b.height/2,b.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left+b.width/2,b.width),e=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();return this.floating&&f?"right"==f&&d||"left"==f&&!d:e&&("down"==e&&c||"up"==e&&!c)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return 0!=a&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-this.lastPositionAbs.left;return 0!=a&&(a>0?"right":"left")},refresh:function(a){return this._refreshItems(a),this.refreshPositions(),this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(b){var c=[],d=[],e=this._connectWith();if(e&&b)for(var f=e.length-1;f>=0;f--)for(var g=a(e[f]),h=g.length-1;h>=0;h--){var i=a.data(g[h],this.widgetName);i&&i!=this&&!i.options.disabled&&d.push([a.isFunction(i.options.items)?i.options.items.call(i.element):a(i.options.items,i.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),i])}d.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var f=d.length-1;f>=0;f--)d[f][0].each(function(){c.push(this)});return a(c)},_removeCurrentsFromItems:function(){for(var a=this.currentItem.find(":data("+this.widgetName+"-item)"),b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(b){this.items=[],this.containers=[this];var c=this.items,d=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]],e=this._connectWith();if(e&&this.ready)for(var f=e.length-1;f>=0;f--)for(var g=a(e[f]),h=g.length-1;h>=0;h--){var i=a.data(g[h],this.widgetName);i&&i!=this&&!i.options.disabled&&(d.push([a.isFunction(i.options.items)?i.options.items.call(i.element[0],b,{item:this.currentItem}):a(i.options.items,i.element),i]),this.containers.push(i))}for(var f=d.length-1;f>=0;f--)for(var j=d[f][1],k=d[f][0],h=0,l=k.length;l>h;h++){var m=a(k[h]);m.data(this.widgetName+"-item",j),c.push({item:m,instance:j,width:0,height:0,left:0,top:0})}},refreshPositions:function(b){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var c=this.items.length-1;c>=0;c--){var d=this.items[c];if(d.instance==this.currentContainer||!this.currentContainer||d.item[0]==this.currentItem[0]){var e=this.options.toleranceElement?a(this.options.toleranceElement,d.item):d.item;b||(d.width=e.outerWidth(),d.height=e.outerHeight());var f=e.offset();d.left=f.left,d.top=f.top}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var c=this.containers.length-1;c>=0;c--){var f=this.containers[c].element.offset();this.containers[c].containerCache.left=f.left,this.containers[c].containerCache.top=f.top,this.containers[c].containerCache.width=this.containers[c].element.outerWidth(),this.containers[c].containerCache.height=this.containers[c].element.outerHeight()}return this},_createPlaceholder:function(b){var c=b||this,d=c.options;if(!d.placeholder||d.placeholder.constructor==String){var e=d.placeholder;d.placeholder={element:function(){var b=a(document.createElement(c.currentItem[0].nodeName)).addClass(e||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return e||(b.style.visibility="hidden"),b},update:function(a,b){(!e||d.forcePlaceholderSize)&&(b.height()||b.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10)),b.width()||b.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10)))}}}c.placeholder=a(d.placeholder.element.call(c.element,c.currentItem)),c.currentItem.after(c.placeholder),d.placeholder.update(c,c.placeholder)},_contactContainers:function(b){for(var c=null,d=null,e=this.containers.length-1;e>=0;e--)if(!a.ui.contains(this.currentItem[0],this.containers[e].element[0]))if(this._intersectsWith(this.containers[e].containerCache)){if(c&&a.ui.contains(this.containers[e].element[0],c.element[0]))continue;c=this.containers[e],d=e}else this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",b,this._uiHash(this)),this.containers[e].containerCache.over=0);if(c)if(1===this.containers.length)this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1;else if(this.currentContainer!=this.containers[d]){for(var f=1e4,g=null,h=this.positionAbs[this.containers[d].floating?"left":"top"],i=this.items.length-1;i>=0;i--)if(a.ui.contains(this.containers[d].element[0],this.items[i].item[0])){var j=this.containers[d].floating?this.items[i].item.offset().left:this.items[i].item.offset().top;Math.abs(j-h)<f&&(f=Math.abs(j-h),g=this.items[i],this.direction=j-h>0?"down":"up")}if(!g&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[d],g?this._rearrange(b,g,null,!0):this._rearrange(b,null,this.containers[d].element,!0),this._trigger("change",b,this._uiHash()),this.containers[d]._trigger("change",b,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1}},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b,this.currentItem])):"clone"==c.helper?this.currentItem.clone():this.currentItem;return d.parents("body").length||a("parent"!=c.appendTo?c.appendTo:this.currentItem[0].parentNode)[0].appendChild(d[0]),d[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(""==d[0].style.width||c.forceHelperSize)&&d.width(this.currentItem.width()),(""==d[0].style.height||c.forceHelperSize)&&d.height(this.currentItem.height()),d},_adjustOffsetFromHelper:function(b){"string"==typeof b&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();return"absolute"==this.cssPosition&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&"html"==this.offsetParent[0].tagName.toLowerCase()&&a.browser.msie)&&(b={top:0,left:0}),{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"==this.cssPosition){var a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;if("parent"==b.containment&&(b.containment=this.helper[0].parentNode),("document"==b.containment||"window"==b.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a("document"==b.containment?document:window).width()-this.helperProportions.width-this.margins.left,(a("document"==b.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),!/^(document|window|parent)$/.test(b.containment)){var c=a(b.containment)[0],d=a(b.containment).offset(),e="hidden"!=a(c).css("overflow");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(e?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(e?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(b,c){c||(c=this.position);var d="absolute"==b?1:-1,e=(this.options,"absolute"!=this.cssPosition||this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent),f=/(html|body)/i.test(e[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollTop():f?0:e.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollLeft():f?0:e.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d="absolute"!=this.cssPosition||this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,e=/(html|body)/i.test(d[0].tagName);"relative"!=this.cssPosition||this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset());var f=b.pageX,g=b.pageY;if(this.originalPosition&&(this.containment&&(b.pageX-this.offset.click.left<this.containment[0]&&(f=this.containment[0]+this.offset.click.left),b.pageY-this.offset.click.top<this.containment[1]&&(g=this.containment[1]+this.offset.click.top),b.pageX-this.offset.click.left>this.containment[2]&&(f=this.containment[2]+this.offset.click.left),b.pageY-this.offset.click.top>this.containment[3]&&(g=this.containment[3]+this.offset.click.top)),c.grid)){var h=this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1]; g=this.containment&&(h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3])?h-this.offset.click.top<this.containment[1]?h+c.grid[1]:h-c.grid[1]:h;var i=this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0];f=this.containment&&(i-this.offset.click.left<this.containment[0]||i-this.offset.click.left>this.containment[2])?i-this.offset.click.left<this.containment[0]?i+c.grid[0]:i-c.grid[0]:i}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_rearrange:function(a,b,c,d){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],"down"==this.direction?b.item[0]:b.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var e=this,f=this.counter;window.setTimeout(function(){f==e.counter&&e.refreshPositions(!d)},0)},_clear:function(b,c){this.reverting=!1;var d=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]==this.currentItem[0]){for(var e in this._storedCSS)("auto"==this._storedCSS[e]||"static"==this._storedCSS[e])&&(this._storedCSS[e]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!c&&d.push(function(a){this._trigger("receive",a,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev==this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent==this.currentItem.parent()[0]||c||d.push(function(a){this._trigger("update",a,this._uiHash())}),this!==this.currentContainer&&(c||(d.push(function(a){this._trigger("remove",a,this._uiHash())}),d.push(function(a){return function(b){a._trigger("receive",b,this._uiHash(this))}}.call(this,this.currentContainer)),d.push(function(a){return function(b){a._trigger("update",b,this._uiHash(this))}}.call(this,this.currentContainer))));for(var e=this.containers.length-1;e>=0;e--)c||d.push(function(a){return function(b){a._trigger("deactivate",b,this._uiHash(this))}}.call(this,this.containers[e])),this.containers[e].containerCache.over&&(d.push(function(a){return function(b){a._trigger("out",b,this._uiHash(this))}}.call(this,this.containers[e])),this.containers[e].containerCache.over=0);if(this._storedCursor&&a("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"==this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!c){this._trigger("beforeStop",b,this._uiHash());for(var e=0;e<d.length;e++)d[e].call(this,b);this._trigger("stop",b,this._uiHash())}return this.fromOutside=!1,!1}if(c||this._trigger("beforeStop",b,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null,!c){for(var e=0;e<d.length;e++)d[e].call(this,b);this._trigger("stop",b,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){a.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(b){var c=b||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:b?b.element:null}}}),a.extend(a.ui.sortable,{version:"1.8.24"})}(jQuery);
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
JamesWatling/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ActorClient from '../../utils/ActorClient'; import { Styles, FlatButton } from 'material-ui'; import { KeyCodes } from '../../constants/ActorAppConstants'; import ActorTheme from '../../constants/ActorTheme'; import MessageActionCreators from '../../actions/MessageActionCreators'; import TypingActionCreators from '../../actions/TypingActionCreators'; import DraftActionCreators from '../../actions/DraftActionCreators'; import DraftStore from '../../stores/DraftStore'; import AvatarItem from '../../components/common/AvatarItem.react'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { text: DraftStore.getDraft(), profile: ActorClient.getUser(ActorClient.getUid()) }; }; var ComposeSection = React.createClass({ displayName: 'ComposeSection', propTypes: { peer: React.PropTypes.object.isRequired }, childContextTypes: { muiTheme: React.PropTypes.object }, mixins: [PureRenderMixin], getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; }, componentWillMount() { ThemeManager.setTheme(ActorTheme); DraftStore.addLoadDraftListener(this.onDraftLoad); }, componentWillUnmount() { DraftStore.removeLoadDraftListener(this.onDraftLoad); }, getInitialState: function() { return getStateFromStores(); }, onDraftLoad() { this.setState(getStateFromStores()); }, _onChange: function(event) { TypingActionCreators.onTyping(this.props.peer); this.setState({text: event.target.value}); }, _onKeyDown: function(event) { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this._sendTextMessage(); } else if (event.keyCode === 50 && event.shiftKey) { console.warn('Mention should show now.'); } }, onKeyUp() { DraftActionCreators.saveDraft(this.state.text); }, _sendTextMessage() { const text = this.state.text; if (text) { MessageActionCreators.sendTextMessage(this.props.peer, text); } this.setState({text: ''}); DraftActionCreators.saveDraft('', true); }, _onSendFileClick: function() { const fileInput = document.getElementById('composeFileInput'); fileInput.click(); }, _onSendPhotoClick: function() { const photoInput = document.getElementById('composePhotoInput'); photoInput.accept = 'image/*'; photoInput.click(); }, _onFileInputChange: function() { const files = document.getElementById('composeFileInput').files; MessageActionCreators.sendFileMessage(this.props.peer, files[0]); }, _onPhotoInputChange: function() { const photos = document.getElementById('composePhotoInput').files; MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]); }, _onPaste: function(event) { let preventDefault = false; _.forEach(event.clipboardData.items, function(item) { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }, render: function() { const text = this.state.text; const profile = this.state.profile; return ( <section className="compose" onPaste={this._onPaste}> <AvatarItem image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this._onChange} onKeyDown={this._onKeyDown} onKeyUp={this.onKeyUp} value={text}> </textarea> <footer className="compose__footer row"> <button className="button" onClick={this._onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button" onClick={this._onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <FlatButton label="Send" onClick={this._sendTextMessage} secondary={true}/> </footer> <div className="compose__hidden"> <input id="composeFileInput" onChange={this._onFileInputChange} type="file"/> <input id="composePhotoInput" onChange={this._onPhotoInputChange} type="file"/> </div> </section> ); } }); export default ComposeSection;
App/node_modules/react-navigation/lib-rn/views/Drawer/DrawerNavigatorItems.js
Dagers/React-Native-Differential-Updater
import React from 'react'; import { View, Text, Platform, StyleSheet } from 'react-native'; import TouchableItem from '../TouchableItem'; var babelPluginFlowReactPropTypes_proptype_Style = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_Style || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_NavigationRoute = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationRoute || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_NavigationAction = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationAction || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_NavigationState = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationState || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_NavigationScreenProp = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationScreenProp || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_DrawerItem = require('./DrawerView.js').babelPluginFlowReactPropTypes_proptype_DrawerItem || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_DrawerScene = require('./DrawerView.js').babelPluginFlowReactPropTypes_proptype_DrawerScene || require('prop-types').any; /** * Component that renders the navigation list in the drawer. */ const DrawerNavigatorItems = ({ navigation: { state, navigate }, items, activeItemKey, activeTintColor, activeBackgroundColor, inactiveTintColor, inactiveBackgroundColor, getLabel, renderIcon, onItemPress, style, labelStyle }) => <View style={[styles.container, style]}> {items.map((route, index) => { const focused = activeItemKey === route.key; const color = focused ? activeTintColor : inactiveTintColor; const backgroundColor = focused ? activeBackgroundColor : inactiveBackgroundColor; const scene = { route, index, focused, tintColor: color }; const icon = renderIcon(scene); const label = getLabel(scene); return <TouchableItem key={route.key} onPress={() => { onItemPress({ route, focused }); }} delayPressIn={0}> <View style={[styles.item, { backgroundColor }]}> {icon ? <View style={[styles.icon, focused ? null : styles.inactiveIcon]}> {icon} </View> : null} {typeof label === 'string' ? <Text style={[styles.label, { color }, labelStyle]}> {label} </Text> : label} </View> </TouchableItem>; })} </View>; /* Material design specs - https://material.io/guidelines/patterns/navigation-drawer.html#navigation-drawer-specs */ DrawerNavigatorItems.propTypes = { navigation: babelPluginFlowReactPropTypes_proptype_NavigationScreenProp, items: require('prop-types').arrayOf(babelPluginFlowReactPropTypes_proptype_NavigationRoute).isRequired, activeItemKey: require('prop-types').string, activeTintColor: require('prop-types').string, activeBackgroundColor: require('prop-types').string, inactiveTintColor: require('prop-types').string, inactiveBackgroundColor: require('prop-types').string, getLabel: require('prop-types').func.isRequired, renderIcon: require('prop-types').func.isRequired, onItemPress: require('prop-types').func.isRequired, style: babelPluginFlowReactPropTypes_proptype_Style, labelStyle: babelPluginFlowReactPropTypes_proptype_Style }; DrawerNavigatorItems.defaultProps = { activeTintColor: '#2196f3', activeBackgroundColor: 'rgba(0, 0, 0, .04)', inactiveTintColor: 'rgba(0, 0, 0, .87)', inactiveBackgroundColor: 'transparent' }; const styles = StyleSheet.create({ container: { marginTop: Platform.OS === 'ios' ? 20 : 0, paddingVertical: 4 }, item: { flexDirection: 'row', alignItems: 'center' }, icon: { marginHorizontal: 16, width: 24, alignItems: 'center' }, inactiveIcon: { /* * Icons have 0.54 opacity according to guidelines * 100/87 * 54 ~= 62 */ opacity: 0.62 }, label: { margin: 16, fontWeight: 'bold' } }); export default DrawerNavigatorItems;
geonode/monitoring/frontend/src/components/organisms/geonode-layers-analytics/index.js
ppasq/geonode
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getResponseData, getErrorCount } from '../../../utils'; import HoverPaper from '../../atoms/hover-paper'; import HR from '../../atoms/hr'; import ResponseTable from '../../cels/response-table'; import LayerSelect from '../../cels/layer-select'; import FrequentLayers from '../../cels/frequent-layers'; import styles from './styles'; import actions from './actions'; const mapStateToProps = (state) => ({ interval: state.interval.interval, response: state.geonodeLayerResponse.response, errorNumber: state.geonodeLayerError.response, }); @connect(mapStateToProps, actions) class GeonodeLayerAnalytics extends React.Component { static propTypes = { getResponses: PropTypes.func.isRequired, resetResponses: PropTypes.func.isRequired, getErrors: PropTypes.func.isRequired, resetErrors: PropTypes.func.isRequired, interval: PropTypes.number, response: PropTypes.object, errorNumber: PropTypes.object, timestamp: PropTypes.instanceOf(Date), } constructor(props) { super(props); this.get = (layer, interval = this.props.interval) => { this.setState({ layer }); this.props.getErrors(layer, interval); this.props.getResponses(layer, interval); }; this.reset = () => { this.props.resetErrors(); this.props.resetResponses(); }; } componentWillReceiveProps(nextProps) { if (nextProps) { if ( nextProps.timestamp && nextProps.timestamp !== this.props.timestamp && this.state && this.state.layer ) { this.get(this.state.layer, nextProps.interval); } } } componentWillUnmount() { this.reset(); } render() { let average = 0; let max = 0; let requests = 0; [ average, max, requests, ] = getResponseData(this.props.response); const errorNumber = getErrorCount(this.props.errorNumber); return ( <HoverPaper style={styles.content}> <div style={styles.header}> <h3>Geonode Layers Analytics</h3> <LayerSelect onChange={this.get} /> </div> <HR /> <ResponseTable average={average} max={max} requests={requests} errorNumber={errorNumber} /> <FrequentLayers /> </HoverPaper> ); } } export default GeonodeLayerAnalytics;
ajax/libs/x-editable/1.5.1/jqueryui-editable/js/jqueryui-editable.js
khasinski/cdnjs
/*! X-editable - v1.5.1 * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery * http://github.com/vitalets/x-editable * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */ /** Form with single input element, two buttons and two states: normal/loading. Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown. Editableform is linked with one of input types, e.g. 'text', 'select' etc. @class editableform @uses text @uses textarea **/ (function ($) { "use strict"; var EditableForm = function (div, options) { this.options = $.extend({}, $.fn.editableform.defaults, options); this.$div = $(div); //div, containing form. Not form tag. Not editable-element. if(!this.options.scope) { this.options.scope = this; } //nothing shown after init }; EditableForm.prototype = { constructor: EditableForm, initInput: function() { //called once //take input from options (as it is created in editable-element) this.input = this.options.input; //set initial value //todo: may be add check: typeof str === 'string' ? this.value = this.input.str2value(this.options.value); //prerender: get input.$input this.input.prerender(); }, initTemplate: function() { this.$form = $($.fn.editableform.template); }, initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } }, /** Renders editableform @method render **/ render: function() { //init loader this.$loading = $($.fn.editableform.loading); this.$div.empty().append(this.$loading); //init form template and buttons this.initTemplate(); if(this.options.showbuttons) { this.initButtons(); } else { this.$form.find('.editable-buttons').remove(); } //show loading state this.showLoading(); //flag showing is form now saving value to server. //It is needed to wait when closing form. this.isSaving = false; /** Fired when rendering starts @event rendering @param {Object} event event object **/ this.$div.triggerHandler('rendering'); //init input this.initInput(); //append input to form this.$form.find('div.editable-input').append(this.input.$tpl); //append form to container this.$div.append(this.$form); //render input $.when(this.input.render()) .then($.proxy(function () { //setup input to submit automatically when no buttons shown if(!this.options.showbuttons) { this.input.autosubmit(); } //attach 'cancel' handler this.$form.find('.editable-cancel').click($.proxy(this.cancel, this)); if(this.input.error) { this.error(this.input.error); this.$form.find('.editable-submit').attr('disabled', true); this.input.$input.attr('disabled', true); //prevent form from submitting this.$form.submit(function(e){ e.preventDefault(); }); } else { this.error(false); this.input.$input.removeAttr('disabled'); this.$form.find('.editable-submit').removeAttr('disabled'); var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value; this.input.value2input(value); //attach submit handler this.$form.submit($.proxy(this.submit, this)); } /** Fired when form is rendered @event rendered @param {Object} event event object **/ this.$div.triggerHandler('rendered'); this.showForm(); //call postrender method to perform actions required visibility of form if(this.input.postrender) { this.input.postrender(); } }, this)); }, cancel: function() { /** Fired when form was cancelled by user @event cancel @param {Object} event event object **/ this.$div.triggerHandler('cancel'); }, showLoading: function() { var w, h; if(this.$form) { //set loading size equal to form w = this.$form.outerWidth(); h = this.$form.outerHeight(); if(w) { this.$loading.width(w); } if(h) { this.$loading.height(h); } this.$form.hide(); } else { //stretch loading to fill container width w = this.$loading.parent().width(); if(w) { this.$loading.width(w); } } this.$loading.show(); }, showForm: function(activate) { this.$loading.hide(); this.$form.show(); if(activate !== false) { this.input.activate(); } /** Fired when form is shown @event show @param {Object} event event object **/ this.$div.triggerHandler('show'); }, error: function(msg) { var $group = this.$form.find('.control-group'), $block = this.$form.find('.editable-error-block'), lines; if(msg === false) { $group.removeClass($.fn.editableform.errorGroupClass); $block.removeClass($.fn.editableform.errorBlockClass).empty().hide(); } else { //convert newline to <br> for more pretty error display if(msg) { lines = (''+msg).split('\n'); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } msg = lines.join('<br>'); } $group.addClass($.fn.editableform.errorGroupClass); $block.addClass($.fn.editableform.errorBlockClass).html(msg).show(); } }, submit: function(e) { e.stopPropagation(); e.preventDefault(); //get new value from input var newValue = this.input.input2value(); //validation: if validate returns string or truthy value - means error //if returns object like {newValue: '...'} => submitted value is reassigned to it var error = this.validate(newValue); if ($.type(error) === 'object' && error.newValue !== undefined) { newValue = error.newValue; this.input.value2input(newValue); if(typeof error.msg === 'string') { this.error(error.msg); this.showForm(); return; } } else if (error) { this.error(error); this.showForm(); return; } //if value not changed --> trigger 'nochange' event and return /*jslint eqeq: true*/ if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) { /*jslint eqeq: false*/ /** Fired when value not changed but form is submitted. Requires savenochange = false. @event nochange @param {Object} event event object **/ this.$div.triggerHandler('nochange'); return; } //convert value for submitting to server var submitValue = this.input.value2submit(newValue); this.isSaving = true; //sending data to server $.when(this.save(submitValue)) .done($.proxy(function(response) { this.isSaving = false; //run success callback var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null; //if success callback returns false --> keep form open and do not activate input if(res === false) { this.error(false); this.showForm(false); return; } //if success callback returns string --> keep form open, show error and activate input if(typeof res === 'string') { this.error(res); this.showForm(); return; } //if success callback returns object like {newValue: <something>} --> use that value instead of submitted //it is usefull if you want to chnage value in url-function if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) { newValue = res.newValue; } //clear error message this.error(false); this.value = newValue; /** Fired when form is submitted @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue raw new value @param {mixed} params.submitValue submitted value as string @param {Object} params.response ajax response @example $('#form-div').on('save'), function(e, params){ if(params.newValue === 'username') {...} }); **/ this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response}); }, this)) .fail($.proxy(function(xhr) { this.isSaving = false; var msg; if(typeof this.options.error === 'function') { msg = this.options.error.call(this.options.scope, xhr, newValue); } else { msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!'; } this.error(msg); this.showForm(); }, this)); }, save: function(submitValue) { //try parse composite pk defined as json string in data-pk this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true); var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk, /* send on server in following cases: 1. url is function 2. url is string AND (pk defined OR send option = always) */ send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))), params; if (send) { //send to server this.showLoading(); //standard params params = { name: this.options.name || '', value: submitValue, pk: pk }; //additional params if(typeof this.options.params === 'function') { params = this.options.params.call(this.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true); $.extend(params, this.options.params); } if(typeof this.options.url === 'function') { //user's function return this.options.url.call(this.options.scope, params); } else { //send ajax to server and return deferred object return $.ajax($.extend({ url : this.options.url, data : params, type : 'POST' }, this.options.ajaxOptions)); } } }, validate: function (value) { if (value === undefined) { value = this.value; } if (typeof this.options.validate === 'function') { return this.options.validate.call(this.options.scope, value); } }, option: function(key, value) { if(key in this.options) { this.options[key] = value; } if(key === 'value') { this.setValue(value); } //do not pass option to input as it is passed in editable-element }, setValue: function(value, convertStr) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } //if form is visible, update input if(this.$form && this.$form.is(':visible')) { this.input.value2input(this.value); } } }; /* Initialize editableform. Applied to jQuery object. @method $().editableform(options) @params {Object} options @example var $form = $('&lt;div&gt;').editableform({ type: 'text', name: 'username', url: '/post', value: 'vitaliy' }); //to display form you should call 'render' method $form.editableform('render'); */ $.fn.editableform = function (option) { var args = arguments; return this.each(function () { var $this = $(this), data = $this.data('editableform'), options = typeof option === 'object' && option; if (!data) { $this.data('editableform', (data = new EditableForm(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //keep link to constructor to allow inheritance $.fn.editableform.Constructor = EditableForm; //defaults $.fn.editableform.defaults = { /* see also defaults for input */ /** Type of input. Can be <code>text|textarea|select|date|checklist</code> @property type @type string @default 'text' **/ type: 'text', /** Url for submit, e.g. <code>'/post'</code> If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks. @property url @type string|function @default null @example url: function(params) { var d = new $.Deferred; if(params.value === 'abc') { return d.reject('error message'); //returning error via deferred object } else { //async saving data in js model someModel.asyncSaveMethod({ ..., success: function(){ d.resolve(); } }); return d.promise(); } } **/ url:null, /** Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value). If defined as <code>function</code> - returned object **overwrites** original ajax data. @example params: function(params) { //originally params contain pk, name and value params.a = 1; return params; } @property params @type object|function @default null **/ params:null, /** Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute @property name @type string @default null **/ name: null, /** Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>. Can be calculated dynamically via function. @property pk @type string|object|function @default null **/ pk: null, /** Initial value. If not defined - will be taken from element's content. For __select__ type should be defined (as it is ID of shown text). @property value @type string|object @default null **/ value: null, /** Value that will be displayed in input if original field value is empty (`null|undefined|''`). @property defaultValue @type string|object @default null @since 1.4.6 **/ defaultValue: null, /** Strategy for sending data on server. Can be `auto|always|never`. When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally. @property send @type string @default 'auto' **/ send: 'auto', /** Function for client-side validation. If returns string - means validation not passed and string showed as error. Since 1.5.1 you can modify submitted value by returning object from `validate`: `{newValue: '...'}` or `{newValue: '...', msg: '...'}` @property validate @type function @default null @example validate: function(value) { if($.trim(value) == '') { return 'This field is required'; } } **/ validate: null, /** Success callback. Called when value successfully sent on server and **response status = 200**. Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code> or <code>{success: false, msg: "server error"}</code> you can check it inside this callback. If it returns **string** - means error occured and string is shown as error message. If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user. Otherwise newValue simply rendered into element. @property success @type function @default null @example success: function(response, newValue) { if(!response.success) return response.msg; } **/ success: null, /** Error callback. Called when request failed (response status != 200). Usefull when you want to parse error response and display a custom message. Must return **string** - the message to be displayed in the error block. @property error @type function @default null @since 1.4.4 @example error: function(response, newValue) { if(response.status === 500) { return 'Service unavailable. Please try later.'; } else { return response.responseText; } } **/ error: null, /** Additional options for submit ajax request. List of values: http://api.jquery.com/jQuery.ajax @property ajaxOptions @type object @default null @since 1.1.1 @example ajaxOptions: { type: 'put', dataType: 'json' } **/ ajaxOptions: null, /** Where to show buttons: left(true)|bottom|false Form without buttons is auto-submitted. @property showbuttons @type boolean|string @default true @since 1.1.1 **/ showbuttons: true, /** Scope for callback methods (success, validate). If <code>null</code> means editableform instance itself. @property scope @type DOMElement|object @default null @since 1.2.0 @private **/ scope: null, /** Whether to save or cancel value when it was not changed but form was submitted @property savenochange @type boolean @default false @since 1.2.0 **/ savenochange: false }; /* Note: following params could redefined in engine: bootstrap or jqueryui: Classes 'control-group' and 'editable-error-block' must always present! */ $.fn.editableform.template = '<form class="form-inline editableform">'+ '<div class="control-group">' + '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+ '<div class="editable-error-block"></div>' + '</div>' + '</form>'; //loading div $.fn.editableform.loading = '<div class="editableform-loading"></div>'; //buttons $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+ '<button type="button" class="editable-cancel">cancel</button>'; //error class attached to control-group $.fn.editableform.errorGroupClass = null; //error class attached to editable-error-block $.fn.editableform.errorBlockClass = 'editable-error'; //engine $.fn.editableform.engine = 'jquery'; }(window.jQuery)); /** * EditableForm utilites */ (function ($) { "use strict"; //utils $.fn.editableutils = { /** * classic JS inheritance function */ inherit: function (Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; }, /** * set caret position in input * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area */ setCursorPosition: function(elem, pos) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, /** * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes) * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}"> * safe = true --> means no exception will be thrown * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery */ tryParseJson: function(s, safe) { if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) { if (safe) { try { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } catch (e) {} finally { return s; } } else { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } } return s; }, /** * slice object by specified keys */ sliceObj: function(obj, keys, caseSensitive /* default: false */) { var key, keyLower, newObj = {}; if (!$.isArray(keys) || !keys.length) { return newObj; } for (var i = 0; i < keys.length; i++) { key = keys[i]; if (obj.hasOwnProperty(key)) { newObj[key] = obj[key]; } if(caseSensitive === true) { continue; } //when getting data-* attributes via $.data() it's converted to lowercase. //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery //workaround is code below. keyLower = key.toLowerCase(); if (obj.hasOwnProperty(keyLower)) { newObj[key] = obj[keyLower]; } } return newObj; }, /* exclude complex objects from $.data() before pass to config */ getConfigData: function($element) { var data = {}; $.each($element.data(), function(k, v) { if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) { data[k] = v; } }); return data; }, /* returns keys of object */ objectKeys: function(o) { if (Object.keys) { return Object.keys(o); } else { if (o !== Object(o)) { throw new TypeError('Object.keys called on a non-object'); } var k=[], p; for (p in o) { if (Object.prototype.hasOwnProperty.call(o,p)) { k.push(p); } } return k; } }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /* returns array items from sourceData having value property equal or inArray of 'value' */ itemsByValue: function(value, sourceData, valueProp) { if(!sourceData || value === null) { return []; } if (typeof(valueProp) !== "function") { var idKey = valueProp || 'value'; valueProp = function (e) { return e[idKey]; }; } var isValArray = $.isArray(value), result = [], that = this; $.each(sourceData, function(i, o) { if(o.children) { result = result.concat(that.itemsByValue(value, o.children, valueProp)); } else { /*jslint eqeq: true*/ if(isValArray) { if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) { result.push(o); } } else { var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o; if(value == itemValue) { result.push(o); } } /*jslint eqeq: false*/ } }); return result; }, /* Returns input by options: type, mode. */ createInput: function(options) { var TypeConstructor, typeOptions, input, type = options.type; //`date` is some kind of virtual type that is transformed to one of exact types //depending on mode and core lib if(type === 'date') { //inline if(options.mode === 'inline') { if($.fn.editabletypes.datefield) { type = 'datefield'; } else if($.fn.editabletypes.dateuifield) { type = 'dateuifield'; } //popup } else { if($.fn.editabletypes.date) { type = 'date'; } else if($.fn.editabletypes.dateui) { type = 'dateui'; } } //if type still `date` and not exist in types, replace with `combodate` that is base input if(type === 'date' && !$.fn.editabletypes.date) { type = 'combodate'; } } //`datetime` should be datetimefield in 'inline' mode if(type === 'datetime' && options.mode === 'inline') { type = 'datetimefield'; } //change wysihtml5 to textarea for jquery UI and plain versions if(type === 'wysihtml5' && !$.fn.editabletypes[type]) { type = 'textarea'; } //create input of specified type. Input will be used for converting value, not in form if(typeof $.fn.editabletypes[type] === 'function') { TypeConstructor = $.fn.editabletypes[type]; typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults)); input = new TypeConstructor(typeOptions); return input; } else { $.error('Unknown type: '+ type); return false; } }, //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions: function () { var b = document.body || document.documentElement, s = b.style, p = 'transition', v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms']; if(typeof s[p] === 'string') { return true; } // Tests for vendor specific prop p = p.charAt(0).toUpperCase() + p.substr(1); for(var i=0; i<v.length; i++) { if(typeof s[v[i] + p] === 'string') { return true; } } return false; } }; }(window.jQuery)); /** Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br> This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br> Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br> Applied as jQuery method. @class editableContainer @uses editableform **/ (function ($) { "use strict"; var Popup = function (element, options) { this.init(element, options); }; var Inline = function (element, options) { this.init(element, options); }; //methods Popup.prototype = { containerName: null, //method to call container on element containerDataName: null, //object name in element's .data() innerCss: null, //tbd in child class containerClass: 'editable-container editable-popup', //css class applied to container element defaults: {}, //container itself defaults init: function(element, options) { this.$element = $(element); //since 1.4.1 container do not use data-* directly as they already merged into options. this.options = $.extend({}, $.fn.editableContainer.defaults, options); this.splitOptions(); //set scope of form callbacks to element this.formOptions.scope = this.$element[0]; this.initContainer(); //flag to hide container, when saving value will finish this.delayedHide = false; //bind 'destroyed' listener to destroy container when element is removed from dom this.$element.on('destroyed', $.proxy(function(){ this.destroy(); }, this)); //attach document handler to close containers on click / escape if(!$(document).data('editable-handlers-attached')) { //close all on escape $(document).on('keyup.editable', function (e) { if (e.which === 27) { $('.editable-open').editableContainer('hide'); //todo: return focus on element } }); //close containers when click outside //(mousedown could be better than click, it closes everything also on drag drop) $(document).on('click.editable', function(e) { var $target = $(e.target), i, exclude_classes = ['.editable-container', '.ui-datepicker-header', '.datepicker', //in inline mode datepicker is rendered into body '.modal-backdrop', '.bootstrap-wysihtml5-insert-image-modal', '.bootstrap-wysihtml5-insert-link-modal' ]; //check if element is detached. It occurs when clicking in bootstrap datepicker if (!$.contains(document.documentElement, e.target)) { return; } //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199 //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec if($target.is(document)) { return; } //if click inside one of exclude classes --> no nothing for(i=0; i<exclude_classes.length; i++) { if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) { return; } } //close all open containers (except one - target) Popup.prototype.closeOthers(e.target); }); $(document).data('editable-handlers-attached', true); } }, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; if(!$.fn[this.containerName]) { throw new Error(this.containerName + ' not found. Have you included corresponding js file?'); } //keys defined in container defaults go to container, others go to form for(var k in this.options) { if(k in this.defaults) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, /* Returns jquery object of container @method tip() */ tip: function() { return this.container() ? this.container().$tip : null; }, /* returns container object */ container: function() { var container; //first, try get it by `containerDataName` if(this.containerDataName) { if(container = this.$element.data(this.containerDataName)) { return container; } } //second, try `containerName` container = this.$element.data(this.containerName); return container; }, /* call native method of underlying container, e.g. this.$element.popover('method') */ call: function() { this.$element[this.containerName].apply(this.$element, arguments); }, initContainer: function(){ this.call(this.containerOptions); }, renderForm: function() { this.$form .editableform(this.formOptions) .on({ save: $.proxy(this.save, this), //click on submit button (value changed) nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed) cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button show: $.proxy(function() { if(this.delayedHide) { this.hide(this.delayedHide.reason); this.delayedHide = false; } else { this.setPosition(); } }, this), //re-position container every time form is shown (occurs each time after loading state) rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed rendered: $.proxy(function(){ /** Fired when container is shown and form is rendered (for select will wait for loading dropdown options). **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event shown @param {Object} event event object @example $('#username').on('shown', function(e, editable) { editable.input.$input.val('overwriting value of input..'); }); **/ /* TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events. */ this.$element.triggerHandler('shown', $(this.options.scope).data('editable')); }, this) }) .editableform('render'); }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ /* Note: poshytip owerwrites this method totally! */ show: function (closeAll) { this.$element.addClass('editable-open'); if(closeAll !== false) { //close all open containers (except this) this.closeOthers(this.$element[0]); } //show container itself this.innerShow(); this.tip().addClass(this.containerClass); /* Currently, form is re-rendered on every show. The main reason is that we dont know, what will container do with content when closed: remove(), detach() or just hide() - it depends on container. Detaching form itself before hide and re-insert before show is good solution, but visually it looks ugly --> container changes size before hide. */ //if form already exist - delete previous data if(this.$form) { //todo: destroy prev data! //this.$form.destroy(); } this.$form = $('<div>'); //insert form into container body if(this.tip().is(this.innerCss)) { //for inline container this.tip().append(this.$form); } else { this.tip().find(this.innerCss).append(this.$form); } //render form this.renderForm(); }, /** Hides container with form @method hide() @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code> **/ hide: function(reason) { if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) { return; } //if form is saving value, schedule hide if(this.$form.data('editableform').isSaving) { this.delayedHide = {reason: reason}; return; } else { this.delayedHide = false; } this.$element.removeClass('editable-open'); this.innerHide(); /** Fired when container was hidden. It occurs on both save or cancel. **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event hidden @param {object} event event object @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code> @example $('#username').on('hidden', function(e, reason) { if(reason === 'save' || reason === 'cancel') { //auto-open next editable $(this).closest('tr').next().find('.editable').editable('show'); } }); **/ this.$element.triggerHandler('hidden', reason || 'manual'); }, /* internal show method. To be overwritten in child classes */ innerShow: function () { }, /* internal hide method. To be overwritten in child classes */ innerHide: function () { }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container() && this.tip() && this.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* Updates the position of container when content changed. @method setPosition() */ setPosition: function() { //tbd in child class }, save: function(e, params) { /** Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { //assuming server response: '{success: true}' var pk = $(this).data('editableContainer').options.pk; if(params.response && params.response.success) { alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!'); } else { alert('error!'); } }); **/ this.$element.triggerHandler('save', params); //hide must be after trigger, as saving value may require methods of plugin, applied to input this.hide('save'); }, /** Sets new option @method option(key, value) @param {string} key @param {mixed} value **/ option: function(key, value) { this.options[key] = value; if(key in this.containerOptions) { this.containerOptions[key] = value; this.setContainerOption(key, value); } else { this.formOptions[key] = value; if(this.$form) { this.$form.editableform('option', key, value); } } }, setContainerOption: function(key, value) { this.call('option', key, value); }, /** Destroys the container instance @method destroy() **/ destroy: function() { this.hide(); this.innerDestroy(); this.$element.off('destroyed'); this.$element.removeData('editableContainer'); }, /* to be overwritten in child classes */ innerDestroy: function() { }, /* Closes other containers except one related to passed element. Other containers can be cancelled or submitted (depends on onblur option) */ closeOthers: function(element) { $('.editable-open').each(function(i, el){ //do nothing with passed element and it's children if(el === element || $(el).find(element).length) { return; } //otherwise cancel or submit all open containers var $el = $(el), ec = $el.data('editableContainer'); if(!ec) { return; } if(ec.options.onblur === 'cancel') { $el.data('editableContainer').hide('onblur'); } else if(ec.options.onblur === 'submit') { $el.data('editableContainer').tip().find('form').submit(); } }); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.tip && this.tip().is(':visible') && this.$form) { this.$form.data('editableform').input.activate(); } } }; /** jQuery method to initialize editableContainer. @method $().editableContainer(options) @params {Object} options @example $('#edit').editableContainer({ type: 'text', url: '/post', pk: 1, value: 'hello' }); **/ $.fn.editableContainer = function (option) { var args = arguments; return this.each(function () { var $this = $(this), dataKey = 'editableContainer', data = $this.data(dataKey), options = typeof option === 'object' && option, Constructor = (options.mode === 'inline') ? Inline : Popup; if (!data) { $this.data(dataKey, (data = new Constructor(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //store constructors $.fn.editableContainer.Popup = Popup; $.fn.editableContainer.Inline = Inline; //defaults $.fn.editableContainer.defaults = { /** Initial value of form input @property value @type mixed @default null @private **/ value: null, /** Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container. @property placement @type string @default 'top' **/ placement: 'top', /** Whether to hide container on save/cancel. @property autohide @type boolean @default true @private **/ autohide: true, /** Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>. Setting <code>ignore</code> allows to have several containers open. @property onblur @type string @default 'cancel' @since 1.1.1 **/ onblur: 'cancel', /** Animation speed (inline mode only) @property anim @type string @default false **/ anim: false, /** Mode of editable, can be `popup` or `inline` @property mode @type string @default 'popup' @since 1.4.0 **/ mode: 'popup' }; /* * workaround to have 'destroyed' event to destroy popover when element is destroyed * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom */ jQuery.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; }(window.jQuery)); /** * Editable Inline * --------------------- */ (function ($) { "use strict"; //copy prototype from EditableContainer //extend methods $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, { containerName: 'editableform', innerCss: '.editable-inline', containerClass: 'editable-container editable-inline', //css class applied to container element initContainer: function(){ //container is <span> element this.$tip = $('<span></span>'); //convert anim to miliseconds (int) if(!this.options.anim) { this.options.anim = 0; } }, splitOptions: function() { //all options are passed to form this.containerOptions = {}; this.formOptions = this.options; }, tip: function() { return this.$tip; }, innerShow: function () { this.$element.hide(); this.tip().insertAfter(this.$element).show(); }, innerHide: function () { this.$tip.hide(this.options.anim, $.proxy(function() { this.$element.show(); this.innerDestroy(); }, this)); }, innerDestroy: function() { if(this.tip()) { this.tip().empty().remove(); } } }); }(window.jQuery)); /** Makes editable any HTML element on the page. Applied as jQuery method. @class editable @uses editableContainer **/ (function ($) { "use strict"; var Editable = function (element, options) { this.$element = $(element); //data-* has more priority over js options: because dynamically created elements may change data-* this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element)); if(this.options.selector) { this.initLive(); } else { this.init(); } //check for transition support if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) { this.options.highlight = false; } }; Editable.prototype = { constructor: Editable, init: function () { var isValueByText = false, doAutotext, finalize; //name this.options.name = this.options.name || this.$element.attr('id'); //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select) //also we set scope option to have access to element inside input specific callbacks (e. g. source as function) this.options.scope = this.$element[0]; this.input = $.fn.editableutils.createInput(this.options); if(!this.input) { return; } //set value from settings or by element's text if (this.options.value === undefined || this.options.value === null) { this.value = this.input.html2value($.trim(this.$element.html())); isValueByText = true; } else { /* value can be string when received from 'data-value' attribute for complext objects value can be set as json string in data-value attribute, e.g. data-value="{city: 'Moscow', street: 'Lenina'}" */ this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true); if(typeof this.options.value === 'string') { this.value = this.input.str2value(this.options.value); } else { this.value = this.options.value; } } //add 'editable' class to every editable element this.$element.addClass('editable'); //specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks if(this.input.type === 'textarea') { this.$element.addClass('editable-pre-wrapped'); } //attach handler activating editable. In disabled mode it just prevent default action (useful for links) if(this.options.toggle !== 'manual') { this.$element.addClass('editable-click'); this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){ //prevent following link if editable enabled if(!this.options.disabled) { e.preventDefault(); } //stop propagation not required because in document click handler it checks event target //e.stopPropagation(); if(this.options.toggle === 'mouseenter') { //for hover only show container this.show(); } else { //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener var closeAll = (this.options.toggle !== 'click'); this.toggle(closeAll); } }, this)); } else { this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually } //if display is function it's far more convinient to have autotext = always to render correctly on init //see https://github.com/vitalets/x-editable-yii/issues/34 if(typeof this.options.display === 'function') { this.options.autotext = 'always'; } //check conditions for autotext: switch(this.options.autotext) { case 'always': doAutotext = true; break; case 'auto': //if element text is empty and value is defined and value not generated by text --> run autotext doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText; break; default: doAutotext = false; } //depending on autotext run render() or just finilize init $.when(doAutotext ? this.render() : true).then($.proxy(function() { if(this.options.disabled) { this.disable(); } else { this.enable(); } /** Fired when element was initialized by `$().editable()` method. Please note that you should setup `init` handler **before** applying `editable`. @event init @param {Object} event event object @param {Object} editable editable instance (as here it cannot accessed via data('editable')) @since 1.2.0 @example $('#username').on('init', function(e, editable) { alert('initialized ' + editable.options.name); }); $('#username').editable(); **/ this.$element.triggerHandler('init', this); }, this)); }, /* Initializes parent element for live editables */ initLive: function() { //store selector var selector = this.options.selector; //modify options for child elements this.options.selector = false; this.options.autotext = 'never'; //listen toggle events this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){ var $target = $(e.target); if(!$target.data('editable')) { //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user) //see https://github.com/vitalets/x-editable/issues/137 if($target.hasClass(this.options.emptyclass)) { $target.empty(); } $target.editable(this.options).trigger(e); } }, this)); }, /* Renders value into element's text. Can call custom display method from options. Can return deferred object. @method render() @param {mixed} response server response (if exist) to pass into display function */ render: function(response) { //do not display anything if(this.options.display === false) { return; } //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded if(this.input.value2htmlFinal) { return this.input.value2html(this.value, this.$element[0], this.options.display, response); //if display method defined --> use it } else if(typeof this.options.display === 'function') { return this.options.display.call(this.$element[0], this.value, response); //else use input's original value2html() method } else { return this.input.value2html(this.value, this.$element[0]); } }, /** Enables editable @method enable() **/ enable: function() { this.options.disabled = false; this.$element.removeClass('editable-disabled'); this.handleEmpty(this.isEmpty); if(this.options.toggle !== 'manual') { if(this.$element.attr('tabindex') === '-1') { this.$element.removeAttr('tabindex'); } } }, /** Disables editable @method disable() **/ disable: function() { this.options.disabled = true; this.hide(); this.$element.addClass('editable-disabled'); this.handleEmpty(this.isEmpty); //do not stop focus on this element this.$element.attr('tabindex', -1); }, /** Toggles enabled / disabled state of editable element @method toggleDisabled() **/ toggleDisabled: function() { if(this.options.disabled) { this.enable(); } else { this.disable(); } }, /** Sets new option @method option(key, value) @param {string|object} key option name or object with several options @param {mixed} value option new value @example $('.editable').editable('option', 'pk', 2); **/ option: function(key, value) { //set option(s) by object if(key && typeof key === 'object') { $.each(key, $.proxy(function(k, v){ this.option($.trim(k), v); }, this)); return; } //set option by string this.options[key] = value; //disabled if(key === 'disabled') { return value ? this.disable() : this.enable(); } //value if(key === 'value') { this.setValue(value); } //transfer new option to container! if(this.container) { this.container.option(key, value); } //pass option to input directly (as it points to the same in form) if(this.input.option) { this.input.option(key, value); } }, /* * set emptytext if element is empty */ handleEmpty: function (isEmpty) { //do not handle empty if we do not display anything if(this.options.display === false) { return; } /* isEmpty may be set directly as param of method. It is required when we enable/disable field and can't rely on content as node content is text: "Empty" that is not empty %) */ if(isEmpty !== undefined) { this.isEmpty = isEmpty; } else { //detect empty //for some inputs we need more smart check //e.g. wysihtml5 may have <br>, <p></p>, <img> if(typeof(this.input.isEmpty) === 'function') { this.isEmpty = this.input.isEmpty(this.$element); } else { this.isEmpty = $.trim(this.$element.html()) === ''; } } //emptytext shown only for enabled if(!this.options.disabled) { if (this.isEmpty) { this.$element.html(this.options.emptytext); if(this.options.emptyclass) { this.$element.addClass(this.options.emptyclass); } } else if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } else { //below required if element disable property was changed if(this.isEmpty) { this.$element.empty(); if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } } }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ show: function (closeAll) { if(this.options.disabled) { return; } //init editableContainer: popover, tooltip, inline, etc.. if(!this.container) { var containerOptions = $.extend({}, this.options, { value: this.value, input: this.input //pass input to form (as it is already created) }); this.$element.editableContainer(containerOptions); //listen `save` event this.$element.on("save.internal", $.proxy(this.save, this)); this.container = this.$element.data('editableContainer'); } else if(this.container.tip().is(':visible')) { return; } //show container this.container.show(closeAll); }, /** Hides container with form @method hide() **/ hide: function () { if(this.container) { this.container.hide(); } }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container && this.container.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* * called when form was submitted */ save: function(e, params) { //mark element with unsaved class if needed if(this.options.unsavedclass) { /* Add unsaved css to element if: - url is not user's function - value was not sent to server - params.response === undefined, that means data was not sent - value changed */ var sent = false; sent = sent || typeof this.options.url === 'function'; sent = sent || this.options.display === false; sent = sent || params.response !== undefined; sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue)); if(sent) { this.$element.removeClass(this.options.unsavedclass); } else { this.$element.addClass(this.options.unsavedclass); } } //highlight when saving if(this.options.highlight) { var $e = this.$element, bgColor = $e.css('background-color'); $e.css('background-color', this.options.highlight); setTimeout(function(){ if(bgColor === 'transparent') { bgColor = ''; } $e.css('background-color', bgColor); $e.addClass('editable-bg-transition'); setTimeout(function(){ $e.removeClass('editable-bg-transition'); }, 1700); }, 10); } //set new value this.setValue(params.newValue, false, params.response); /** Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { alert('Saved value: ' + params.newValue); }); **/ //event itself is triggered by editableContainer. Description here is only for documentation }, validate: function () { if (typeof this.options.validate === 'function') { return this.options.validate.call(this, this.value); } }, /** Sets new value of editable @method setValue(value, convertStr) @param {mixed} value new value @param {boolean} convertStr whether to convert value from string to internal format **/ setValue: function(value, convertStr, response) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } if(this.container) { this.container.option('value', this.value); } $.when(this.render(response)) .then($.proxy(function() { this.handleEmpty(); }, this)); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.container) { this.container.activate(); } }, /** Removes editable feature from element @method destroy() **/ destroy: function() { this.disable(); if(this.container) { this.container.destroy(); } this.input.destroy(); if(this.options.toggle !== 'manual') { this.$element.removeClass('editable-click'); this.$element.off(this.options.toggle + '.editable'); } this.$element.off("save.internal"); this.$element.removeClass('editable editable-open editable-disabled'); this.$element.removeData('editable'); } }; /* EDITABLE PLUGIN DEFINITION * ======================= */ /** jQuery method to initialize editable element. @method $().editable(options) @params {Object} options @example $('#username').editable({ type: 'text', url: '/post', pk: 1 }); **/ $.fn.editable = function (option) { //special API methods returning non-jquery object var result = {}, args = arguments, datakey = 'editable'; switch (option) { /** Runs client-side validation for all matched editables @method validate() @returns {Object} validation errors map @example $('#username, #fullname').editable('validate'); // possible result: { username: "username is required", fullname: "fullname should be minimum 3 letters length" } **/ case 'validate': this.each(function () { var $this = $(this), data = $this.data(datakey), error; if (data && (error = data.validate())) { result[data.options.name] = error; } }); return result; /** Returns current values of editable elements. Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements. If value of some editable is `null` or `undefined` it is excluded from result object. When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object. @method getValue() @param {bool} isSingle whether to return just value of single element @returns {Object} object of element names and values @example $('#username, #fullname').editable('getValue'); //result: { username: "superuser", fullname: "John" } //isSingle = true $('#username').editable('getValue', true); //result "superuser" **/ case 'getValue': if(arguments.length === 2 && arguments[1] === true) { //isSingle = true result = this.eq(0).data(datakey).value; } else { this.each(function () { var $this = $(this), data = $this.data(datakey); if (data && data.value !== undefined && data.value !== null) { result[data.options.name] = data.input.value2submit(data.value); } }); } return result; /** This method collects values from several editable elements and submit them all to server. Internally it runs client-side validation for all fields and submits only in case of success. See <a href="#newrecord">creating new records</a> for details. Since 1.5.1 `submit` can be applied to single element to send data programmatically. In that case `url`, `success` and `error` is taken from initial options and you can just call `$('#username').editable('submit')`. @method submit(options) @param {object} options @param {object} options.url url to submit data @param {object} options.data additional data to submit @param {object} options.ajaxOptions additional ajax options @param {function} options.error(obj) error handler @param {function} options.success(obj,config) success handler @returns {Object} jQuery object **/ case 'submit': //collects value, validate and submit to server for creating new record var config = arguments[1] || {}, $elems = this, errors = this.editable('validate'); // validation ok if($.isEmptyObject(errors)) { var ajaxOptions = {}; // for single element use url, success etc from options if($elems.length === 1) { var editable = $elems.data('editable'); //standard params var params = { name: editable.options.name || '', value: editable.input.value2submit(editable.value), pk: (typeof editable.options.pk === 'function') ? editable.options.pk.call(editable.options.scope) : editable.options.pk }; //additional params if(typeof editable.options.params === 'function') { params = editable.options.params.call(editable.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) editable.options.params = $.fn.editableutils.tryParseJson(editable.options.params, true); $.extend(params, editable.options.params); } ajaxOptions = { url: editable.options.url, data: params, type: 'POST' }; // use success / error from options config.success = config.success || editable.options.success; config.error = config.error || editable.options.error; // multiple elements } else { var values = this.editable('getValue'); ajaxOptions = { url: config.url, data: values, type: 'POST' }; } // ajax success callabck (response 200 OK) ajaxOptions.success = typeof config.success === 'function' ? function(response) { config.success.call($elems, response, config); } : $.noop; // ajax error callabck ajaxOptions.error = typeof config.error === 'function' ? function() { config.error.apply($elems, arguments); } : $.noop; // extend ajaxOptions if(config.ajaxOptions) { $.extend(ajaxOptions, config.ajaxOptions); } // extra data if(config.data) { $.extend(ajaxOptions.data, config.data); } // perform ajax request $.ajax(ajaxOptions); } else { //client-side validation error if(typeof config.error === 'function') { config.error.call($elems, errors); } } return this; } //return jquery object return this.each(function () { var $this = $(this), data = $this.data(datakey), options = typeof option === 'object' && option; //for delegated targets do not store `editable` object for element //it's allows several different selectors. //see: https://github.com/vitalets/x-editable/issues/312 if(options && options.selector) { data = new Editable(this, options); return; } if (!data) { $this.data(datakey, (data = new Editable(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; $.fn.editable.defaults = { /** Type of input. Can be <code>text|textarea|select|date|checklist</code> and more @property type @type string @default 'text' **/ type: 'text', /** Sets disabled state of editable @property disabled @type boolean @default false **/ disabled: false, /** How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>. When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable. **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document. @example $('#edit-button').click(function(e) { e.stopPropagation(); $('#username').editable('toggle'); }); @property toggle @type string @default 'click' **/ toggle: 'click', /** Text shown when element is empty. @property emptytext @type string @default 'Empty' **/ emptytext: 'Empty', /** Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date. For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>. <code>auto</code> - text will be automatically set only if element is empty. <code>always|never</code> - always(never) try to set element's text. @property autotext @type string @default 'auto' **/ autotext: 'auto', /** Initial value of input. If not set, taken from element's text. Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option). For example, to display currency sign: @example <a id="price" data-type="text" data-value="100"></a> <script> $('#price').editable({ ... display: function(value) { $(this).text(value + '$'); } }) </script> @property value @type mixed @default element's text **/ value: null, /** Callback to perform custom displaying of value in element's text. If `null`, default input's display used. If `false`, no displaying methods will be called, element's text will never change. Runs under element's scope. _**Parameters:**_ * `value` current value to be displayed * `response` server response (if display called after ajax submit), since 1.4.0 For _inputs with source_ (select, checklist) parameters are different: * `value` current value to be displayed * `sourceData` array of items for current input (e.g. dropdown items) * `response` server response (if display called after ajax submit), since 1.4.0 To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`. @property display @type function|boolean @default null @since 1.2.0 @example display: function(value, sourceData) { //display checklist as comma-separated values var html = [], checked = $.fn.editableutils.itemsByValue(value, sourceData); if(checked.length) { $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); }); $(this).html(html.join(', ')); } else { $(this).empty(); } } **/ display: null, /** Css class applied when editable text is empty. @property emptyclass @type string @since 1.4.1 @default editable-empty **/ emptyclass: 'editable-empty', /** Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`). You may set it to `null` if you work with editables locally and submit them together. @property unsavedclass @type string @since 1.4.1 @default editable-unsaved **/ unsavedclass: 'editable-unsaved', /** If selector is provided, editable will be delegated to the specified targets. Usefull for dynamically generated DOM elements. **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, as they actually become editable only after first click. You should manually set class `editable-click` to these elements. Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element: @property selector @type string @since 1.4.1 @default null @example <div id="user"> <!-- empty --> <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a> <!-- non-empty --> <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a> </div> <script> $('#user').editable({ selector: 'a', url: '/post', pk: 1 }); </script> **/ selector: null, /** Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers. @property highlight @type string|boolean @since 1.4.5 @default #FFFF80 **/ highlight: '#FFFF80' }; }(window.jQuery)); /** AbstractInput - base class for all editable inputs. It defines interface to be implemented by any input type. To create your own input you can inherit from this class. @class abstractinput **/ (function ($) { "use strict"; //types $.fn.editabletypes = {}; var AbstractInput = function () { }; AbstractInput.prototype = { /** Initializes input @method init() **/ init: function(type, options, defaults) { this.type = type; this.options = $.extend({}, defaults, options); }, /* this method called before render to init $tpl that is inserted in DOM */ prerender: function() { this.$tpl = $(this.options.tpl); //whole tpl as jquery object this.$input = this.$tpl; //control itself, can be changed in render method this.$clear = null; //clear button this.error = null; //error message, if input cannot be rendered }, /** Renders input from tpl. Can return jQuery deferred object. Can be overwritten in child objects @method render() **/ render: function() { }, /** Sets element's html by value. @method value2html(value, element) @param {mixed} value @param {DOMElement} element **/ value2html: function(value, element) { $(element)[this.options.escape ? 'text' : 'html']($.trim(value)); }, /** Converts element's html to value @method html2value(html) @param {string} html @returns {mixed} **/ html2value: function(html) { return $('<div>').html(html).text(); }, /** Converts value to string (for internal compare). For submitting to server used value2submit(). @method value2str(value) @param {mixed} value @returns {string} **/ value2str: function(value) { return value; }, /** Converts string received from server into value. Usually from `data-value` attribute. @method str2value(str) @param {string} str @returns {mixed} **/ str2value: function(str) { return str; }, /** Converts value for submitting to server. Result can be string or object. @method value2submit(value) @param {mixed} value @returns {mixed} **/ value2submit: function(value) { return value; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function(value) { this.$input.val(value); }, /** Returns value of input. Value can be object (e.g. datepicker) @method input2value() **/ input2value: function() { return this.$input.val(); }, /** Activates input. For text it sets focus. @method activate() **/ activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); } }, /** Creates input. @method clear() **/ clear: function() { this.$input.val(null); }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /** attach handler to automatically submit form when value changed (useful when buttons not shown) **/ autosubmit: function() { }, /** Additional actions when destroying element **/ destroy: function() { }, // -------- helper functions -------- setClass: function() { if(this.options.inputclass) { this.$input.addClass(this.options.inputclass); } }, setAttr: function(attr) { if (this.options[attr] !== undefined && this.options[attr] !== null) { this.$input.attr(attr, this.options[attr]); } }, option: function(key, value) { this.options[key] = value; } }; AbstractInput.defaults = { /** HTML template of input. Normally you should not change it. @property tpl @type string @default '' **/ tpl: '', /** CSS class automatically applied to input @property inputclass @type string @default null **/ inputclass: null, /** If `true` - html will be escaped in content of element via $.text() method. If `false` - html will not be escaped, $.html() used. When you use own `display` function, this option obviosly has no effect. @property escape @type boolean @since 1.5.0 @default true **/ escape: true, //scope for external methods (e.g. source defined as function) //for internal use only scope: null, //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults) showbuttons: true }; $.extend($.fn.editabletypes, {abstractinput: AbstractInput}); }(window.jQuery)); /** List - abstract class for inputs that have source option loaded from js array or via ajax @class list @extends abstractinput **/ (function ($) { "use strict"; var List = function (options) { }; $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput); $.extend(List.prototype, { render: function () { var deferred = $.Deferred(); this.error = null; this.onSourceReady(function () { this.renderList(); deferred.resolve(); }, function () { this.error = this.options.sourceError; deferred.resolve(); }); return deferred.promise(); }, html2value: function (html) { return null; //can't set value by text }, value2html: function (value, element, display, response) { var deferred = $.Deferred(), success = function () { if(typeof display === 'function') { //custom display method display.call(element, value, this.sourceData, response); } else { this.value2htmlFinal(value, element); } deferred.resolve(); }; //for null value just call success without loading source if(value === null) { success.call(this); } else { this.onSourceReady(success, function () { deferred.resolve(); }); } return deferred.promise(); }, // ------------- additional functions ------------ onSourceReady: function (success, error) { //run source if it function var source; if ($.isFunction(this.options.source)) { source = this.options.source.call(this.options.scope); this.sourceData = null; //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed } else { source = this.options.source; } //if allready loaded just call success if(this.options.sourceCache && $.isArray(this.sourceData)) { success.call(this); return; } //try parse json in single quotes (for double quotes jquery does automatically) try { source = $.fn.editableutils.tryParseJson(source, false); } catch (e) { error.call(this); return; } //loading from url if (typeof source === 'string') { //try to get sourceData from cache if(this.options.sourceCache) { var cacheID = source, cache; if (!$(document).data(cacheID)) { $(document).data(cacheID, {}); } cache = $(document).data(cacheID); //check for cached data if (cache.loading === false && cache.sourceData) { //take source from cache this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); return; } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later cache.callbacks.push($.proxy(function () { this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); }, this)); //also collecting error callbacks cache.err_callbacks.push($.proxy(error, this)); return; } else { //no cache yet, activate it cache.loading = true; cache.callbacks = []; cache.err_callbacks = []; } } //ajaxOptions for source. Can be overwritten bt options.sourceOptions var ajaxOptions = $.extend({ url: source, type: 'get', cache: false, dataType: 'json', success: $.proxy(function (data) { if(cache) { cache.loading = false; } this.sourceData = this.makeArray(data); if($.isArray(this.sourceData)) { if(cache) { //store result in cache cache.sourceData = this.sourceData; //run success callbacks for other fields waiting for this source $.each(cache.callbacks, function () { this.call(); }); } this.doPrepend(); success.call(this); } else { error.call(this); if(cache) { //run error callbacks for other fields waiting for this source $.each(cache.err_callbacks, function () { this.call(); }); } } }, this), error: $.proxy(function () { error.call(this); if(cache) { cache.loading = false; //run error callbacks for other fields $.each(cache.err_callbacks, function () { this.call(); }); } }, this) }, this.options.sourceOptions); //loading sourceData from server $.ajax(ajaxOptions); } else { //options as json/array this.sourceData = this.makeArray(source); if($.isArray(this.sourceData)) { this.doPrepend(); success.call(this); } else { error.call(this); } } }, doPrepend: function () { if(this.options.prepend === null || this.options.prepend === undefined) { return; } if(!$.isArray(this.prependData)) { //run prepend if it is function (once) if ($.isFunction(this.options.prepend)) { this.options.prepend = this.options.prepend.call(this.options.scope); } //try parse json in single quotes this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true); //convert prepend from string to object if (typeof this.options.prepend === 'string') { this.options.prepend = {'': this.options.prepend}; } this.prependData = this.makeArray(this.options.prepend); } if($.isArray(this.prependData) && $.isArray(this.sourceData)) { this.sourceData = this.prependData.concat(this.sourceData); } }, /* renders input list */ renderList: function() { // this method should be overwritten in child class }, /* set element's html by value */ value2htmlFinal: function(value, element) { // this method should be overwritten in child class }, /** * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}] */ makeArray: function(data) { var count, obj, result = [], item, iterateItem; if(!data || typeof data === 'string') { return null; } if($.isArray(data)) { //array /* function to iterate inside item of array if item is object. Caclulates count of keys in item and store in obj. */ iterateItem = function (k, v) { obj = {value: k, text: v}; if(count++ >= 2) { return false;// exit from `each` if item has more than one key. } }; for(var i = 0; i < data.length; i++) { item = data[i]; if(typeof item === 'object') { count = 0; //count of keys inside item $.each(item, iterateItem); //case: [{val1: 'text1'}, {val2: 'text2} ...] if(count === 1) { result.push(obj); //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...] } else if(count > 1) { //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text') if(item.children) { item.children = this.makeArray(item.children); } result.push(item); } } else { //case: ['text1', 'text2' ...] result.push({value: item, text: item}); } } } else { //case: {val1: 'text1', val2: 'text2, ...} $.each(data, function (k, v) { result.push({value: k, text: v}); }); } return result; }, option: function(key, value) { this.options[key] = value; if(key === 'source') { this.sourceData = null; } if(key === 'prepend') { this.prependData = null; } } }); List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** Source data for list. If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]` For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order. If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option. If **function**, it should return data in format above (since 1.4.0). Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only). `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` @property source @type string | array | object | function @default null **/ source: null, /** Data automatically prepended to the beginning of dropdown list. @property prepend @type string | array | object | function @default false **/ prepend: false, /** Error message when list cannot be loaded (e.g. ajax error) @property sourceError @type string @default Error when loading list **/ sourceError: 'Error when loading list', /** if <code>true</code> and source is **string url** - results will be cached for fields with the same source. Usefull for editable column in grid to prevent extra requests. @property sourceCache @type boolean @default true @since 1.2.0 **/ sourceCache: true, /** Additional ajax options to be used in $.ajax() when loading list from server. Useful to send extra parameters (`data` key) or change request method (`type` key). @property sourceOptions @type object|function @default null @since 1.5.0 **/ sourceOptions: null }); $.fn.editabletypes.list = List; }(window.jQuery)); /** Text input @class text @extends abstractinput @final @example <a href="#" id="username" data-type="text" data-pk="1">awesome</a> <script> $(function(){ $('#username').editable({ url: '/post', title: 'Enter username' }); }); </script> **/ (function ($) { "use strict"; var Text = function (options) { this.init('text', options, Text.defaults); }; $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput); $.extend(Text.prototype, { render: function() { this.renderClear(); this.setClass(); this.setAttr('placeholder'); }, activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length); if(this.toggleClear) { this.toggleClear(); } } }, //render clear button renderClear: function() { if (this.options.clear) { this.$clear = $('<span class="editable-clear-x"></span>'); this.$input.after(this.$clear) .css('padding-right', 24) .keyup($.proxy(function(e) { //arrows, enter, tab, etc if(~$.inArray(e.keyCode, [40,38,9,13,27])) { return; } clearTimeout(this.t); var that = this; this.t = setTimeout(function() { that.toggleClear(e); }, 100); }, this)) .parent().css('position', 'relative'); this.$clear.click($.proxy(this.clear, this)); } }, postrender: function() { /* //now `clear` is positioned via css if(this.$clear) { //can position clear button only here, when form is shown and height can be calculated // var h = this.$input.outerHeight(true) || 20, var h = this.$clear.parent().height(), delta = (h - this.$clear.height()) / 2; //this.$clear.css({bottom: delta, right: delta}); } */ }, //show / hide clear button toggleClear: function(e) { if(!this.$clear) { return; } var len = this.$input.val().length, visible = this.$clear.is(':visible'); if(len && !visible) { this.$clear.show(); } if(!len && visible) { this.$clear.hide(); } }, clear: function() { this.$clear.hide(); this.$input.val('').focus(); } }); Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text">', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Whether to show `clear` button @property clear @type boolean @default true **/ clear: true }); $.fn.editabletypes.text = Text; }(window.jQuery)); /** Textarea input @class textarea @extends abstractinput @final @example <a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a> <script> $(function(){ $('#comments').editable({ url: '/post', title: 'Enter comments', rows: 10 }); }); </script> **/ (function ($) { "use strict"; var Textarea = function (options) { this.init('textarea', options, Textarea.defaults); }; $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput); $.extend(Textarea.prototype, { render: function () { this.setClass(); this.setAttr('placeholder'); this.setAttr('rows'); //ctrl + enter this.$input.keydown(function (e) { if (e.ctrlKey && e.which === 13) { $(this).closest('form').submit(); } }); }, //using `white-space: pre-wrap` solves \n <--> BR conversion very elegant! /* value2html: function(value, element) { var html = '', lines; if(value) { lines = value.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } html = lines.join('<br>'); } $(element).html(html); }, html2value: function(html) { if(!html) { return ''; } var regex = new RegExp(String.fromCharCode(10), 'g'); var lines = html.split(/<br\s*\/?>/i); for (var i = 0; i < lines.length; i++) { var text = $('<div>').html(lines[i]).text(); // Remove newline characters (\n) to avoid them being converted by value2html() method // thus adding extra <br> tags text = text.replace(regex, ''); lines[i] = text; } return lines.join("\n"); }, */ activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); } }); Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <textarea></textarea> **/ tpl:'<textarea></textarea>', /** @property inputclass @default input-large **/ inputclass: 'input-large', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Number of rows in textarea @property rows @type integer @default 7 **/ rows: 7 }); $.fn.editabletypes.textarea = Textarea; }(window.jQuery)); /** Select (dropdown) @class select @extends list @final @example <a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a> <script> $(function(){ $('#status').editable({ value: 2, source: [ {value: 1, text: 'Active'}, {value: 2, text: 'Blocked'}, {value: 3, text: 'Deleted'} ] }); }); </script> **/ (function ($) { "use strict"; var Select = function (options) { this.init('select', options, Select.defaults); }; $.fn.editableutils.inherit(Select, $.fn.editabletypes.list); $.extend(Select.prototype, { renderList: function() { this.$input.empty(); var fillItems = function($el, data) { var attr; if($.isArray(data)) { for(var i=0; i<data.length; i++) { attr = {}; if(data[i].children) { attr.label = data[i].text; $el.append(fillItems($('<optgroup>', attr), data[i].children)); } else { attr.value = data[i].value; if(data[i].disabled) { attr.disabled = true; } $el.append($('<option>', attr).text(data[i].text)); } } } return $el; }; fillItems(this.$input, this.sourceData); this.setClass(); //enter submit this.$input.on('keydown.editable', function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); }, value2htmlFinal: function(value, element) { var text = '', items = $.fn.editableutils.itemsByValue(value, this.sourceData); if(items.length) { text = items[0].text; } //$(element).text(text); $.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element); }, autosubmit: function() { this.$input.off('keydown.editable').on('change.editable', function(){ $(this).closest('form').submit(); }); } }); Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <select></select> **/ tpl:'<select></select>' }); $.fn.editabletypes.select = Select; }(window.jQuery)); /** List of checkboxes. Internally value stored as javascript array of values. @class checklist @extends list @final @example <a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a> <script> $(function(){ $('#options').editable({ value: [2, 3], source: [ {value: 1, text: 'option1'}, {value: 2, text: 'option2'}, {value: 3, text: 'option3'} ] }); }); </script> **/ (function ($) { "use strict"; var Checklist = function (options) { this.init('checklist', options, Checklist.defaults); }; $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list); $.extend(Checklist.prototype, { renderList: function() { var $label, $div; this.$tpl.empty(); if(!$.isArray(this.sourceData)) { return; } for(var i=0; i<this.sourceData.length; i++) { $label = $('<label>').append($('<input>', { type: 'checkbox', value: this.sourceData[i].value })) .append($('<span>').text(' '+this.sourceData[i].text)); $('<div>').append($label).appendTo(this.$tpl); } this.$input = this.$tpl.find('input[type="checkbox"]'); this.setClass(); }, value2str: function(value) { return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : ''; }, //parse separated string str2value: function(str) { var reg, value = null; if(typeof str === 'string' && str.length) { reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*'); value = str.split(reg); } else if($.isArray(str)) { value = str; } else { value = [str]; } return value; }, //set checked on required checkboxes value2input: function(value) { this.$input.prop('checked', false); if($.isArray(value) && value.length) { this.$input.each(function(i, el) { var $el = $(el); // cannot use $.inArray as it performs strict comparison $.each(value, function(j, val){ /*jslint eqeq: true*/ if($el.val() == val) { /*jslint eqeq: false*/ $el.prop('checked', true); } }); }); } }, input2value: function() { var checked = []; this.$input.filter(':checked').each(function(i, el) { checked.push($(el).val()); }); return checked; }, //collect text of checked boxes value2htmlFinal: function(value, element) { var html = [], checked = $.fn.editableutils.itemsByValue(value, this.sourceData), escape = this.options.escape; if(checked.length) { $.each(checked, function(i, v) { var text = escape ? $.fn.editableutils.escape(v.text) : v.text; html.push(text); }); $(element).html(html.join('<br>')); } else { $(element).empty(); } }, activate: function() { this.$input.first().focus(); }, autosubmit: function() { this.$input.on('keydown', function(e){ if (e.which === 13) { $(this).closest('form').submit(); } }); } }); Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-checklist"></div>', /** @property inputclass @type string @default null **/ inputclass: null, /** Separator of values when reading from `data-value` attribute @property separator @type string @default ',' **/ separator: ',' }); $.fn.editabletypes.checklist = Checklist; }(window.jQuery)); /** HTML5 input types. Following types are supported: * password * email * url * tel * number * range * time Learn more about html5 inputs: http://www.w3.org/wiki/HTML5_form_additions To check browser compatibility please see: https://developer.mozilla.org/en-US/docs/HTML/Element/Input @class html5types @extends text @final @since 1.3.0 @example <a href="#" id="email" data-type="email" data-pk="1">[email protected]</a> <script> $(function(){ $('#email').editable({ url: '/post', title: 'Enter email' }); }); </script> **/ /** @property tpl @default depends on type **/ /* Password */ (function ($) { "use strict"; var Password = function (options) { this.init('password', options, Password.defaults); }; $.fn.editableutils.inherit(Password, $.fn.editabletypes.text); $.extend(Password.prototype, { //do not display password, show '[hidden]' instead value2html: function(value, element) { if(value) { $(element).text('[hidden]'); } else { $(element).empty(); } }, //as password not displayed, should not set value by html html2value: function(html) { return null; } }); Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="password">' }); $.fn.editabletypes.password = Password; }(window.jQuery)); /* Email */ (function ($) { "use strict"; var Email = function (options) { this.init('email', options, Email.defaults); }; $.fn.editableutils.inherit(Email, $.fn.editabletypes.text); Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="email">' }); $.fn.editabletypes.email = Email; }(window.jQuery)); /* Url */ (function ($) { "use strict"; var Url = function (options) { this.init('url', options, Url.defaults); }; $.fn.editableutils.inherit(Url, $.fn.editabletypes.text); Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="url">' }); $.fn.editabletypes.url = Url; }(window.jQuery)); /* Tel */ (function ($) { "use strict"; var Tel = function (options) { this.init('tel', options, Tel.defaults); }; $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text); Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="tel">' }); $.fn.editabletypes.tel = Tel; }(window.jQuery)); /* Number */ (function ($) { "use strict"; var NumberInput = function (options) { this.init('number', options, NumberInput.defaults); }; $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text); $.extend(NumberInput.prototype, { render: function () { NumberInput.superclass.render.call(this); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); }, postrender: function() { if(this.$clear) { //increase right ffset for up/down arrows this.$clear.css({right: 24}); /* //can position clear button only here, when form is shown and height can be calculated var h = this.$input.outerHeight(true) || 20, delta = (h - this.$clear.height()) / 2; //add 12px to offset right for up/down arrows this.$clear.css({top: delta, right: delta + 16}); */ } } }); NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="number">', inputclass: 'input-mini', min: null, max: null, step: null }); $.fn.editabletypes.number = NumberInput; }(window.jQuery)); /* Range (inherit from number) */ (function ($) { "use strict"; var Range = function (options) { this.init('range', options, Range.defaults); }; $.fn.editableutils.inherit(Range, $.fn.editabletypes.number); $.extend(Range.prototype, { render: function () { this.$input = this.$tpl.filter('input'); this.setClass(); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); this.$input.on('input', function(){ $(this).siblings('output').text($(this).val()); }); }, activate: function() { this.$input.focus(); } }); Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, { tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>', inputclass: 'input-medium' }); $.fn.editabletypes.range = Range; }(window.jQuery)); /* Time */ (function ($) { "use strict"; var Time = function (options) { this.init('time', options, Time.defaults); }; //inherit from abstract, as inheritance from text gives selection error. $.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput); $.extend(Time.prototype, { render: function() { this.setClass(); } }); Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { tpl: '<input type="time">' }); $.fn.editabletypes.time = Time; }(window.jQuery)); /** Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2. Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options. You should manually download and include select2 distributive: <link href="select2/select2.css" rel="stylesheet" type="text/css"></link> <script src="select2/select2.js"></script> To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link> **Note:** currently `autotext` feature does not work for select2 with `ajax` remote source. You need initially put both `data-value` and element's text youself: <a href="#" data-type="select2" data-value="1">Text1</a> @class select2 @extends abstractinput @since 1.4.1 @final @example <a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a> <script> $(function(){ //local source $('#country').editable({ source: [ {id: 'gb', text: 'Great Britain'}, {id: 'us', text: 'United States'}, {id: 'ru', text: 'Russia'} ], select2: { multiple: true } }); //remote source (simple) $('#country').editable({ source: '/getCountries', select2: { placeholder: 'Select Country', minimumInputLength: 1 } }); //remote source (advanced) $('#country').editable({ select2: { placeholder: 'Select Country', allowClear: true, minimumInputLength: 3, id: function (item) { return item.CountryId; }, ajax: { url: '/getCountries', dataType: 'json', data: function (term, page) { return { query: term }; }, results: function (data, page) { return { results: data }; } }, formatResult: function (item) { return item.CountryName; }, formatSelection: function (item) { return item.CountryName; }, initSelection: function (element, callback) { return $.get('/getCountryById', { query: element.val() }, function (data) { callback(data); }); } } }); }); </script> **/ (function ($) { "use strict"; var Constructor = function (options) { this.init('select2', options, Constructor.defaults); options.select2 = options.select2 || {}; this.sourceData = null; //placeholder if(options.placeholder) { options.select2.placeholder = options.placeholder; } //if not `tags` mode, use source if(!options.select2.tags && options.source) { var source = options.source; //if source is function, call it (once!) if ($.isFunction(options.source)) { source = options.source.call(options.scope); } if (typeof source === 'string') { options.select2.ajax = options.select2.ajax || {}; //some default ajax params if(!options.select2.ajax.data) { options.select2.ajax.data = function(term) {return { query:term };}; } if(!options.select2.ajax.results) { options.select2.ajax.results = function(data) { return {results:data };}; } options.select2.ajax.url = source; } else { //check format and convert x-editable format to select2 format (if needed) this.sourceData = this.convertSource(source); options.select2.data = this.sourceData; } } //overriding objects in config (as by default jQuery extend() is not recursive) this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2); //detect whether it is multi-valued this.isMultiple = this.options.select2.tags || this.options.select2.multiple; this.isRemote = ('ajax' in this.options.select2); //store function returning ID of item //should be here as used inautotext for local source this.idFunc = this.options.select2.id; if (typeof(this.idFunc) !== "function") { var idKey = this.idFunc || 'id'; this.idFunc = function (e) { return e[idKey]; }; } //store function that renders text in select2 this.formatSelection = this.options.select2.formatSelection; if (typeof(this.formatSelection) !== "function") { this.formatSelection = function (e) { return e.text; }; } }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function() { this.setClass(); //can not apply select2 here as it calls initSelection //over input that does not have correct value yet. //apply select2 only in value2input //this.$input.select2(this.options.select2); //when data is loaded via ajax, we need to know when it's done to populate listData if(this.isRemote) { //listen to loaded event to populate data this.$input.on('select2-loaded', $.proxy(function(e) { this.sourceData = e.items.results; }, this)); } //trigger resize of editableform to re-position container in multi-valued mode if(this.isMultiple) { this.$input.on('change', function() { $(this).closest('form').parent().triggerHandler('resize'); }); } }, value2html: function(value, element) { var text = '', data, that = this; if(this.options.select2.tags) { //in tags mode just assign value data = value; //data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc); } else if(this.sourceData) { data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); } else { //can not get list of possible values //(e.g. autotext for select2 with ajax source) } //data may be array (when multiple values allowed) if($.isArray(data)) { //collect selected data and show with separator text = []; $.each(data, function(k, v){ text.push(v && typeof v === 'object' ? that.formatSelection(v) : v); }); } else if(data) { text = that.formatSelection(data); } text = $.isArray(text) ? text.join(this.options.viewseparator) : text; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null; }, value2input: function(value) { // if value array => join it anyway if($.isArray(value)) { value = value.join(this.getSeparator()); } //for remote source just set value, text is updated by initSelection if(!this.$input.data('select2')) { this.$input.val(value); this.$input.select2(this.options.select2); } else { //second argument needed to separate initial change from user's click (for autosubmit) this.$input.val(value).trigger('change', true); //Uncaught Error: cannot call val() if initSelection() is not defined //this.$input.select2('val', value); } // if defined remote source AND no multiple mode AND no user's initSelection provided --> // we should somehow get text for provided id. // The solution is to use element's text as text for that id (exclude empty) if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) { // customId and customText are methods to extract `id` and `text` from data object // we can use this workaround only if user did not define these methods // otherwise we cant construct data object var customId = this.options.select2.id, customText = this.options.select2.formatSelection; if(!customId && !customText) { var $el = $(this.options.scope); if (!$el.data('editable').isEmpty) { var data = {id: value, text: $el.text()}; this.$input.select2('data', data); } } } }, input2value: function() { return this.$input.select2('val'); }, str2value: function(str, separator) { if(typeof str !== 'string' || !this.isMultiple) { return str; } separator = separator || this.getSeparator(); var val, i, l; if (str === null || str.length < 1) { return null; } val = str.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) { val[i] = $.trim(val[i]); } return val; }, autosubmit: function() { this.$input.on('change', function(e, isInitial){ if(!isInitial) { $(this).closest('form').submit(); } }); }, getSeparator: function() { return this.options.select2.separator || $.fn.select2.defaults.separator; }, /* Converts source from x-editable format: {value: 1, text: "1"} to select2 format: {id: 1, text: "1"} */ convertSource: function(source) { if($.isArray(source) && source.length && source[0].value !== undefined) { for(var i = 0; i<source.length; i++) { if(source[i].value !== undefined) { source[i].id = source[i].value; delete source[i].value; } } } return source; }, destroy: function() { if(this.$input.data('select2')) { this.$input.select2('destroy'); } } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="hidden"> **/ tpl:'<input type="hidden">', /** Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2). @property select2 @type object @default null **/ select2: null, /** Placeholder attribute of select @property placeholder @type string @default null **/ placeholder: null, /** Source data for select. It will be assigned to select2 `data` property and kept here just for convenience. Please note, that format is different from simple `select` input: use 'id' instead of 'value'. E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`. @property source @type array|string|function @default null **/ source: null, /** Separator used to display tags. @property viewseparator @type string @default ', ' **/ viewseparator: ', ' }); $.fn.editabletypes.select2 = Constructor; }(window.jQuery)); /** * Combodate - 1.0.5 * Dropdown date and time picker. * Converts text input into dropdowns to pick day, month, year, hour, minute and second. * Uses momentjs as datetime library http://momentjs.com. * For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang * * Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight * In combodate: * 12:00 pm --> 12:00 (24-h format, midday) * 12:00 am --> 00:00 (24-h format, midnight, start of day) * * Differs from momentjs parse rules: * 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change) * 00:00 am, 12:00 am --> 00:00 (24-h format, day not change) * * * Author: Vitaliy Potapov * Project page: http://github.com/vitalets/combodate * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License. **/ (function ($) { var Combodate = function (element, options) { this.$element = $(element); if(!this.$element.is('input')) { $.error('Combodate should be applied to INPUT element'); return; } this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data()); this.init(); }; Combodate.prototype = { constructor: Combodate, init: function () { this.map = { //key regexp moment.method day: ['D', 'date'], month: ['M', 'month'], year: ['Y', 'year'], hour: ['[Hh]', 'hours'], minute: ['m', 'minutes'], second: ['s', 'seconds'], ampm: ['[Aa]', ''] }; this.$widget = $('<span class="combodate"></span>').html(this.getTemplate()); this.initCombos(); //update original input on change this.$widget.on('change', 'select', $.proxy(function(e) { this.$element.val(this.getValue()).change(); // update days count if month or year changes if (this.options.smartDays) { if ($(e.target).is('.month') || $(e.target).is('.year')) { this.fillCombo('day'); } } }, this)); this.$widget.find('select').css('width', 'auto'); // hide original input and insert widget this.$element.hide().after(this.$widget); // set initial value this.setValue(this.$element.val() || this.options.value); }, /* Replace tokens in template with <select> elements */ getTemplate: function() { var tpl = this.options.template; //first pass $.each(this.map, function(k, v) { v = v[0]; var r = new RegExp(v+'+'), token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace(r, '{'+token+'}'); }); //replace spaces with &nbsp; tpl = tpl.replace(/ /g, '&nbsp;'); //second pass $.each(this.map, function(k, v) { v = v[0]; var token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>'); }); return tpl; }, /* Initialize combos that presents in template */ initCombos: function() { for (var k in this.map) { var $c = this.$widget.find('.'+k); // set properties like this.$day, this.$month etc. this['$'+k] = $c.length ? $c : null; // fill with items this.fillCombo(k); } }, /* Fill combo with items */ fillCombo: function(k) { var $combo = this['$'+k]; if (!$combo) { return; } // define method name to fill items, e.g `fillDays` var f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); var items = this[f](); var value = $combo.val(); $combo.empty(); for(var i=0; i<items.length; i++) { $combo.append('<option value="'+items[i][0]+'">'+items[i][1]+'</option>'); } $combo.val(value); }, /* Initialize items of combos. Handles `firstItem` option */ fillCommon: function(key) { var values = [], relTime; if(this.options.firstItem === 'name') { //need both to support moment ver < 2 and >= 2 relTime = moment.relativeTime || moment.langData()._relativeTime; var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key]; //take last entry (see momentjs lang files structure) header = header.split(' ').reverse()[0]; values.push(['', header]); } else if(this.options.firstItem === 'empty') { values.push(['', '']); } return values; }, /* fill day */ fillDay: function() { var items = this.fillCommon('d'), name, i, twoDigit = this.options.template.indexOf('DD') !== -1, daysCount = 31; // detect days count (depends on month and year) // originally https://github.com/vitalets/combodate/pull/7 if (this.options.smartDays && this.$month && this.$year) { var month = parseInt(this.$month.val(), 10); var year = parseInt(this.$year.val(), 10); if (!isNaN(month) && !isNaN(year)) { daysCount = moment([year, month]).daysInMonth(); } } for (i = 1; i <= daysCount; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill month */ fillMonth: function() { var items = this.fillCommon('M'), name, i, longNames = this.options.template.indexOf('MMMM') !== -1, shortNames = this.options.template.indexOf('MMM') !== -1, twoDigit = this.options.template.indexOf('MM') !== -1; for(i=0; i<=11; i++) { if(longNames) { //see https://github.com/timrwood/momentjs.com/pull/36 name = moment().date(1).month(i).format('MMMM'); } else if(shortNames) { name = moment().date(1).month(i).format('MMM'); } else if(twoDigit) { name = this.leadZero(i+1); } else { name = i+1; } items.push([i, name]); } return items; }, /* fill year */ fillYear: function() { var items = [], name, i, longNames = this.options.template.indexOf('YYYY') !== -1; for(i=this.options.maxYear; i>=this.options.minYear; i--) { name = longNames ? i : (i+'').substring(2); items[this.options.yearDescending ? 'push' : 'unshift']([i, name]); } items = this.fillCommon('y').concat(items); return items; }, /* fill hour */ fillHour: function() { var items = this.fillCommon('h'), name, i, h12 = this.options.template.indexOf('h') !== -1, h24 = this.options.template.indexOf('H') !== -1, twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1, min = h12 ? 1 : 0, max = h12 ? 12 : 23; for(i=min; i<=max; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill minute */ fillMinute: function() { var items = this.fillCommon('m'), name, i, twoDigit = this.options.template.indexOf('mm') !== -1; for(i=0; i<=59; i+= this.options.minuteStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill second */ fillSecond: function() { var items = this.fillCommon('s'), name, i, twoDigit = this.options.template.indexOf('ss') !== -1; for(i=0; i<=59; i+= this.options.secondStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill ampm */ fillAmpm: function() { var ampmL = this.options.template.indexOf('a') !== -1, ampmU = this.options.template.indexOf('A') !== -1, items = [ ['am', ampmL ? 'am' : 'AM'], ['pm', ampmL ? 'pm' : 'PM'] ]; return items; }, /* Returns current date value from combos. If format not specified - `options.format` used. If format = `null` - Moment object returned. */ getValue: function(format) { var dt, values = {}, that = this, notSelected = false; //getting selected values $.each(this.map, function(k, v) { if(k === 'ampm') { return; } var def = k === 'day' ? 1 : 0; values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def; if(isNaN(values[k])) { notSelected = true; return false; } }); //if at least one visible combo not selected - return empty string if(notSelected) { return ''; } //convert hours 12h --> 24h if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour === 12) { values.hour = this.$ampm.val() === 'am' ? 0 : 12; } else { values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12; } } dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]); //highlight invalid date this.highlight(dt); format = format === undefined ? this.options.format : format; if(format === null) { return dt.isValid() ? dt : null; } else { return dt.isValid() ? dt.format(format) : ''; } }, setValue: function(value) { if(!value) { return; } var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value), that = this, values = {}; //function to find nearest value in select options function getNearest($select, value) { var delta = {}; $select.children('option').each(function(i, opt){ var optValue = $(opt).attr('value'), distance; if(optValue === '') return; distance = Math.abs(optValue - value); if(typeof delta.distance === 'undefined' || distance < delta.distance) { delta = {value: optValue, distance: distance}; } }); return delta.value; } if(dt.isValid()) { //read values from date object $.each(this.map, function(k, v) { if(k === 'ampm') { return; } values[k] = dt[v[1]](); }); if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour >= 12) { values.ampm = 'pm'; if(values.hour > 12) { values.hour -= 12; } } else { values.ampm = 'am'; if(values.hour === 0) { values.hour = 12; } } } $.each(values, function(k, v) { //call val() for each existing combo, e.g. this.$hour.val() if(that['$'+k]) { if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } that['$'+k].val(v); } }); // update days count if (this.options.smartDays) { this.fillCombo('day'); } this.$element.val(dt.format(this.options.format)).change(); } }, /* highlight combos if date is invalid */ highlight: function(dt) { if(!dt.isValid()) { if(this.options.errorClass) { this.$widget.addClass(this.options.errorClass); } else { //store original border color if(!this.borderColor) { this.borderColor = this.$widget.find('select').css('border-color'); } this.$widget.find('select').css('border-color', 'red'); } } else { if(this.options.errorClass) { this.$widget.removeClass(this.options.errorClass); } else { this.$widget.find('select').css('border-color', this.borderColor); } } }, leadZero: function(v) { return v <= 9 ? '0' + v : v; }, destroy: function() { this.$widget.remove(); this.$element.removeData('combodate').show(); } //todo: clear method }; $.fn.combodate = function ( option ) { var d, args = Array.apply(null, arguments); args.shift(); //getValue returns date as string / object (not jQuery object) if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) { return d.getValue.apply(d, args); } return this.each(function () { var $this = $(this), data = $this.data('combodate'), options = typeof option == 'object' && option; if (!data) { $this.data('combodate', (data = new Combodate(this, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.combodate.defaults = { //in this format value stored in original input format: 'DD-MM-YYYY HH:mm', //in this format items in dropdowns are displayed template: 'D / MMM / YYYY H : mm', //initial value, can be `new Date()` value: null, minYear: 1970, maxYear: 2015, yearDescending: true, minuteStep: 5, secondStep: 1, firstItem: 'empty', //'name', 'empty', 'none' errorClass: null, roundTime: true, // whether to round minutes and seconds if step > 1 smartDays: false // whether days in combo depend on selected month: 31, 30, 28 }; }(window.jQuery)); /** Combodate input - dropdown date and time picker. Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com). <script src="js/moment.min.js"></script> Allows to input: * only date * only time * both date and time Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker. Internally value stored as `momentjs` object. @class combodate @extends abstractinput @final @since 1.4.0 @example <a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a> <script> $(function(){ $('#dob').editable({ format: 'YYYY-MM-DD', viewformat: 'DD.MM.YYYY', template: 'D / MMMM / YYYY', combodate: { minYear: 2000, maxYear: 2015, minuteStep: 1 } } }); }); </script> **/ /*global moment*/ (function ($) { "use strict"; var Constructor = function (options) { this.init('combodate', options, Constructor.defaults); //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse combodate config defined as json string in data-combodate options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true); //overriding combodate config (as by default jQuery extend() is not recursive) this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, { format: this.options.format, template: this.options.template }); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function () { this.$input.combodate(this.options.combodate); if($.fn.editableform.engine === 'bs3') { this.$input.siblings().find('select').addClass('form-control'); } if(this.options.inputclass) { this.$input.siblings().find('select').addClass(this.options.inputclass); } //"clear" link /* if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } */ }, value2html: function(value, element) { var text = value ? value.format(this.options.viewformat) : ''; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return html ? moment(html, this.options.viewformat) : null; }, value2str: function(value) { return value ? value.format(this.options.format) : ''; }, str2value: function(str) { return str ? moment(str, this.options.format) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.combodate('setValue', value); }, input2value: function() { return this.$input.combodate('getValue', null); }, activate: function() { this.$input.siblings('.combodate').find('select').eq(0).focus(); }, /* clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); }, */ autosubmit: function() { } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl:'<input type="text">', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format) @property format @type string @default YYYY-MM-DD **/ format:'YYYY-MM-DD', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to `format`. @property viewformat @type string @default null **/ viewformat: null, /** Template used for displaying dropdowns. @property template @type string @default D / MMM / YYYY **/ template: 'D / MMM / YYYY', /** Configuration of combodate. Full list of options: http://vitalets.github.com/combodate/#docs @property combodate @type object @default null **/ combodate: null /* (not implemented yet) Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' */ //clear: '&times; clear' }); $.fn.editabletypes.combodate = Constructor; }(window.jQuery)); /* Editableform based on jQuery UI */ (function ($) { "use strict"; $.extend($.fn.editableform.Constructor.prototype, { initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } this.$form.find('.editable-submit').button({ icons: { primary: "ui-icon-check" }, text: false }).removeAttr('title'); this.$form.find('.editable-cancel').button({ icons: { primary: "ui-icon-closethick" }, text: false }).removeAttr('title'); } }); //error classes $.fn.editableform.errorGroupClass = null; $.fn.editableform.errorBlockClass = 'ui-state-error'; //engine $.fn.editableform.engine = 'jquery-ui'; }(window.jQuery)); /** * Editable jQuery UI Tooltip * --------------------- * requires jquery ui 1.9.x */ (function ($) { "use strict"; //extend methods $.extend($.fn.editableContainer.Popup.prototype, { containerName: 'tooltip', //jQuery method, aplying the widget //object name in element's .data() containerDataName: 'ui-tooltip', innerCss: '.ui-tooltip-content', defaults: $.ui.tooltip.prototype.options, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; //check that jQueryUI build contains tooltip widget if(!$.ui[this.containerName]) { $.error('Please use jQueryUI with "tooltip" widget! http://jqueryui.com/download'); return; } //defaults for tooltip for(var k in this.options) { if(k in this.defaults) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, initContainer: function(){ this.handlePlacement(); $.extend(this.containerOptions, { items: '*', content: ' ', track: false, open: $.proxy(function() { //disable events hiding tooltip by default this.container()._on(this.container().element, { mouseleave: function(e){ e.stopImmediatePropagation(); }, focusout: function(e){ e.stopImmediatePropagation(); } }); }, this) }); this.call(this.containerOptions); //disable standart triggering tooltip events this.container()._off(this.container().element, 'mouseover focusin'); }, tip: function() { return this.container() ? this.container()._find(this.container().element) : null; }, innerShow: function() { this.call('open'); var label = this.options.title || this.$element.data( "ui-tooltip-title") || this.$element.data( "originalTitle"); this.tip().find(this.innerCss).empty().append($('<label>').text(label)); }, innerHide: function() { this.call('close'); }, innerDestroy: function() { /* tooltip destroys itself on hide */ }, setPosition: function() { this.tip().position( $.extend({ of: this.$element }, this.containerOptions.position ) ); }, handlePlacement: function() { var pos; switch(this.options.placement) { case 'top': pos = { my: "center bottom-5", at: "center top", collision: 'flipfit' }; break; case 'right': pos = { my: "left+5 center", at: "right center", collision: 'flipfit' }; break; case 'bottom': pos = { my: "center top+5", at: "center bottom", collision: 'flipfit' }; break; case 'left': pos = { my: "right-5 center", at: "left center", collision: 'flipfit' }; break; } this.containerOptions.position = pos; } }); }(window.jQuery)); /** jQuery UI Datepicker. Description and examples: http://jqueryui.com/datepicker. This input is also accessible as **date** type. Do not use it together with __bootstrap-datepicker__ as both apply <code>$().datepicker()</code> method. For **i18n** you should include js file from here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n. @class dateui @extends abstractinput @final @example <a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a> <script> $(function(){ $('#dob').editable({ format: 'yyyy-mm-dd', viewformat: 'dd/mm/yyyy', datepicker: { firstDay: 1 } } }); }); </script> **/ (function ($) { "use strict"; var DateUI = function (options) { this.init('dateui', options, DateUI.defaults); this.initPicker(options, DateUI.defaults); }; $.fn.editableutils.inherit(DateUI, $.fn.editabletypes.abstractinput); $.extend(DateUI.prototype, { initPicker: function(options, defaults) { //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //correct formats: replace yyyy with yy (for compatibility with bootstrap datepicker) this.options.viewformat = this.options.viewformat.replace('yyyy', 'yy'); this.options.format = this.options.format.replace('yyyy', 'yy'); //overriding datepicker config (as by default jQuery extend() is not recursive) //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, { dateFormat: this.options.viewformat }); }, render: function () { this.$input.datepicker(this.options.datepicker); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { var text = $.datepicker.formatDate(this.options.viewformat, value); DateUI.superclass.value2html.call(this, text, element); }, html2value: function(html) { if(typeof html !== 'string') { return html; } //if string does not match format, UI datepicker throws exception var d; try { d = $.datepicker.parseDate(this.options.viewformat, html); } catch(e) {} return d; }, value2str: function(value) { return $.datepicker.formatDate(this.options.format, value); }, str2value: function(str) { if(typeof str !== 'string') { return str; } //if string does not match format, UI datepicker throws exception var d; try { d = $.datepicker.parseDate(this.options.format, str); } catch(e) {} return d; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.datepicker('setDate', value); }, input2value: function() { return this.$input.datepicker('getDate'); }, activate: function() { }, clear: function() { this.$input.datepicker('setDate', null); // submit automatically whe that are no buttons if(this.isAutosubmit) { this.submit(); } }, autosubmit: function() { this.isAutosubmit = true; this.$input.on('mouseup', 'table.ui-datepicker-calendar a.ui-state-default', $.proxy(this.submit, this)); }, submit: function() { var $form = this.$input.closest('form'); setTimeout(function() { $form.submit(); }, 200); } }); DateUI.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Full list of tokens: http://docs.jquery.com/UI/Datepicker/formatDate @property format @type string @default yyyy-mm-dd **/ format:'yyyy-mm-dd', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datepicker. Full list of options: http://api.jqueryui.com/datepicker @property datepicker @type object @default { firstDay: 0, changeYear: true, changeMonth: true } **/ datepicker: { firstDay: 0, changeYear: true, changeMonth: true, showOtherMonths: true }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.dateui = DateUI; }(window.jQuery)); /** jQuery UI datefield input - modification for inline mode. Shows normal <input type="text"> and binds popup datepicker. Automatically shown in inline mode. @class dateuifield @extends dateui @since 1.4.0 **/ (function ($) { "use strict"; var DateUIField = function (options) { this.init('dateuifield', options, DateUIField.defaults); this.initPicker(options, DateUIField.defaults); }; $.fn.editableutils.inherit(DateUIField, $.fn.editabletypes.dateui); $.extend(DateUIField.prototype, { render: function () { // this.$input = this.$tpl.find('input'); this.$input.datepicker(this.options.datepicker); $.fn.editabletypes.text.prototype.renderClear.call(this); }, value2input: function(value) { this.$input.val($.datepicker.formatDate(this.options.viewformat, value)); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, toggleClear: function() { $.fn.editabletypes.text.prototype.toggleClear.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateUIField.defaults = $.extend({}, $.fn.editabletypes.dateui.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text"/>', /** @property inputclass @default null **/ inputclass: null, /* datepicker config */ datepicker: { showOn: "button", buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif", buttonImageOnly: true, firstDay: 0, changeYear: true, changeMonth: true, showOtherMonths: true }, /* disable clear link */ clear: false }); $.fn.editabletypes.dateuifield = DateUIField; }(window.jQuery));
src/components/List.js
jcmnunes/josenunesxyz
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import ListItem from './ListItem'; const StyledList = styled.ul` color: ${props => props.theme.neutral100}; margin-bottom: 0; `; class List extends Component { render() { const { data } = this.props; return ( <StyledList> {data.map(item => ( <ListItem key={item.key} data={item} /> ))} </StyledList> ); } } List.propTypes = { data: PropTypes.array.isRequired, }; export default List;
client/extensions/woocommerce/app/store-stats/listview.js
Automattic/woocommerce-connect-client
/** @format */ /** * External dependencies */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; /** * Internal dependencies */ import { getSelectedSiteId, getSelectedSiteSlug } from 'state/ui/selectors'; import { getQueries } from './utils'; import JetpackColophon from 'components/jetpack-colophon'; import List from './store-stats-list'; import Main from 'components/main'; import Module from './store-stats-module'; import { topProducts, topCategories, topCoupons } from 'woocommerce/app/store-stats/constants'; import QuerySiteStats from 'components/data/query-site-stats'; import StoreStatsPeriodNav from 'woocommerce/app/store-stats/store-stats-period-nav'; import PageViewTracker from 'lib/analytics/page-view-tracker'; import titlecase from 'to-title-case'; const listType = { products: topProducts, categories: topCategories, coupons: topCoupons, }; class StoreStatsListView extends Component { static propTypes = { path: PropTypes.string.isRequired, selectedDate: PropTypes.string, siteId: PropTypes.number, type: PropTypes.string.isRequired, unit: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, }; render() { const { siteId, slug, selectedDate, type, unit, queryParams } = this.props; const { topListQuery } = getQueries( unit, selectedDate, { topListQuery: { limit: 100 } } ); const statType = listType[ type ].statType; return ( <Main className="store-stats__list-view woocommerce" wideLayout> <PageViewTracker path={ `/store/stats/${ type }/${ unit }/:site` } title={ `Store > Stats > ${ titlecase( type ) } > ${ titlecase( unit ) }` } /> { siteId && ( <QuerySiteStats statType={ statType } siteId={ siteId } query={ topListQuery } /> ) } <StoreStatsPeriodNav type={ type } selectedDate={ selectedDate } unit={ unit } slug={ slug } query={ topListQuery } statType={ statType } title={ listType[ type ].title } queryParams={ queryParams } /> <Module siteId={ siteId } emptyMessage={ listType[ type ].empty } query={ topListQuery } statType={ statType } > <List siteId={ siteId } values={ listType[ type ].values } query={ topListQuery } statType={ statType } /> </Module> <JetpackColophon /> </Main> ); } } export default connect( state => ( { slug: getSelectedSiteSlug( state ), siteId: getSelectedSiteId( state ), } ) )( StoreStatsListView );
ajax/libs/vue/2.2.0-beta.2/vue.common.min.js
wout/cdnjs
"use strict";function _toString(e){return null==e?"":"object"==typeof e?JSON.stringify(e,null,2):String(e)}function toNumber(e){var t=parseFloat(e);return isNaN(t)?e:t}function makeMap(e,t){for(var n=Object.create(null),r=e.split(","),o=0;o<r.length;o++)n[r[o]]=!0;return t?function(e){return n[e.toLowerCase()]}:function(e){return n[e]}}function remove(e,t){if(e.length){var n=e.indexOf(t);if(n>-1)return e.splice(n,1)}}function hasOwn(e,t){return hasOwnProperty.call(e,t)}function isPrimitive(e){return"string"==typeof e||"number"==typeof e}function cached(e){var t=Object.create(null);return function(n){var r=t[n];return r||(t[n]=e(n))}}function bind(e,t){function n(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}return n._length=e.length,n}function toArray(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function extend(e,t){for(var n in t)e[n]=t[n];return e}function isObject(e){return null!==e&&"object"==typeof e}function isPlainObject(e){return toString.call(e)===OBJECT_STRING}function toObject(e){for(var t={},n=0;n<e.length;n++)e[n]&&extend(t,e[n]);return t}function noop(){}function genStaticKeys(e){return e.reduce(function(e,t){return e.concat(t.staticKeys||[])},[]).join(",")}function looseEqual(e,t){var n=isObject(e),r=isObject(t);return n&&r?JSON.stringify(e)===JSON.stringify(t):!n&&!r&&String(e)===String(t)}function looseIndexOf(e,t){for(var n=0;n<e.length;n++)if(looseEqual(e[n],t))return n;return-1}function once(e){var t=!1;return function(){t||(t=!0,e())}}function isNative(e){return/native code/.test(e.toString())}function isReserved(e){var t=(e+"").charCodeAt(0);return 36===t||95===t}function def(e,t,n,r){Object.defineProperty(e,t,{value:n,enumerable:!!r,writable:!0,configurable:!0})}function parsePath(e){if(!bailRE.test(e)){var t=e.split(".");return function(e){for(var n=0;n<t.length;n++){if(!e)return;e=e[t[n]]}return e}}}function pushTarget(e){Dep.target&&targetStack.push(Dep.target),Dep.target=e}function popTarget(){Dep.target=targetStack.pop()}function protoAugment(e,t){e.__proto__=t}function copyAugment(e,t,n){for(var r=0,o=n.length;r<o;r++){var i=n[r];def(e,i,t[i])}}function observe(e,t){if(isObject(e)){var n;return hasOwn(e,"__ob__")&&e.__ob__ instanceof Observer?n=e.__ob__:observerState.shouldConvert&&!isServerRendering()&&(Array.isArray(e)||isPlainObject(e))&&Object.isExtensible(e)&&!e._isVue&&(n=new Observer(e)),t&&n&&n.vmCount++,n}}function defineReactive$$1(e,t,n,r){var o=new Dep,i=Object.getOwnPropertyDescriptor(e,t);if(!i||i.configurable!==!1){var a=i&&i.get,s=i&&i.set,c=observe(n);Object.defineProperty(e,t,{enumerable:!0,configurable:!0,get:function(){var t=a?a.call(e):n;return Dep.target&&(o.depend(),c&&c.dep.depend(),Array.isArray(t)&&dependArray(t)),t},set:function(t){var i=a?a.call(e):n;t===i||t!==t&&i!==i||("production"!==process.env.NODE_ENV&&r&&r(),s?s.call(e,t):n=t,c=observe(t),o.notify())}})}}function set(e,t,n){if(Array.isArray(e))return e.length=Math.max(e.length,t),e.splice(t,1,n),n;if(hasOwn(e,t))return void(e[t]=n);var r=e.__ob__;return e._isVue||r&&r.vmCount?void("production"!==process.env.NODE_ENV&&warn("Avoid adding reactive properties to a Vue instance or its root $data at runtime - declare it upfront in the data option.")):r?(defineReactive$$1(r.value,t,n),r.dep.notify(),n):void(e[t]=n)}function del(e,t){if(Array.isArray(e))return void e.splice(t,1);var n=e.__ob__;return e._isVue||n&&n.vmCount?void("production"!==process.env.NODE_ENV&&warn("Avoid deleting properties on a Vue instance or its root $data - just set it to null.")):void(hasOwn(e,t)&&(delete e[t],n&&n.dep.notify()))}function dependArray(e){for(var t=void 0,n=0,r=e.length;n<r;n++)t=e[n],t&&t.__ob__&&t.__ob__.dep.depend(),Array.isArray(t)&&dependArray(t)}function mergeData(e,t){if(!t)return e;for(var n,r,o,i=Object.keys(t),a=0;a<i.length;a++)n=i[a],r=e[n],o=t[n],hasOwn(e,n)?isPlainObject(r)&&isPlainObject(o)&&mergeData(r,o):set(e,n,o);return e}function mergeHook(e,t){return t?e?e.concat(t):Array.isArray(t)?t:[t]:e}function mergeAssets(e,t){var n=Object.create(e||null);return t?extend(n,t):n}function checkComponents(e){for(var t in e.components){var n=t.toLowerCase();(isBuiltInTag(n)||config.isReservedTag(n))&&warn("Do not use built-in or reserved HTML elements as component id: "+t)}}function normalizeProps(e){var t=e.props;if(t){var n,r,o,i={};if(Array.isArray(t))for(n=t.length;n--;)r=t[n],"string"==typeof r?(o=camelize(r),i[o]={type:null}):"production"!==process.env.NODE_ENV&&warn("props must be strings when using array syntax.");else if(isPlainObject(t))for(var a in t)r=t[a],o=camelize(a),i[o]=isPlainObject(r)?r:{type:r};e.props=i}}function normalizeDirectives(e){var t=e.directives;if(t)for(var n in t){var r=t[n];"function"==typeof r&&(t[n]={bind:r,update:r})}}function mergeOptions(e,t,n){function r(r){var o=strats[r]||defaultStrat;l[r]=o(e[r],t[r],n,r)}"production"!==process.env.NODE_ENV&&checkComponents(t),normalizeProps(t),normalizeDirectives(t);var o=t.extends;if(o&&(e="function"==typeof o?mergeOptions(e,o.options,n):mergeOptions(e,o,n)),t.mixins)for(var i=0,a=t.mixins.length;i<a;i++){var s=t.mixins[i];s.prototype instanceof Vue$3&&(s=s.options),e=mergeOptions(e,s,n)}var c,l={};for(c in e)r(c);for(c in t)hasOwn(e,c)||r(c);return l}function resolveAsset(e,t,n,r){if("string"==typeof n){var o=e[t];if(hasOwn(o,n))return o[n];var i=camelize(n);if(hasOwn(o,i))return o[i];var a=capitalize(i);if(hasOwn(o,a))return o[a];var s=o[n]||o[i]||o[a];return"production"!==process.env.NODE_ENV&&r&&!s&&warn("Failed to resolve "+t.slice(0,-1)+": "+n,e),s}}function validateProp(e,t,n,r){var o=t[e],i=!hasOwn(n,e),a=n[e];if(isType(Boolean,o.type)&&(i&&!hasOwn(o,"default")?a=!1:isType(String,o.type)||""!==a&&a!==hyphenate(e)||(a=!0)),void 0===a){a=getPropDefaultValue(r,o,e);var s=observerState.shouldConvert;observerState.shouldConvert=!0,observe(a),observerState.shouldConvert=s}return"production"!==process.env.NODE_ENV&&assertProp(o,e,a,r,i),a}function getPropDefaultValue(e,t,n){if(hasOwn(t,"default")){var r=t.default;return"production"!==process.env.NODE_ENV&&isObject(r)&&warn('Invalid default value for prop "'+n+'": Props with type Object/Array must use a factory function to return the default value.',e),e&&e.$options.propsData&&void 0===e.$options.propsData[n]&&void 0!==e._props[n]?e._props[n]:"function"==typeof r&&"Function"!==getType(t.type)?r.call(e):r}}function assertProp(e,t,n,r,o){if(e.required&&o)return void warn('Missing required prop: "'+t+'"',r);if(null!=n||e.required){var i=e.type,a=!i||i===!0,s=[];if(i){Array.isArray(i)||(i=[i]);for(var c=0;c<i.length&&!a;c++){var l=assertType(n,i[c]);s.push(l.expectedType||""),a=l.valid}}if(!a)return void warn('Invalid prop: type check failed for prop "'+t+'". Expected '+s.map(capitalize).join(", ")+", got "+Object.prototype.toString.call(n).slice(8,-1)+".",r);var d=e.validator;d&&(d(n)||warn('Invalid prop: custom validator check failed for prop "'+t+'".',r))}}function assertType(e,t){var n,r=getType(t);return n="String"===r?typeof e==(r="string"):"Number"===r?typeof e==(r="number"):"Boolean"===r?typeof e==(r="boolean"):"Function"===r?typeof e==(r="function"):"Object"===r?isPlainObject(e):"Array"===r?Array.isArray(e):e instanceof t,{valid:n,expectedType:r}}function getType(e){var t=e&&e.toString().match(/^\s*function (\w+)/);return t&&t[1]}function isType(e,t){if(!Array.isArray(t))return getType(t)===getType(e);for(var n=0,r=t.length;n<r;n++)if(getType(t[n])===getType(e))return!0;return!1}function handleError(e,t,n){if(config.errorHandler)config.errorHandler.call(null,e,t,n);else{if("production"!==process.env.NODE_ENV&&warn("Error in "+n+":",t),!inBrowser||"undefined"==typeof console)throw e;console.error(e)}}function createTextVNode(e){return new VNode(void 0,void 0,void 0,String(e))}function cloneVNode(e){var t=new VNode(e.tag,e.data,e.children,e.text,e.elm,e.context,e.componentOptions);return t.ns=e.ns,t.isStatic=e.isStatic,t.key=e.key,t.isCloned=!0,t}function cloneVNodes(e){for(var t=new Array(e.length),n=0;n<e.length;n++)t[n]=cloneVNode(e[n]);return t}function createFnInvoker(e){function t(){var e=arguments,n=t.fns;if(!Array.isArray(n))return n.apply(null,arguments);for(var r=0;r<n.length;r++)n[r].apply(null,e)}return t.fns=e,t}function updateListeners(e,t,n,r,o){var i,a,s,c;for(i in e)a=e[i],s=t[i],c=normalizeEvent(i),a?s?a!==s&&(s.fns=a,e[i]=s):(a.fns||(a=e[i]=createFnInvoker(a)),n(c.name,a,c.once,c.capture)):"production"!==process.env.NODE_ENV&&warn('Invalid handler for event "'+c.name+'": got '+String(a),o);for(i in t)e[i]||(c=normalizeEvent(i),r(c.name,t[i],c.capture))}function mergeVNodeHook(e,t,n){function r(){n.apply(this,arguments),remove(o.fns,r)}var o,i=e[t];i?i.fns&&i.merged?(o=i,o.fns.push(r)):o=createFnInvoker([i,r]):o=createFnInvoker([r]),o.merged=!0,e[t]=o}function simpleNormalizeChildren(e){for(var t=0;t<e.length;t++)if(Array.isArray(e[t]))return Array.prototype.concat.apply([],e);return e}function normalizeChildren(e){return isPrimitive(e)?[createTextVNode(e)]:Array.isArray(e)?normalizeArrayChildren(e):void 0}function normalizeArrayChildren(e,t){var n,r,o,i=[];for(n=0;n<e.length;n++)r=e[n],null!=r&&"boolean"!=typeof r&&(o=i[i.length-1],Array.isArray(r)?i.push.apply(i,normalizeArrayChildren(r,(t||"")+"_"+n)):isPrimitive(r)?o&&o.text?o.text+=String(r):""!==r&&i.push(createTextVNode(r)):r.text&&o&&o.text?i[i.length-1]=createTextVNode(o.text+r.text):(r.tag&&null==r.key&&null!=t&&(r.key="__vlist"+t+"_"+n+"__"),i.push(r)));return i}function getFirstComponentChild(e){return e&&e.filter(function(e){return e&&e.componentOptions})[0]}function initEvents(e){e._events=Object.create(null),e._hasHookEvent=!1;var t=e.$options._parentListeners;t&&updateComponentListeners(e,t)}function add(e,t,n){n?target.$once(e,t):target.$on(e,t)}function remove$1(e,t){target.$off(e,t)}function updateComponentListeners(e,t,n){target=e,updateListeners(t,n||{},add,remove$1,e)}function eventsMixin(e){var t=/^hook:/;e.prototype.$on=function(e,n){var r=this,o=this;if(Array.isArray(e))for(var i=0,a=e.length;i<a;i++)r.$on(e[i],n);else(o._events[e]||(o._events[e]=[])).push(n),t.test(e)&&(o._hasHookEvent=!0);return o},e.prototype.$once=function(e,t){function n(){r.$off(e,n),t.apply(r,arguments)}var r=this;return n.fn=t,r.$on(e,n),r},e.prototype.$off=function(e,t){var n=this;if(!arguments.length)return n._events=Object.create(null),n;var r=n._events[e];if(!r)return n;if(1===arguments.length)return n._events[e]=null,n;for(var o,i=r.length;i--;)if(o=r[i],o===t||o.fn===t){r.splice(i,1);break}return n},e.prototype.$emit=function(e){var t=this,n=t._events[e];if(n){n=n.length>1?toArray(n):n;for(var r=toArray(arguments,1),o=0,i=n.length;o<i;o++)n[o].apply(t,r)}return t}}function resolveSlots(e,t){var n={};if(!e)return n;for(var r,o,i=[],a=0,s=e.length;a<s;a++)if(o=e[a],(o.context===t||o.functionalContext===t)&&o.data&&(r=o.data.slot)){var c=n[r]||(n[r]=[]);"template"===o.tag?c.push.apply(c,o.children):c.push(o)}else i.push(o);return i.length&&(1!==i.length||" "!==i[0].text&&!i[0].isComment)&&(n.default=i),n}function resolveScopedSlots(e){for(var t={},n=0;n<e.length;n++)t[e[n][0]]=e[n][1];return t}function initLifecycle(e){var t=e.$options,n=t.parent;if(n&&!t.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(e)}e.$parent=n,e.$root=n?n.$root:e,e.$children=[],e.$refs={},e._watcher=null,e._inactive=null,e._directInactive=!1,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1}function lifecycleMixin(e){e.prototype._update=function(e,t){var n=this;n._isMounted&&callHook(n,"beforeUpdate");var r=n.$el,o=n._vnode,i=activeInstance;activeInstance=n,n._vnode=e,o?n.$el=n.__patch__(o,e):n.$el=n.__patch__(n.$el,e,t,!1,n.$options._parentElm,n.$options._refElm),activeInstance=i,r&&(r.__vue__=null),n.$el&&(n.$el.__vue__=n),n.$vnode&&n.$parent&&n.$vnode===n.$parent._vnode&&(n.$parent.$el=n.$el)},e.prototype.$forceUpdate=function(){var e=this;e._watcher&&e._watcher.update()},e.prototype.$destroy=function(){var e=this;if(!e._isBeingDestroyed){callHook(e,"beforeDestroy"),e._isBeingDestroyed=!0;var t=e.$parent;!t||t._isBeingDestroyed||e.$options.abstract||remove(t.$children,e),e._watcher&&e._watcher.teardown();for(var n=e._watchers.length;n--;)e._watchers[n].teardown();e._data.__ob__&&e._data.__ob__.vmCount--,e._isDestroyed=!0,callHook(e,"destroyed"),e.$off(),e.$el&&(e.$el.__vue__=null),e.__patch__(e._vnode,null)}}}function mountComponent(e,t,n){e.$el=t,e.$options.render||(e.$options.render=createEmptyVNode,"production"!==process.env.NODE_ENV&&(e.$options.template&&"#"!==e.$options.template.charAt(0)?warn("You are using the runtime-only build of Vue where the template option is not available. Either pre-compile the templates into render functions, or use the compiler-included build.",e):warn("Failed to mount component: template or render function not defined.",e))),callHook(e,"beforeMount");var r;return r="production"!==process.env.NODE_ENV&&config.performance&&perf?function(){var t=e._name,r="start "+t,o="end "+t;perf.mark(r);var i=e._render();perf.mark(o),perf.measure(t+" render",r,o),perf.mark(r),e._update(i,n),perf.mark(o),perf.measure(t+" patch",r,o)}:function(){e._update(e._render(),n)},e._watcher=new Watcher(e,r,noop),n=!1,null==e.$vnode&&(e._isMounted=!0,callHook(e,"mounted")),e}function updateChildComponent(e,t,n,r,o){var i=!!(o||e.$options._renderChildren||r.data.scopedSlots||e.$scopedSlots!==emptyObject);if(e.$options._parentVnode=r,e.$vnode=r,e._vnode&&(e._vnode.parent=r),e.$options._renderChildren=o,t&&e.$options.props){observerState.shouldConvert=!1,"production"!==process.env.NODE_ENV&&(observerState.isSettingProps=!0);for(var a=e._props,s=e.$options._propKeys||[],c=0;c<s.length;c++){var l=s[c];a[l]=validateProp(l,e.$options.props,t,e)}observerState.shouldConvert=!0,"production"!==process.env.NODE_ENV&&(observerState.isSettingProps=!1),e.$options.propsData=t}if(n){var d=e.$options._parentListeners;e.$options._parentListeners=n,updateComponentListeners(e,n,d)}i&&(e.$slots=resolveSlots(o,r.context),e.$forceUpdate())}function isInInactiveTree(e){for(;e&&(e=e.$parent);)if(e._inactive)return!0;return!1}function activateChildComponent(e,t){if(t){if(e._directInactive=!1,isInInactiveTree(e))return}else if(e._directInactive)return;if(e._inactive||null==e._inactive){e._inactive=!1;for(var n=0;n<e.$children.length;n++)activateChildComponent(e.$children[n]);callHook(e,"activated")}}function deactivateChildComponent(e,t){if(!(t&&(e._directInactive=!0,isInInactiveTree(e))||e._inactive)){e._inactive=!0;for(var n=0;n<e.$children.length;n++)deactivateChildComponent(e.$children[n]);callHook(e,"deactivated")}}function callHook(e,t){var n=e.$options[t];if(n)for(var r=0,o=n.length;r<o;r++)try{n[r].call(e)}catch(n){handleError(n,e,t+" hook")}e._hasHookEvent&&e.$emit("hook:"+t)}function resetSchedulerState(){queue.length=0,has={},"production"!==process.env.NODE_ENV&&(circular={}),waiting=flushing=!1}function flushSchedulerQueue(){flushing=!0;var e,t,n;for(queue.sort(function(e,t){return e.id-t.id}),index=0;index<queue.length;index++)if(e=queue[index],t=e.id,has[t]=null,e.run(),"production"!==process.env.NODE_ENV&&null!=has[t]&&(circular[t]=(circular[t]||0)+1,circular[t]>config._maxUpdateCount)){warn("You may have an infinite update loop "+(e.user?'in watcher with expression "'+e.expression+'"':"in a component render function."),e.vm);break}for(index=queue.length;index--;)e=queue[index],n=e.vm,n._watcher===e&&n._isMounted&&callHook(n,"updated");devtools&&config.devtools&&devtools.emit("flush"),resetSchedulerState()}function queueWatcher(e){var t=e.id;if(null==has[t]){if(has[t]=!0,flushing){for(var n=queue.length-1;n>=0&&queue[n].id>e.id;)n--;queue.splice(Math.max(n,index)+1,0,e)}else queue.push(e);waiting||(waiting=!0,nextTick(flushSchedulerQueue))}}function traverse(e){seenObjects.clear(),_traverse(e,seenObjects)}function _traverse(e,t){var n,r,o=Array.isArray(e);if((o||isObject(e))&&Object.isExtensible(e)){if(e.__ob__){var i=e.__ob__.dep.id;if(t.has(i))return;t.add(i)}if(o)for(n=e.length;n--;)_traverse(e[n],t);else for(r=Object.keys(e),n=r.length;n--;)_traverse(e[r[n]],t)}}function proxy(e,t,n){sharedPropertyDefinition.get=function(){return this[t][n]},sharedPropertyDefinition.set=function(e){this[t][n]=e},Object.defineProperty(e,n,sharedPropertyDefinition)}function initState(e){e._watchers=[];var t=e.$options;t.props&&initProps(e,t.props),t.methods&&initMethods(e,t.methods),t.data?initData(e):observe(e._data={},!0),t.computed&&initComputed(e,t.computed),t.watch&&initWatch(e,t.watch)}function initProps(e,t){var n=e.$options.propsData||{},r=e._props={},o=e.$options._propKeys=[],i=!e.$parent;observerState.shouldConvert=i;var a=function(i){o.push(i);var a=validateProp(i,t,n,e);"production"!==process.env.NODE_ENV?(isReservedProp[i]&&warn('"'+i+'" is a reserved attribute and cannot be used as component prop.',e),defineReactive$$1(r,i,a,function(){e.$parent&&!observerState.isSettingProps&&warn("Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: \""+i+'"',e)})):defineReactive$$1(r,i,a),i in e||proxy(e,"_props",i)};for(var s in t)a(s);observerState.shouldConvert=!0}function initData(e){var t=e.$options.data;t=e._data="function"==typeof t?t.call(e):t||{},isPlainObject(t)||(t={},"production"!==process.env.NODE_ENV&&warn("data functions should return an object:\nhttps://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function",e));for(var n=Object.keys(t),r=e.$options.props,o=n.length;o--;)r&&hasOwn(r,n[o])?"production"!==process.env.NODE_ENV&&warn('The data property "'+n[o]+'" is already declared as a prop. Use prop default value instead.',e):isReserved(n[o])||proxy(e,"_data",n[o]);observe(t,!0)}function initComputed(e,t){var n=e._computedWatchers=Object.create(null);for(var r in t){var o=t[r],i="function"==typeof o?o:o.get;n[r]=new Watcher(e,i,noop,computedWatcherOptions),r in e||defineComputed(e,r,o)}}function defineComputed(e,t,n){"function"==typeof n?(sharedPropertyDefinition.get=createComputedGetter(t),sharedPropertyDefinition.set=noop):(sharedPropertyDefinition.get=n.get?n.cache!==!1?createComputedGetter(t):n.get:noop,sharedPropertyDefinition.set=n.set?n.set:noop),Object.defineProperty(e,t,sharedPropertyDefinition)}function createComputedGetter(e){return function(){var t=this._computedWatchers&&this._computedWatchers[e];if(t)return t.dirty&&t.evaluate(),Dep.target&&t.depend(),t.value}}function initMethods(e,t){var n=e.$options.props;for(var r in t)e[r]=null==t[r]?noop:bind(t[r],e),"production"!==process.env.NODE_ENV&&(null==t[r]&&warn('method "'+r+'" has an undefined value in the component definition. Did you reference the function correctly?',e),n&&hasOwn(n,r)&&warn('method "'+r+'" has already been defined as a prop.',e))}function initWatch(e,t){for(var n in t){var r=t[n];if(Array.isArray(r))for(var o=0;o<r.length;o++)createWatcher(e,n,r[o]);else createWatcher(e,n,r)}}function createWatcher(e,t,n){var r;isPlainObject(n)&&(r=n,n=n.handler),"string"==typeof n&&(n=e[n]),e.$watch(t,n,r)}function stateMixin(e){var t={};t.get=function(){return this._data};var n={};n.get=function(){return this._props},"production"!==process.env.NODE_ENV&&(t.set=function(e){warn("Avoid replacing instance root $data. Use nested data properties instead.",this)},n.set=function(){warn("$props is readonly.",this)}),Object.defineProperty(e.prototype,"$data",t),Object.defineProperty(e.prototype,"$props",n),e.prototype.$set=set,e.prototype.$delete=del,e.prototype.$watch=function(e,t,n){var r=this;n=n||{},n.user=!0;var o=new Watcher(r,e,t,n);return n.immediate&&t.call(r,o.value),function(){o.teardown()}}}function createComponent(e,t,n,r,o){if(e){var i=n.$options._base;if(isObject(e)&&(e=i.extend(e)),"function"!=typeof e)return void("production"!==process.env.NODE_ENV&&warn("Invalid Component definition: "+String(e),n));if(!e.cid)if(e.resolved)e=e.resolved;else if(e=resolveAsyncComponent(e,i,function(){n.$forceUpdate()}),!e)return;resolveConstructorOptions(e),t=t||{},t.model&&transformModel(e.options,t);var a=extractProps(t,e);if(e.options.functional)return createFunctionalComponent(e,a,t,n,r);var s=t.on;t.on=t.nativeOn,e.options.abstract&&(t={}),mergeHooks(t);var c=e.options.name||o,l=new VNode("vue-component-"+e.cid+(c?"-"+c:""),t,void 0,void 0,void 0,n,{Ctor:e,propsData:a,listeners:s,tag:o,children:r});return l}}function createFunctionalComponent(e,t,n,r,o){var i={},a=e.options.props;if(a)for(var s in a)i[s]=validateProp(s,a,t);var c=Object.create(r),l=function(e,t,n,r){return createElement(c,e,t,n,r,!0)},d=e.options.render.call(null,l,{props:i,data:n,parent:r,children:o,slots:function(){return resolveSlots(o,r)}});return d instanceof VNode&&(d.functionalContext=r,n.slot&&((d.data||(d.data={})).slot=n.slot)),d}function createComponentInstanceForVnode(e,t,n,r){var o=e.componentOptions,i={_isComponent:!0,parent:t,propsData:o.propsData,_componentTag:o.tag,_parentVnode:e,_parentListeners:o.listeners,_renderChildren:o.children,_parentElm:n||null,_refElm:r||null},a=e.data.inlineTemplate;return a&&(i.render=a.render,i.staticRenderFns=a.staticRenderFns),new o.Ctor(i)}function init(e,t,n,r){if(!e.componentInstance||e.componentInstance._isDestroyed){var o=e.componentInstance=createComponentInstanceForVnode(e,activeInstance,n,r);o.$mount(t?e.elm:void 0,t)}else if(e.data.keepAlive){var i=e;prepatch(i,i)}}function prepatch(e,t){var n=t.componentOptions,r=t.componentInstance=e.componentInstance;updateChildComponent(r,n.propsData,n.listeners,t,n.children)}function insert(e){e.componentInstance._isMounted||(e.componentInstance._isMounted=!0,callHook(e.componentInstance,"mounted")),e.data.keepAlive&&activateChildComponent(e.componentInstance,!0)}function destroy(e){e.componentInstance._isDestroyed||(e.data.keepAlive?deactivateChildComponent(e.componentInstance,!0):e.componentInstance.$destroy())}function resolveAsyncComponent(e,t,n){if(!e.requested){e.requested=!0;var r=e.pendingCallbacks=[n],o=!0,i=function(n){if(isObject(n)&&(n=t.extend(n)),e.resolved=n,!o)for(var i=0,a=r.length;i<a;i++)r[i](n)},a=function(t){"production"!==process.env.NODE_ENV&&warn("Failed to resolve async component: "+String(e)+(t?"\nReason: "+t:""))},s=e(i,a);return s&&"function"==typeof s.then&&!e.resolved&&s.then(i,a),o=!1,e.resolved}e.pendingCallbacks.push(n)}function extractProps(e,t){var n=t.options.props;if(n){var r={},o=e.attrs,i=e.props,a=e.domProps;if(o||i||a)for(var s in n){var c=hyphenate(s);checkProp(r,i,s,c,!0)||checkProp(r,o,s,c)||checkProp(r,a,s,c)}return r}}function checkProp(e,t,n,r,o){if(t){if(hasOwn(t,n))return e[n]=t[n],o||delete t[n],!0;if(hasOwn(t,r))return e[n]=t[r],o||delete t[r],!0}return!1}function mergeHooks(e){e.hook||(e.hook={});for(var t=0;t<hooksToMerge.length;t++){var n=hooksToMerge[t],r=e.hook[n],o=hooks[n];e.hook[n]=r?mergeHook$1(o,r):o}}function mergeHook$1(e,t){return function(n,r,o,i){e(n,r,o,i),t(n,r,o,i)}}function transformModel(e,t){var n=e.model&&e.model.prop||"value",r=e.model&&e.model.event||"input";(t.props||(t.props={}))[n]=t.model.value;var o=t.on||(t.on={});o[r]?o[r]=[t.model.callback].concat(o[r]):o[r]=t.model.callback}function createElement(e,t,n,r,o,i){return(Array.isArray(n)||isPrimitive(n))&&(o=r,r=n,n=void 0),i&&(o=ALWAYS_NORMALIZE),_createElement(e,t,n,r,o)}function _createElement(e,t,n,r,o){if(n&&n.__ob__)return"production"!==process.env.NODE_ENV&&warn("Avoid using observed data object as vnode data: "+JSON.stringify(n)+"\nAlways create fresh vnode data objects in each render!",e),createEmptyVNode();if(!t)return createEmptyVNode();Array.isArray(r)&&"function"==typeof r[0]&&(n=n||{},n.scopedSlots={default:r[0]},r.length=0),o===ALWAYS_NORMALIZE?r=normalizeChildren(r):o===SIMPLE_NORMALIZE&&(r=simpleNormalizeChildren(r));var i,a;if("string"==typeof t){var s;a=config.getTagNamespace(t),i=config.isReservedTag(t)?new VNode(config.parsePlatformTagName(t),n,r,void 0,void 0,e):(s=resolveAsset(e.$options,"components",t))?createComponent(s,n,e,r,t):new VNode(t,n,r,void 0,void 0,e)}else i=createComponent(t,n,e,r);return i?(a&&applyNS(i,a),i):createEmptyVNode()}function applyNS(e,t){if(e.ns=t,"foreignObject"!==e.tag&&e.children)for(var n=0,r=e.children.length;n<r;n++){var o=e.children[n];o.tag&&!o.ns&&applyNS(o,t)}}function renderList(e,t){var n,r,o,i,a;if(Array.isArray(e)||"string"==typeof e)for(n=new Array(e.length),r=0,o=e.length;r<o;r++)n[r]=t(e[r],r);else if("number"==typeof e)for(n=new Array(e),r=0;r<e;r++)n[r]=t(r+1,r);else if(isObject(e))for(i=Object.keys(e),n=new Array(i.length),r=0,o=i.length;r<o;r++)a=i[r],n[r]=t(e[a],a,r);return n}function renderSlot(e,t,n,r){var o=this.$scopedSlots[e];if(o)return n=n||{},r&&extend(n,r),o(n)||t;var i=this.$slots[e];return i&&"production"!==process.env.NODE_ENV&&(i._rendered&&warn('Duplicate presence of slot "'+e+'" found in the same render tree - this will likely cause render errors.',this),i._rendered=!0),i||t}function resolveFilter(e){return resolveAsset(this.$options,"filters",e,!0)||identity}function checkKeyCodes(e,t,n){var r=config.keyCodes[t]||n;return Array.isArray(r)?r.indexOf(e)===-1:r!==e}function bindObjectProps(e,t,n,r){if(n)if(isObject(n)){Array.isArray(n)&&(n=toObject(n));for(var o in n)if("class"===o||"style"===o)e[o]=n[o];else{var i=e.attrs&&e.attrs.type,a=r||config.mustUseProp(t,i,o)?e.domProps||(e.domProps={}):e.attrs||(e.attrs={});a[o]=n[o]}}else"production"!==process.env.NODE_ENV&&warn("v-bind without argument expects an Object or Array value",this);return e}function renderStatic(e,t){var n=this._staticTrees[e];return n&&!t?Array.isArray(n)?cloneVNodes(n):cloneVNode(n):(n=this._staticTrees[e]=this.$options.staticRenderFns[e].call(this._renderProxy),markStatic(n,"__static__"+e,!1),n)}function markOnce(e,t,n){return markStatic(e,"__once__"+t+(n?"_"+n:""),!0),e}function markStatic(e,t,n){if(Array.isArray(e))for(var r=0;r<e.length;r++)e[r]&&"string"!=typeof e[r]&&markStaticNode(e[r],t+"_"+r,n);else markStaticNode(e,t,n)}function markStaticNode(e,t,n){e.isStatic=!0,e.key=t,e.isOnce=n}function initRender(e){e.$vnode=null,e._vnode=null,e._staticTrees=null;var t=e.$options._parentVnode,n=t&&t.context;e.$slots=resolveSlots(e.$options._renderChildren,n),e.$scopedSlots=emptyObject,e._c=function(t,n,r,o){return createElement(e,t,n,r,o,!1)},e.$createElement=function(t,n,r,o){return createElement(e,t,n,r,o,!0)}}function renderMixin(e){e.prototype.$nextTick=function(e){return nextTick(e,this)},e.prototype._render=function(){var e=this,t=e.$options,n=t.render,r=t.staticRenderFns,o=t._parentVnode;if(e._isMounted)for(var i in e.$slots)e.$slots[i]=cloneVNodes(e.$slots[i]);e.$scopedSlots=o&&o.data.scopedSlots||emptyObject,r&&!e._staticTrees&&(e._staticTrees=[]),e.$vnode=o;var a;try{a=n.call(e._renderProxy,e.$createElement)}catch(t){handleError(t,e,"render function"),a="production"!==process.env.NODE_ENV&&e.$options.renderError?e.$options.renderError.call(e._renderProxy,e.$createElement,t):e._vnode}return a instanceof VNode||("production"!==process.env.NODE_ENV&&Array.isArray(a)&&warn("Multiple root nodes returned from render function. Render function should return a single root node.",e),a=createEmptyVNode()),a.parent=o,a},e.prototype._o=markOnce,e.prototype._n=toNumber,e.prototype._s=_toString,e.prototype._l=renderList,e.prototype._t=renderSlot,e.prototype._q=looseEqual,e.prototype._i=looseIndexOf,e.prototype._m=renderStatic,e.prototype._f=resolveFilter,e.prototype._k=checkKeyCodes,e.prototype._b=bindObjectProps,e.prototype._v=createTextVNode,e.prototype._e=createEmptyVNode,e.prototype._u=resolveScopedSlots}function initInjections(e){var t=e.$options.provide,n=e.$options.inject;if(t&&(e._provided="function"==typeof t?t.call(e):t),n)for(var r=Array.isArray(n),o=r?n:Object.keys(n),i=0;i<o.length;i++)for(var a=o[i],s=r?a:n[a],c=e;c;){if(c._provided&&c._provided[s]){e[a]=c._provided[s];break}c=c.$parent}}function initMixin(e){e.prototype._init=function(e){"production"!==process.env.NODE_ENV&&config.performance&&perf&&perf.mark("init");var t=this;t._uid=uid++,t._isVue=!0,e&&e._isComponent?initInternalComponent(t,e):t.$options=mergeOptions(resolveConstructorOptions(t.constructor),e||{},t),"production"!==process.env.NODE_ENV?initProxy(t):t._renderProxy=t,t._self=t,initLifecycle(t),initEvents(t),initRender(t),callHook(t,"beforeCreate"),initState(t),initInjections(t),callHook(t,"created"),"production"!==process.env.NODE_ENV&&config.performance&&perf&&(t._name=formatComponentName(t,!1),perf.mark("init end"),perf.measure(t._name+" init","init","init end")),t.$options.el&&t.$mount(t.$options.el)}}function initInternalComponent(e,t){var n=e.$options=Object.create(e.constructor.options);n.parent=t.parent,n.propsData=t.propsData,n._parentVnode=t._parentVnode,n._parentListeners=t._parentListeners,n._renderChildren=t._renderChildren,n._componentTag=t._componentTag,n._parentElm=t._parentElm,n._refElm=t._refElm,t.render&&(n.render=t.render,n.staticRenderFns=t.staticRenderFns)}function resolveConstructorOptions(e){var t=e.options;if(e.super){var n=resolveConstructorOptions(e.super),r=e.superOptions;if(n!==r){e.superOptions=n;var o=resolveModifiedOptions(e);o&&extend(e.extendOptions,o),t=e.options=mergeOptions(n,e.extendOptions),t.name&&(t.components[t.name]=e)}}return t}function resolveModifiedOptions(e){var t,n=e.options,r=e.sealedOptions;for(var o in n)n[o]!==r[o]&&(t||(t={}),t[o]=dedupe(n[o],r[o]));return t}function dedupe(e,t){if(Array.isArray(e)){var n=[];t=Array.isArray(t)?t:[t];for(var r=0;r<e.length;r++)t.indexOf(e[r])<0&&n.push(e[r]);return n}return e}function Vue$3(e){"production"===process.env.NODE_ENV||this instanceof Vue$3||warn("Vue is a constructor and should be called with the `new` keyword"),this._init(e)}function initUse(e){e.use=function(e){if(!e.installed){var t=toArray(arguments,1);return t.unshift(this),"function"==typeof e.install?e.install.apply(e,t):"function"==typeof e&&e.apply(null,t),e.installed=!0,this}}}function initMixin$1(e){e.mixin=function(e){this.options=mergeOptions(this.options,e)}}function initExtend(e){e.cid=0;var t=1;e.extend=function(e){e=e||{};var n=this,r=n.cid,o=e._Ctor||(e._Ctor={});if(o[r])return o[r];var i=e.name||n.options.name;"production"!==process.env.NODE_ENV&&(/^[a-zA-Z][\w-]*$/.test(i)||warn('Invalid component name: "'+i+'". Component names can only contain alphanumeric characters and the hyphen, and must start with a letter.'));var a=function(e){this._init(e)};return a.prototype=Object.create(n.prototype),a.prototype.constructor=a,a.cid=t++,a.options=mergeOptions(n.options,e),a.super=n,a.options.props&&initProps$1(a),a.options.computed&&initComputed$1(a),a.extend=n.extend,a.mixin=n.mixin,a.use=n.use,config._assetTypes.forEach(function(e){a[e]=n[e]}),i&&(a.options.components[i]=a),a.superOptions=n.options,a.extendOptions=e,a.sealedOptions=extend({},a.options),o[r]=a,a}}function initProps$1(e){var t=e.options.props;for(var n in t)proxy(e.prototype,"_props",n)}function initComputed$1(e){var t=e.options.computed;for(var n in t)defineComputed(e.prototype,n,t[n])}function initAssetRegisters(e){config._assetTypes.forEach(function(t){e[t]=function(e,n){return n?("production"!==process.env.NODE_ENV&&"component"===t&&config.isReservedTag(e)&&warn("Do not use built-in or reserved HTML elements as component id: "+e),"component"===t&&isPlainObject(n)&&(n.name=n.name||e,n=this.options._base.extend(n)),"directive"===t&&"function"==typeof n&&(n={bind:n,update:n}),this.options[t+"s"][e]=n,n):this.options[t+"s"][e]}})}function getComponentName(e){return e&&(e.Ctor.options.name||e.tag)}function matches(e,t){return"string"==typeof e?e.split(",").indexOf(t)>-1:e instanceof RegExp&&e.test(t)}function pruneCache(e,t){for(var n in e){var r=e[n];if(r){var o=getComponentName(r.componentOptions);o&&!t(o)&&(pruneCacheEntry(r),e[n]=null)}}}function pruneCacheEntry(e){e&&(e.componentInstance._inactive||callHook(e.componentInstance,"deactivated"),e.componentInstance.$destroy()); }function initGlobalAPI(e){var t={};t.get=function(){return config},"production"!==process.env.NODE_ENV&&(t.set=function(){warn("Do not replace the Vue.config object, set individual fields instead.")}),Object.defineProperty(e,"config",t),e.util=util,e.set=set,e.delete=del,e.nextTick=nextTick,e.options=Object.create(null),config._assetTypes.forEach(function(t){e.options[t+"s"]=Object.create(null)}),e.options._base=e,extend(e.options.components,builtInComponents),initUse(e),initMixin$1(e),initExtend(e),initAssetRegisters(e)}function genClassForVnode(e){for(var t=e.data,n=e,r=e;r.componentInstance;)r=r.componentInstance._vnode,r.data&&(t=mergeClassData(r.data,t));for(;n=n.parent;)n.data&&(t=mergeClassData(t,n.data));return genClassFromData(t)}function mergeClassData(e,t){return{staticClass:concat(e.staticClass,t.staticClass),class:e.class?[e.class,t.class]:t.class}}function genClassFromData(e){var t=e.class,n=e.staticClass;return n||t?concat(n,stringifyClass(t)):""}function concat(e,t){return e?t?e+" "+t:e:t||""}function stringifyClass(e){var t="";if(!e)return t;if("string"==typeof e)return e;if(Array.isArray(e)){for(var n,r=0,o=e.length;r<o;r++)e[r]&&(n=stringifyClass(e[r]))&&(t+=n+" ");return t.slice(0,-1)}if(isObject(e)){for(var i in e)e[i]&&(t+=i+" ");return t.slice(0,-1)}return t}function getTagNamespace(e){return isSVG(e)?"svg":"math"===e?"math":void 0}function isUnknownElement(e){if(!inBrowser)return!0;if(isReservedTag(e))return!1;if(e=e.toLowerCase(),null!=unknownElementCache[e])return unknownElementCache[e];var t=document.createElement(e);return e.indexOf("-")>-1?unknownElementCache[e]=t.constructor===window.HTMLUnknownElement||t.constructor===window.HTMLElement:unknownElementCache[e]=/HTMLUnknownElement/.test(t.toString())}function query(e){if("string"==typeof e){var t=document.querySelector(e);return t?t:("production"!==process.env.NODE_ENV&&warn("Cannot find element: "+e),document.createElement("div"))}return e}function createElement$1(e,t){var n=document.createElement(e);return"select"!==e?n:(t.data&&t.data.attrs&&void 0!==t.data.attrs.multiple&&n.setAttribute("multiple","multiple"),n)}function createElementNS(e,t){return document.createElementNS(namespaceMap[e],t)}function createTextNode(e){return document.createTextNode(e)}function createComment(e){return document.createComment(e)}function insertBefore(e,t,n){e.insertBefore(t,n)}function removeChild(e,t){e.removeChild(t)}function appendChild(e,t){e.appendChild(t)}function parentNode(e){return e.parentNode}function nextSibling(e){return e.nextSibling}function tagName(e){return e.tagName}function setTextContent(e,t){e.textContent=t}function setAttribute(e,t,n){e.setAttribute(t,n)}function registerRef(e,t){var n=e.data.ref;if(n){var r=e.context,o=e.componentInstance||e.elm,i=r.$refs;t?Array.isArray(i[n])?remove(i[n],o):i[n]===o&&(i[n]=void 0):e.data.refInFor?Array.isArray(i[n])&&i[n].indexOf(o)<0?i[n].push(o):i[n]=[o]:i[n]=o}}function isUndef(e){return null==e}function isDef(e){return null!=e}function sameVnode(e,t){return e.key===t.key&&e.tag===t.tag&&e.isComment===t.isComment&&!e.data==!t.data}function createKeyToOldIdx(e,t,n){var r,o,i={};for(r=t;r<=n;++r)o=e[r].key,isDef(o)&&(i[o]=r);return i}function createPatchFunction(e){function t(e){return new VNode($.tagName(e).toLowerCase(),{},[],void 0,e)}function n(e,t){function n(){0===--n.listeners&&r(e)}return n.listeners=t,n}function r(e){var t=$.parentNode(e);t&&$.removeChild(t,e)}function o(e,t,n,r,o){if(e.isRootInsert=!o,!i(e,t,n,r)){var a=e.data,s=e.children,d=e.tag;isDef(d)?("production"!==process.env.NODE_ENV&&(a&&a.pre&&k++,k||e.ns||config.ignoredElements.length&&config.ignoredElements.indexOf(d)>-1||!config.isUnknownElement(d)||warn("Unknown custom element: <"+d+'> - did you register the component correctly? For recursive components, make sure to provide the "name" option.',e.context)),e.elm=e.ns?$.createElementNS(e.ns,d):$.createElement(d,e),p(e),l(e,s,t),isDef(a)&&u(e,t),c(n,e.elm,r),"production"!==process.env.NODE_ENV&&a&&a.pre&&k--):e.isComment?(e.elm=$.createComment(e.text),c(n,e.elm,r)):(e.elm=$.createTextNode(e.text),c(n,e.elm,r))}}function i(e,t,n,r){var o=e.data;if(isDef(o)){var i=isDef(e.componentInstance)&&o.keepAlive;if(isDef(o=o.hook)&&isDef(o=o.init)&&o(e,!1,n,r),isDef(e.componentInstance))return a(e,t),i&&s(e,t,n,r),!0}}function a(e,t){e.data.pendingInsert&&t.push.apply(t,e.data.pendingInsert),e.elm=e.componentInstance.$el,d(e)?(u(e,t),p(e)):(registerRef(e),t.push(e))}function s(e,t,n,r){for(var o,i=e;i.componentInstance;)if(i=i.componentInstance._vnode,isDef(o=i.data)&&isDef(o=o.transition)){for(o=0;o<O.activate.length;++o)O.activate[o](emptyNode,i);t.push(i);break}c(n,e.elm,r)}function c(e,t,n){e&&(n?$.insertBefore(e,t,n):$.appendChild(e,t))}function l(e,t,n){if(Array.isArray(t))for(var r=0;r<t.length;++r)o(t[r],n,e.elm,null,!0);else isPrimitive(e.text)&&$.appendChild(e.elm,$.createTextNode(e.text))}function d(e){for(;e.componentInstance;)e=e.componentInstance._vnode;return isDef(e.tag)}function u(e,t){for(var n=0;n<O.create.length;++n)O.create[n](emptyNode,e);N=e.data.hook,isDef(N)&&(N.create&&N.create(emptyNode,e),N.insert&&t.push(e))}function p(e){for(var t,n=e;n;)isDef(t=n.context)&&isDef(t=t.$options._scopeId)&&$.setAttribute(e.elm,t,""),n=n.parent;isDef(t=activeInstance)&&t!==e.context&&isDef(t=t.$options._scopeId)&&$.setAttribute(e.elm,t,"")}function f(e,t,n,r,i,a){for(;r<=i;++r)o(n[r],a,e,t)}function v(e){var t,n,r=e.data;if(isDef(r))for(isDef(t=r.hook)&&isDef(t=t.destroy)&&t(e),t=0;t<O.destroy.length;++t)O.destroy[t](e);if(isDef(t=e.children))for(n=0;n<e.children.length;++n)v(e.children[n])}function m(e,t,n,o){for(;n<=o;++n){var i=t[n];isDef(i)&&(isDef(i.tag)?(h(i),v(i)):r(i.elm))}}function h(e,t){if(t||isDef(e.data)){var o=O.remove.length+1;for(t?t.listeners+=o:t=n(e.elm,o),isDef(N=e.componentInstance)&&isDef(N=N._vnode)&&isDef(N.data)&&h(N,t),N=0;N<O.remove.length;++N)O.remove[N](e,t);isDef(N=e.data.hook)&&isDef(N=N.remove)?N(e,t):t()}else r(e.elm)}function g(e,t,n,r,i){for(var a,s,c,l,d=0,u=0,p=t.length-1,v=t[0],h=t[p],g=n.length-1,_=n[0],b=n[g],E=!i;d<=p&&u<=g;)isUndef(v)?v=t[++d]:isUndef(h)?h=t[--p]:sameVnode(v,_)?(y(v,_,r),v=t[++d],_=n[++u]):sameVnode(h,b)?(y(h,b,r),h=t[--p],b=n[--g]):sameVnode(v,b)?(y(v,b,r),E&&$.insertBefore(e,v.elm,$.nextSibling(h.elm)),v=t[++d],b=n[--g]):sameVnode(h,_)?(y(h,_,r),E&&$.insertBefore(e,h.elm,v.elm),h=t[--p],_=n[++u]):(isUndef(a)&&(a=createKeyToOldIdx(t,d,p)),s=isDef(_.key)?a[_.key]:null,isUndef(s)?(o(_,r,e,v.elm),_=n[++u]):(c=t[s],"production"===process.env.NODE_ENV||c||warn("It seems there are duplicate keys that is causing an update error. Make sure each v-for item has a unique key."),sameVnode(c,_)?(y(c,_,r),t[s]=void 0,E&&$.insertBefore(e,_.elm,v.elm),_=n[++u]):(o(_,r,e,v.elm),_=n[++u])));d>p?(l=isUndef(n[g+1])?null:n[g+1].elm,f(e,l,n,u,g,r)):u>g&&m(e,t,d,p)}function y(e,t,n,r){if(e!==t){if(t.isStatic&&e.isStatic&&t.key===e.key&&(t.isCloned||t.isOnce))return t.elm=e.elm,void(t.componentInstance=e.componentInstance);var o,i=t.data,a=isDef(i);a&&isDef(o=i.hook)&&isDef(o=o.prepatch)&&o(e,t);var s=t.elm=e.elm,c=e.children,l=t.children;if(a&&d(t)){for(o=0;o<O.update.length;++o)O.update[o](e,t);isDef(o=i.hook)&&isDef(o=o.update)&&o(e,t)}isUndef(t.text)?isDef(c)&&isDef(l)?c!==l&&g(s,c,l,n,r):isDef(l)?(isDef(e.text)&&$.setTextContent(s,""),f(s,null,l,0,l.length-1,n)):isDef(c)?m(s,c,0,c.length-1):isDef(e.text)&&$.setTextContent(s,""):e.text!==t.text&&$.setTextContent(s,t.text),a&&isDef(o=i.hook)&&isDef(o=o.postpatch)&&o(e,t)}}function _(e,t,n){if(n&&e.parent)e.parent.data.pendingInsert=t;else for(var r=0;r<t.length;++r)t[r].data.hook.insert(t[r])}function b(e,t,n){if("production"!==process.env.NODE_ENV&&!E(e,t))return!1;t.elm=e;var r=t.tag,o=t.data,i=t.children;if(isDef(o)&&(isDef(N=o.hook)&&isDef(N=N.init)&&N(t,!0),isDef(N=t.componentInstance)))return a(t,n),!0;if(isDef(r)){if(isDef(i))if(e.hasChildNodes()){for(var s=!0,c=e.firstChild,d=0;d<i.length;d++){if(!c||!b(c,i[d],n)){s=!1;break}c=c.nextSibling}if(!s||c)return"production"===process.env.NODE_ENV||"undefined"==typeof console||x||(x=!0,console.warn("Parent: ",e),console.warn("Mismatching childNodes vs. VNodes: ",e.childNodes,i)),!1}else l(t,i,n);if(isDef(o))for(var p in o)if(!A(p)){u(t,n);break}}else e.data!==t.text&&(e.data=t.text);return!0}function E(e,t){return t.tag?0===t.tag.indexOf("vue-component")||t.tag.toLowerCase()===(e.tagName&&e.tagName.toLowerCase()):e.nodeType===(t.isComment?8:3)}var N,C,O={},w=e.modules,$=e.nodeOps;for(N=0;N<hooks$1.length;++N)for(O[hooks$1[N]]=[],C=0;C<w.length;++C)void 0!==w[C][hooks$1[N]]&&O[hooks$1[N]].push(w[C][hooks$1[N]]);var k=0,x=!1,A=makeMap("attrs,style,class,staticClass,staticStyle,key");return function(e,n,r,i,a,s){if(!n)return void(e&&v(e));var c=!1,l=[];if(e){var u=isDef(e.nodeType);if(!u&&sameVnode(e,n))y(e,n,l,i);else{if(u){if(1===e.nodeType&&e.hasAttribute("server-rendered")&&(e.removeAttribute("server-rendered"),r=!0),r){if(b(e,n,l))return _(n,l,!0),e;"production"!==process.env.NODE_ENV&&warn("The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.")}e=t(e)}var p=e.elm,f=$.parentNode(p);if(o(n,l,p._leaveCb?null:f,$.nextSibling(p)),n.parent){for(var h=n.parent;h;)h.elm=n.elm,h=h.parent;if(d(n))for(var g=0;g<O.create.length;++g)O.create[g](emptyNode,n.parent)}null!==f?m(f,[e],0,0):isDef(e.tag)&&v(e)}}else c=!0,o(n,l,a,s);return _(n,l,c),n.elm}}function updateDirectives(e,t){(e.data.directives||t.data.directives)&&_update(e,t)}function _update(e,t){var n,r,o,i=e===emptyNode,a=t===emptyNode,s=normalizeDirectives$1(e.data.directives,e.context),c=normalizeDirectives$1(t.data.directives,t.context),l=[],d=[];for(n in c)r=s[n],o=c[n],r?(o.oldValue=r.value,callHook$1(o,"update",t,e),o.def&&o.def.componentUpdated&&d.push(o)):(callHook$1(o,"bind",t,e),o.def&&o.def.inserted&&l.push(o));if(l.length){var u=function(){for(var n=0;n<l.length;n++)callHook$1(l[n],"inserted",t,e)};i?mergeVNodeHook(t.data.hook||(t.data.hook={}),"insert",u):u()}if(d.length&&mergeVNodeHook(t.data.hook||(t.data.hook={}),"postpatch",function(){for(var n=0;n<d.length;n++)callHook$1(d[n],"componentUpdated",t,e)}),!i)for(n in s)c[n]||callHook$1(s[n],"unbind",e,e,a)}function normalizeDirectives$1(e,t){var n=Object.create(null);if(!e)return n;var r,o;for(r=0;r<e.length;r++)o=e[r],o.modifiers||(o.modifiers=emptyModifiers),n[getRawDirName(o)]=o,o.def=resolveAsset(t.$options,"directives",o.name,!0);return n}function getRawDirName(e){return e.rawName||e.name+"."+Object.keys(e.modifiers||{}).join(".")}function callHook$1(e,t,n,r,o){var i=e.def&&e.def[t];i&&i(n.elm,e,n,r,o)}function updateAttrs(e,t){if(e.data.attrs||t.data.attrs){var n,r,o,i=t.elm,a=e.data.attrs||{},s=t.data.attrs||{};s.__ob__&&(s=t.data.attrs=extend({},s));for(n in s)r=s[n],o=a[n],o!==r&&setAttr(i,n,r);isIE9&&s.value!==a.value&&setAttr(i,"value",s.value);for(n in a)null==s[n]&&(isXlink(n)?i.removeAttributeNS(xlinkNS,getXlinkProp(n)):isEnumeratedAttr(n)||i.removeAttribute(n))}}function setAttr(e,t,n){isBooleanAttr(t)?isFalsyAttrValue(n)?e.removeAttribute(t):e.setAttribute(t,t):isEnumeratedAttr(t)?e.setAttribute(t,isFalsyAttrValue(n)||"false"===n?"false":"true"):isXlink(t)?isFalsyAttrValue(n)?e.removeAttributeNS(xlinkNS,getXlinkProp(t)):e.setAttributeNS(xlinkNS,t,n):isFalsyAttrValue(n)?e.removeAttribute(t):e.setAttribute(t,n)}function updateClass(e,t){var n=t.elm,r=t.data,o=e.data;if(r.staticClass||r.class||o&&(o.staticClass||o.class)){var i=genClassForVnode(t),a=n._transitionClasses;a&&(i=concat(i,stringifyClass(a))),i!==n._prevClass&&(n.setAttribute("class",i),n._prevClass=i)}}function parseFilters(e){function t(){(a||(a=[])).push(e.slice(v,o).trim()),v=o+1}var n,r,o,i,a,s=!1,c=!1,l=!1,d=!1,u=0,p=0,f=0,v=0;for(o=0;o<e.length;o++)if(r=n,n=e.charCodeAt(o),s)39===n&&92!==r&&(s=!1);else if(c)34===n&&92!==r&&(c=!1);else if(l)96===n&&92!==r&&(l=!1);else if(d)47===n&&92!==r&&(d=!1);else if(124!==n||124===e.charCodeAt(o+1)||124===e.charCodeAt(o-1)||u||p||f){switch(n){case 34:c=!0;break;case 39:s=!0;break;case 96:l=!0;break;case 40:f++;break;case 41:f--;break;case 91:p++;break;case 93:p--;break;case 123:u++;break;case 125:u--}if(47===n){for(var m=o-1,h=void 0;m>=0&&(h=e.charAt(m)," "===h);m--);h&&validDivisionCharRE.test(h)||(d=!0)}}else void 0===i?(v=o+1,i=e.slice(0,o).trim()):t();if(void 0===i?i=e.slice(0,o).trim():0!==v&&t(),a)for(o=0;o<a.length;o++)i=wrapFilter(i,a[o]);return i}function wrapFilter(e,t){var n=t.indexOf("(");if(n<0)return'_f("'+t+'")('+e+")";var r=t.slice(0,n),o=t.slice(n+1);return'_f("'+r+'")('+e+","+o}function baseWarn(e){console.error("[Vue compiler]: "+e)}function pluckModuleFunction(e,t){return e?e.map(function(e){return e[t]}).filter(function(e){return e}):[]}function addProp(e,t,n){(e.props||(e.props=[])).push({name:t,value:n})}function addAttr(e,t,n){(e.attrs||(e.attrs=[])).push({name:t,value:n})}function addDirective(e,t,n,r,o,i){(e.directives||(e.directives=[])).push({name:t,rawName:n,value:r,arg:o,modifiers:i})}function addHandler(e,t,n,r,o){r&&r.capture&&(delete r.capture,t="!"+t),r&&r.once&&(delete r.once,t="~"+t);var i;r&&r.native?(delete r.native,i=e.nativeEvents||(e.nativeEvents={})):i=e.events||(e.events={});var a={value:n,modifiers:r},s=i[t];Array.isArray(s)?o?s.unshift(a):s.push(a):s?i[t]=o?[a,s]:[s,a]:i[t]=a}function getBindingAttr(e,t,n){var r=getAndRemoveAttr(e,":"+t)||getAndRemoveAttr(e,"v-bind:"+t);if(null!=r)return parseFilters(r);if(n!==!1){var o=getAndRemoveAttr(e,t);if(null!=o)return JSON.stringify(o)}}function getAndRemoveAttr(e,t){var n;if(null!=(n=e.attrsMap[t]))for(var r=e.attrsList,o=0,i=r.length;o<i;o++)if(r[o].name===t){r.splice(o,1);break}return n}function genComponentModel(e,t,n){var r=n||{},o=r.number,i=r.trim,a="$$v",s=a;i&&(s="(typeof "+a+" === 'string'? "+a+".trim(): "+a+")"),o&&(s="_n("+s+")");var c=genAssignmentCode(t,s);e.model={value:"("+t+")",callback:"function ("+a+") {"+c+"}"}}function genAssignmentCode(e,t){var n=parseModel(e);return null===n.idx?e+"="+t:"var $$exp = "+n.exp+", $$idx = "+n.idx+";if (!Array.isArray($$exp)){"+e+"="+t+"}else{$$exp.splice($$idx, 1, "+t+")}"}function parseModel(e){if(str=e,len=str.length,index$1=expressionPos=expressionEndPos=0,e.indexOf("[")<0||e.lastIndexOf("]")<len-1)return{exp:e,idx:null};for(;!eof();)chr=next(),isStringStart(chr)?parseString(chr):91===chr&&parseBracket(chr);return{exp:e.substring(0,expressionPos),idx:e.substring(expressionPos+1,expressionEndPos)}}function next(){return str.charCodeAt(++index$1)}function eof(){return index$1>=len}function isStringStart(e){return 34===e||39===e}function parseBracket(e){var t=1;for(expressionPos=index$1;!eof();)if(e=next(),isStringStart(e))parseString(e);else if(91===e&&t++,93===e&&t--,0===t){expressionEndPos=index$1;break}}function parseString(e){for(var t=e;!eof()&&(e=next(),e!==t););}function model(e,t,n){warn$1=n;var r=t.value,o=t.modifiers,i=e.tag,a=e.attrsMap.type;if("production"!==process.env.NODE_ENV){var s=e.attrsMap["v-bind:type"]||e.attrsMap[":type"];"input"===i&&s&&warn$1('<input :type="'+s+'" v-model="'+r+'">:\nv-model does not support dynamic input types. Use v-if branches instead.'),"input"===i&&"file"===a&&warn$1("<"+e.tag+' v-model="'+r+'" type="file">:\nFile inputs are read only. Use a v-on:change listener instead.')}if("select"===i)genSelect(e,r,o);else if("input"===i&&"checkbox"===a)genCheckboxModel(e,r,o);else if("input"===i&&"radio"===a)genRadioModel(e,r,o);else if("input"===i||"textarea"===i)genDefaultModel(e,r,o);else{if(!config.isReservedTag(i))return genComponentModel(e,r,o),!1;"production"!==process.env.NODE_ENV&&warn$1("<"+e.tag+' v-model="'+r+"\">: v-model is not supported on this element type. If you are working with contenteditable, it's recommended to wrap a library dedicated for that purpose inside a custom component.")}return!0}function genCheckboxModel(e,t,n){"production"!==process.env.NODE_ENV&&null!=e.attrsMap.checked&&warn$1("<"+e.tag+' v-model="'+t+"\" checked>:\ninline checked attributes will be ignored when using v-model. Declare initial values in the component's data option instead.");var r=n&&n.number,o=getBindingAttr(e,"value")||"null",i=getBindingAttr(e,"true-value")||"true",a=getBindingAttr(e,"false-value")||"false";addProp(e,"checked","Array.isArray("+t+")?_i("+t+","+o+")>-1"+("true"===i?":("+t+")":":_q("+t+","+i+")")),addHandler(e,CHECKBOX_RADIO_TOKEN,"var $$a="+t+",$$el=$event.target,$$c=$$el.checked?("+i+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+o+")":o)+",$$i=_i($$a,$$v);if($$c){$$i<0&&("+t+"=$$a.concat($$v))}else{$$i>-1&&("+t+"=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}}else{"+t+"=$$c}",null,!0)}function genRadioModel(e,t,n){"production"!==process.env.NODE_ENV&&null!=e.attrsMap.checked&&warn$1("<"+e.tag+' v-model="'+t+"\" checked>:\ninline checked attributes will be ignored when using v-model. Declare initial values in the component's data option instead.");var r=n&&n.number,o=getBindingAttr(e,"value")||"null";o=r?"_n("+o+")":o,addProp(e,"checked","_q("+t+","+o+")"),addHandler(e,CHECKBOX_RADIO_TOKEN,genAssignmentCode(t,o),null,!0)}function genSelect(e,t,n){"production"!==process.env.NODE_ENV&&e.children.some(checkOptionWarning);var r=n&&n.number,o='Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = "_value" in o ? o._value : o.value;return '+(r?"_n(val)":"val")+"})",i="$event.target.multiple ? $$selectedVal : $$selectedVal[0]",a="var $$selectedVal = "+o+";";a=a+" "+genAssignmentCode(t,i),addHandler(e,"change",a,null,!0)}function checkOptionWarning(e){return 1===e.type&&"option"===e.tag&&null!=e.attrsMap.selected&&(warn$1('<select v-model="'+e.parent.attrsMap["v-model"]+"\">:\ninline selected attributes on <option> will be ignored when using v-model. Declare initial values in the component's data option instead."),!0)}function genDefaultModel(e,t,n){var r=e.attrsMap.type,o=n||{},i=o.lazy,a=o.number,s=o.trim,c=!i&&"range"!==r,l=i?"change":"range"===r?RANGE_TOKEN:"input",d="$event.target.value";s&&(d="$event.target.value.trim()"),a&&(d="_n("+d+")");var u=genAssignmentCode(t,d);c&&(u="if($event.target.composing)return;"+u),addProp(e,"value","("+t+")"),addHandler(e,l,u,null,!0),(s||a||"number"===r)&&addHandler(e,"blur","$forceUpdate()")}function normalizeEvents(e){var t;e[RANGE_TOKEN]&&(t=isIE?"change":"input",e[t]=[].concat(e[RANGE_TOKEN],e[t]||[]),delete e[RANGE_TOKEN]),e[CHECKBOX_RADIO_TOKEN]&&(t=isChrome?"click":"change",e[t]=[].concat(e[CHECKBOX_RADIO_TOKEN],e[t]||[]),delete e[CHECKBOX_RADIO_TOKEN])}function add$1(e,t,n,r){if(n){var o=t,i=target$1;t=function(n){var a=1===arguments.length?o(n):o.apply(null,arguments);null!==a&&remove$2(e,t,r,i)}}target$1.addEventListener(e,t,r)}function remove$2(e,t,n,r){(r||target$1).removeEventListener(e,t,n)}function updateDOMListeners(e,t){if(e.data.on||t.data.on){var n=t.data.on||{},r=e.data.on||{};target$1=t.elm,normalizeEvents(n),updateListeners(n,r,add$1,remove$2,t.context)}}function updateDOMProps(e,t){if(e.data.domProps||t.data.domProps){var n,r,o=t.elm,i=e.data.domProps||{},a=t.data.domProps||{};a.__ob__&&(a=t.data.domProps=extend({},a));for(n in i)null==a[n]&&(o[n]="");for(n in a)if(r=a[n],"textContent"!==n&&"innerHTML"!==n||(t.children&&(t.children.length=0),r!==i[n]))if("value"===n){o._value=r;var s=null==r?"":String(r);shouldUpdateValue(o,t,s)&&(o.value=s)}else o[n]=r}}function shouldUpdateValue(e,t,n){return!e.composing&&("option"===t.tag||isDirty(e,n)||isInputChanged(e,n))}function isDirty(e,t){return document.activeElement!==e&&e.value!==t}function isInputChanged(e,t){var n=e.value,r=e._vModifiers;return r&&r.number||"number"===e.type?toNumber(n)!==toNumber(t):r&&r.trim?n.trim()!==t.trim():n!==t}function normalizeStyleData(e){var t=normalizeStyleBinding(e.style);return e.staticStyle?extend(e.staticStyle,t):t}function normalizeStyleBinding(e){return Array.isArray(e)?toObject(e):"string"==typeof e?parseStyleText(e):e}function getStyle(e,t){var n,r={};if(t)for(var o=e;o.componentInstance;)o=o.componentInstance._vnode,o.data&&(n=normalizeStyleData(o.data))&&extend(r,n);(n=normalizeStyleData(e.data))&&extend(r,n);for(var i=e;i=i.parent;)i.data&&(n=normalizeStyleData(i.data))&&extend(r,n);return r}function updateStyle(e,t){var n=t.data,r=e.data;if(n.staticStyle||n.style||r.staticStyle||r.style){var o,i,a=t.elm,s=e.data.staticStyle,c=e.data.style||{},l=s||c,d=normalizeStyleBinding(t.data.style)||{};t.data.style=d.__ob__?extend({},d):d;var u=getStyle(t,!0);for(i in l)null==u[i]&&setProp(a,i,"");for(i in u)o=u[i],o!==l[i]&&setProp(a,i,null==o?"":o)}}function addClass(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(" ")>-1?t.split(/\s+/).forEach(function(t){return e.classList.add(t)}):e.classList.add(t);else{var n=" "+(e.getAttribute("class")||"")+" ";n.indexOf(" "+t+" ")<0&&e.setAttribute("class",(n+t).trim())}}function removeClass(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(" ")>-1?t.split(/\s+/).forEach(function(t){return e.classList.remove(t)}):e.classList.remove(t);else{for(var n=" "+(e.getAttribute("class")||"")+" ",r=" "+t+" ";n.indexOf(r)>=0;)n=n.replace(r," ");e.setAttribute("class",n.trim())}}function resolveTransition(e){if(e){if("object"==typeof e){var t={};return e.css!==!1&&extend(t,autoCssTransition(e.name||"v")),extend(t,e),t}return"string"==typeof e?autoCssTransition(e):void 0}}function nextFrame(e){raf(function(){raf(e)})}function addTransitionClass(e,t){(e._transitionClasses||(e._transitionClasses=[])).push(t),addClass(e,t)}function removeTransitionClass(e,t){e._transitionClasses&&remove(e._transitionClasses,t),removeClass(e,t)}function whenTransitionEnds(e,t,n){var r=getTransitionInfo(e,t),o=r.type,i=r.timeout,a=r.propCount;if(!o)return n();var s=o===TRANSITION?transitionEndEvent:animationEndEvent,c=0,l=function(){e.removeEventListener(s,d),n()},d=function(t){t.target===e&&++c>=a&&l()};setTimeout(function(){c<a&&l()},i+1),e.addEventListener(s,d)}function getTransitionInfo(e,t){var n,r=window.getComputedStyle(e),o=r[transitionProp+"Delay"].split(", "),i=r[transitionProp+"Duration"].split(", "),a=getTimeout(o,i),s=r[animationProp+"Delay"].split(", "),c=r[animationProp+"Duration"].split(", "),l=getTimeout(s,c),d=0,u=0;t===TRANSITION?a>0&&(n=TRANSITION,d=a,u=i.length):t===ANIMATION?l>0&&(n=ANIMATION,d=l,u=c.length):(d=Math.max(a,l),n=d>0?a>l?TRANSITION:ANIMATION:null,u=n?n===TRANSITION?i.length:c.length:0);var p=n===TRANSITION&&transformRE.test(r[transitionProp+"Property"]);return{type:n,timeout:d,propCount:u,hasTransform:p}}function getTimeout(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max.apply(null,t.map(function(t,n){return toMs(t)+toMs(e[n])}))}function toMs(e){return 1e3*Number(e.slice(0,-1))}function enter(e,t){var n=e.elm;n._leaveCb&&(n._leaveCb.cancelled=!0,n._leaveCb());var r=resolveTransition(e.data.transition);if(r&&!n._enterCb&&1===n.nodeType){for(var o=r.css,i=r.type,a=r.enterClass,s=r.enterToClass,c=r.enterActiveClass,l=r.appearClass,d=r.appearToClass,u=r.appearActiveClass,p=r.beforeEnter,f=r.enter,v=r.afterEnter,m=r.enterCancelled,h=r.beforeAppear,g=r.appear,y=r.afterAppear,_=r.appearCancelled,b=r.duration,E=activeInstance,N=activeInstance.$vnode;N&&N.parent;)N=N.parent,E=N.context;var C=!E._isMounted||!e.isRootInsert;if(!C||g||""===g){var O=C&&l?l:a,w=C&&u?u:c,$=C&&d?d:s,k=C?h||p:p,x=C&&"function"==typeof g?g:f,A=C?y||v:v,T=C?_||m:m,D=isObject(b)?b.enter:b;"production"!==process.env.NODE_ENV&&null!=D&&checkDuration(D,"enter",e);var S=o!==!1&&!isIE9,I=getHookAgumentsLength(x),P=n._enterCb=once(function(){S&&(removeTransitionClass(n,$),removeTransitionClass(n,w)),P.cancelled?(S&&removeTransitionClass(n,O),T&&T(n)):A&&A(n),n._enterCb=null});e.data.show||mergeVNodeHook(e.data.hook||(e.data.hook={}),"insert",function(){var t=n.parentNode,r=t&&t._pending&&t._pending[e.key];r&&r.tag===e.tag&&r.elm._leaveCb&&r.elm._leaveCb(),x&&x(n,P)}),k&&k(n),S&&(addTransitionClass(n,O),addTransitionClass(n,w),nextFrame(function(){addTransitionClass(n,$),removeTransitionClass(n,O),P.cancelled||I||(isValidDuration(D)?setTimeout(P,D):whenTransitionEnds(n,i,P))})),e.data.show&&(t&&t(),x&&x(n,P)),S||I||P()}}}function leave(e,t){function n(){_.cancelled||(e.data.show||((r.parentNode._pending||(r.parentNode._pending={}))[e.key]=e),d&&d(r),h&&(addTransitionClass(r,s),addTransitionClass(r,l),nextFrame(function(){addTransitionClass(r,c),removeTransitionClass(r,s),_.cancelled||g||(isValidDuration(y)?setTimeout(_,y):whenTransitionEnds(r,a,_))})),u&&u(r,_),h||g||_())}var r=e.elm;r._enterCb&&(r._enterCb.cancelled=!0,r._enterCb());var o=resolveTransition(e.data.transition);if(!o)return t();if(!r._leaveCb&&1===r.nodeType){var i=o.css,a=o.type,s=o.leaveClass,c=o.leaveToClass,l=o.leaveActiveClass,d=o.beforeLeave,u=o.leave,p=o.afterLeave,f=o.leaveCancelled,v=o.delayLeave,m=o.duration,h=i!==!1&&!isIE9,g=getHookAgumentsLength(u),y=isObject(m)?m.leave:m;"production"!==process.env.NODE_ENV&&null!=y&&checkDuration(y,"leave",e);var _=r._leaveCb=once(function(){r.parentNode&&r.parentNode._pending&&(r.parentNode._pending[e.key]=null),h&&(removeTransitionClass(r,c),removeTransitionClass(r,l)),_.cancelled?(h&&removeTransitionClass(r,s),f&&f(r)):(t(),p&&p(r)),r._leaveCb=null});v?v(n):n()}}function checkDuration(e,t,n){"number"!=typeof e?warn("<transition> explicit "+t+" duration is not a valid number - got "+JSON.stringify(e)+".",n.context):isNaN(e)&&warn("<transition> explicit "+t+" duration is NaN - the duration expression might be incorrect.",n.context)}function isValidDuration(e){return"number"==typeof e&&!isNaN(e)}function getHookAgumentsLength(e){if(!e)return!1;var t=e.fns;return t?getHookAgumentsLength(Array.isArray(t)?t[0]:t):(e._length||e.length)>1}function _enter(e,t){t.data.show||enter(t)}function setSelected(e,t,n){var r=t.value,o=e.multiple;if(o&&!Array.isArray(r))return void("production"!==process.env.NODE_ENV&&warn('<select multiple v-model="'+t.expression+'"> expects an Array value for its binding, but got '+Object.prototype.toString.call(r).slice(8,-1),n));for(var i,a,s=0,c=e.options.length;s<c;s++)if(a=e.options[s],o)i=looseIndexOf(r,getValue(a))>-1,a.selected!==i&&(a.selected=i);else if(looseEqual(getValue(a),r))return void(e.selectedIndex!==s&&(e.selectedIndex=s));o||(e.selectedIndex=-1)}function hasNoMatchingOption(e,t){for(var n=0,r=t.length;n<r;n++)if(looseEqual(getValue(t[n]),e))return!1;return!0}function getValue(e){return"_value"in e?e._value:e.value}function onCompositionStart(e){e.target.composing=!0}function onCompositionEnd(e){e.target.composing=!1,trigger(e.target,"input")}function trigger(e,t){var n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function locateNode(e){return!e.componentInstance||e.data&&e.data.transition?e:locateNode(e.componentInstance._vnode)}function getRealChild(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?getRealChild(getFirstComponentChild(t.children)):e}function extractTransitionData(e){var t={},n=e.$options;for(var r in n.propsData)t[r]=e[r];var o=n._parentListeners;for(var i in o)t[camelize(i)]=o[i];return t}function placeholder(e,t){return/\d-keep-alive$/.test(t.tag)?e("keep-alive"):null}function hasParentTransition(e){for(;e=e.parent;)if(e.data.transition)return!0}function isSameChild(e,t){return t.key===e.key&&t.tag===e.tag}function callPendingCbs(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function recordPosition(e){e.data.newPos=e.elm.getBoundingClientRect()}function applyTranslation(e){var t=e.data.pos,n=e.data.newPos,r=t.left-n.left,o=t.top-n.top;if(r||o){e.data.moved=!0;var i=e.elm.style;i.transform=i.WebkitTransform="translate("+r+"px,"+o+"px)",i.transitionDuration="0s"}}function shouldDecode(e,t){var n=document.createElement("div");return n.innerHTML='<div a="'+e+'">',n.innerHTML.indexOf(t)>0}function decode(e){return decoder=decoder||document.createElement("div"),decoder.innerHTML=e,decoder.textContent}function decodeAttr(e,t){var n=t?encodedAttrWithNewLines:encodedAttr;return e.replace(n,function(e){return decodingMap[e]})}function parseHTML(e,t){function n(t){u+=t,e=e.substring(t)}function r(){var t=e.match(startTagOpen);if(t){var r={tagName:t[1],attrs:[],start:u};n(t[0].length);for(var o,i;!(o=e.match(startTagClose))&&(i=e.match(attribute));)n(i[0].length),r.attrs.push(i);if(o)return r.unarySlash=o[1],n(o[0].length),r.end=u,r}}function o(e){var n=e.tagName,r=e.unarySlash;l&&("p"===s&&isNonPhrasingTag(n)&&i(s),canBeLeftOpenTag(n)&&s===n&&i(n));for(var o=d(n)||"html"===n&&"head"===s||!!r,a=e.attrs.length,u=new Array(a),p=0;p<a;p++){var f=e.attrs[p];IS_REGEX_CAPTURING_BROKEN&&f[0].indexOf('""')===-1&&(""===f[3]&&delete f[3],""===f[4]&&delete f[4],""===f[5]&&delete f[5]);var v=f[3]||f[4]||f[5]||"";u[p]={name:f[1],value:decodeAttr(v,t.shouldDecodeNewlines)}}o||(c.push({tag:n,lowerCasedTag:n.toLowerCase(),attrs:u}),s=n),t.start&&t.start(n,u,o,e.start,e.end)}function i(e,n,r){var o,i;if(null==n&&(n=u),null==r&&(r=u),e&&(i=e.toLowerCase()),e)for(o=c.length-1;o>=0&&c[o].lowerCasedTag!==i;o--);else o=0;if(o>=0){for(var a=c.length-1;a>=o;a--)"production"!==process.env.NODE_ENV&&(a>o||!e)&&t.warn&&t.warn("tag <"+c[a].tag+"> has no matching end tag."),t.end&&t.end(c[a].tag,n,r);c.length=o,s=o&&c[o-1].tag}else"br"===i?t.start&&t.start(e,[],!0,n,r):"p"===i&&(t.start&&t.start(e,[],!1,n,r),t.end&&t.end(e,n,r))}for(var a,s,c=[],l=t.expectHTML,d=t.isUnaryTag||no,u=0;e;){if(a=e,s&&isScriptOrStyle(s)){var p=s.toLowerCase(),f=reCache[p]||(reCache[p]=new RegExp("([\\s\\S]*?)(</"+p+"[^>]*>)","i")),v=0,m=e.replace(f,function(e,n,r){return v=r.length,"script"!==p&&"style"!==p&&"noscript"!==p&&(n=n.replace(/<!--([\s\S]*?)-->/g,"$1").replace(/<!\[CDATA\[([\s\S]*?)]]>/g,"$1")),t.chars&&t.chars(n),""});u+=e.length-m.length,e=m,i(p,u-v,u)}else{var h=e.indexOf("<");if(0===h){if(comment.test(e)){var g=e.indexOf("-->");if(g>=0){n(g+3);continue}}if(conditionalComment.test(e)){var y=e.indexOf("]>");if(y>=0){n(y+2);continue}}var _=e.match(doctype);if(_){n(_[0].length);continue}var b=e.match(endTag);if(b){var E=u;n(b[0].length),i(b[1],E,u);continue}var N=r();if(N){o(N);continue}}var C=void 0,O=void 0,w=void 0;if(h>=0){for(O=e.slice(h);!(endTag.test(O)||startTagOpen.test(O)||comment.test(O)||conditionalComment.test(O)||(w=O.indexOf("<",1),w<0));)h+=w,O=e.slice(h);C=e.substring(0,h),n(h)}h<0&&(C=e,e=""),t.chars&&C&&t.chars(C)}if(e===a){t.chars&&t.chars(e),"production"!==process.env.NODE_ENV&&!c.length&&t.warn&&t.warn('Mal-formatted tag at end of template: "'+e+'"');break}}i()}function parseText(e,t){var n=t?buildRegex(t):defaultTagRE;if(n.test(e)){for(var r,o,i=[],a=n.lastIndex=0;r=n.exec(e);){o=r.index,o>a&&i.push(JSON.stringify(e.slice(a,o)));var s=parseFilters(r[1].trim());i.push("_s("+s+")"),a=o+r[0].length}return a<e.length&&i.push(JSON.stringify(e.slice(a))),i.join("+")}}function parse(e,t){function n(e){e.pre&&(s=!1),platformIsPreTag(e.tag)&&(c=!1)}warn$2=t.warn||baseWarn,platformGetTagNamespace=t.getTagNamespace||no,platformMustUseProp=t.mustUseProp||no,platformIsPreTag=t.isPreTag||no,preTransforms=pluckModuleFunction(t.modules,"preTransformNode"),transforms=pluckModuleFunction(t.modules,"transformNode"),postTransforms=pluckModuleFunction(t.modules,"postTransformNode"),delimiters=t.delimiters;var r,o,i=[],a=t.preserveWhitespace!==!1,s=!1,c=!1,l=!1;return parseHTML(e,{warn:warn$2,expectHTML:t.expectHTML,isUnaryTag:t.isUnaryTag,shouldDecodeNewlines:t.shouldDecodeNewlines,start:function(e,a,d){function u(e){"production"===process.env.NODE_ENV||l||("slot"!==e.tag&&"template"!==e.tag||(l=!0,warn$2("Cannot use <"+e.tag+"> as component root element because it may contain multiple nodes.")),e.attrsMap.hasOwnProperty("v-for")&&(l=!0,warn$2("Cannot use v-for on stateful component root element because it renders multiple elements.")))}var p=o&&o.ns||platformGetTagNamespace(e);isIE&&"svg"===p&&(a=guardIESVGBug(a)); var f={type:1,tag:e,attrsList:a,attrsMap:makeAttrsMap(a),parent:o,children:[]};p&&(f.ns=p),isForbiddenTag(f)&&!isServerRendering()&&(f.forbidden=!0,"production"!==process.env.NODE_ENV&&warn$2("Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <"+e+">, as they will not be parsed."));for(var v=0;v<preTransforms.length;v++)preTransforms[v](f,t);if(s||(processPre(f),f.pre&&(s=!0)),platformIsPreTag(f.tag)&&(c=!0),s)processRawAttrs(f);else{processFor(f),processIf(f),processOnce(f),processKey(f),f.plain=!f.key&&!a.length,processRef(f),processSlot(f),processComponent(f);for(var m=0;m<transforms.length;m++)transforms[m](f,t);processAttrs(f)}if(r?i.length||(r.if&&(f.elseif||f.else)?(u(f),addIfCondition(r,{exp:f.elseif,block:f})):"production"===process.env.NODE_ENV||l||(l=!0,warn$2("Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead."))):(r=f,u(r)),o&&!f.forbidden)if(f.elseif||f.else)processIfConditions(f,o);else if(f.slotScope){o.plain=!1;var h=f.slotTarget||'"default"';(o.scopedSlots||(o.scopedSlots={}))[h]=f}else o.children.push(f),f.parent=o;d?n(f):(o=f,i.push(f));for(var g=0;g<postTransforms.length;g++)postTransforms[g](f,t)},end:function(){var e=i[i.length-1],t=e.children[e.children.length-1];t&&3===t.type&&" "===t.text&&!c&&e.children.pop(),i.length-=1,o=i[i.length-1],n(e)},chars:function(t){if(!o)return void("production"===process.env.NODE_ENV||l||t!==e||(l=!0,warn$2("Component template requires a root element, rather than just text.")));if(!isIE||"textarea"!==o.tag||o.attrsMap.placeholder!==t){var n=o.children;if(t=c||t.trim()?decodeHTMLCached(t):a&&n.length?" ":""){var r;!s&&" "!==t&&(r=parseText(t,delimiters))?n.push({type:2,expression:r,text:t}):" "===t&&n.length&&" "===n[n.length-1].text||n.push({type:3,text:t})}}}}),r}function processPre(e){null!=getAndRemoveAttr(e,"v-pre")&&(e.pre=!0)}function processRawAttrs(e){var t=e.attrsList.length;if(t)for(var n=e.attrs=new Array(t),r=0;r<t;r++)n[r]={name:e.attrsList[r].name,value:JSON.stringify(e.attrsList[r].value)};else e.pre||(e.plain=!0)}function processKey(e){var t=getBindingAttr(e,"key");t&&("production"!==process.env.NODE_ENV&&"template"===e.tag&&warn$2("<template> cannot be keyed. Place the key on real elements instead."),e.key=t)}function processRef(e){var t=getBindingAttr(e,"ref");t&&(e.ref=t,e.refInFor=checkInFor(e))}function processFor(e){var t;if(t=getAndRemoveAttr(e,"v-for")){var n=t.match(forAliasRE);if(!n)return void("production"!==process.env.NODE_ENV&&warn$2("Invalid v-for expression: "+t));e.for=n[2].trim();var r=n[1].trim(),o=r.match(forIteratorRE);o?(e.alias=o[1].trim(),e.iterator1=o[2].trim(),o[3]&&(e.iterator2=o[3].trim())):e.alias=r}}function processIf(e){var t=getAndRemoveAttr(e,"v-if");if(t)e.if=t,addIfCondition(e,{exp:t,block:e});else{null!=getAndRemoveAttr(e,"v-else")&&(e.else=!0);var n=getAndRemoveAttr(e,"v-else-if");n&&(e.elseif=n)}}function processIfConditions(e,t){var n=findPrevElement(t.children);n&&n.if?addIfCondition(n,{exp:e.elseif,block:e}):"production"!==process.env.NODE_ENV&&warn$2("v-"+(e.elseif?'else-if="'+e.elseif+'"':"else")+" used on element <"+e.tag+"> without corresponding v-if.")}function findPrevElement(e){for(var t=e.length;t--;){if(1===e[t].type)return e[t];"production"!==process.env.NODE_ENV&&" "!==e[t].text&&warn$2('text "'+e[t].text.trim()+'" between v-if and v-else(-if) will be ignored.'),e.pop()}}function addIfCondition(e,t){e.ifConditions||(e.ifConditions=[]),e.ifConditions.push(t)}function processOnce(e){var t=getAndRemoveAttr(e,"v-once");null!=t&&(e.once=!0)}function processSlot(e){if("slot"===e.tag)e.slotName=getBindingAttr(e,"name"),"production"!==process.env.NODE_ENV&&e.key&&warn$2("`key` does not work on <slot> because slots are abstract outlets and can possibly expand into multiple elements. Use the key on a wrapping element instead.");else{var t=getBindingAttr(e,"slot");t&&(e.slotTarget='""'===t?'"default"':t),"template"===e.tag&&(e.slotScope=getAndRemoveAttr(e,"scope"))}}function processComponent(e){var t;(t=getBindingAttr(e,"is"))&&(e.component=t),null!=getAndRemoveAttr(e,"inline-template")&&(e.inlineTemplate=!0)}function processAttrs(e){var t,n,r,o,i,a,s,c,l=e.attrsList;for(t=0,n=l.length;t<n;t++)if(r=o=l[t].name,i=l[t].value,dirRE.test(r))if(e.hasBindings=!0,s=parseModifiers(r),s&&(r=r.replace(modifierRE,"")),bindRE.test(r))r=r.replace(bindRE,""),i=parseFilters(i),c=!1,s&&(s.prop&&(c=!0,r=camelize(r),"innerHtml"===r&&(r="innerHTML")),s.camel&&(r=camelize(r))),c||platformMustUseProp(e.tag,e.attrsMap.type,r)?addProp(e,r,i):addAttr(e,r,i);else if(onRE.test(r))r=r.replace(onRE,""),addHandler(e,r,i,s);else{r=r.replace(dirRE,"");var d=r.match(argRE);d&&(a=d[1])&&(r=r.slice(0,-(a.length+1))),addDirective(e,r,o,i,a,s),"production"!==process.env.NODE_ENV&&"model"===r&&checkForAliasModel(e,i)}else{if("production"!==process.env.NODE_ENV){var u=parseText(i,delimiters);u&&warn$2(r+'="'+i+'": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div id="{{ val }}">, use <div :id="val">.')}addAttr(e,r,JSON.stringify(i))}}function checkInFor(e){for(var t=e;t;){if(void 0!==t.for)return!0;t=t.parent}return!1}function parseModifiers(e){var t=e.match(modifierRE);if(t){var n={};return t.forEach(function(e){n[e.slice(1)]=!0}),n}}function makeAttrsMap(e){for(var t={},n=0,r=e.length;n<r;n++)"production"!==process.env.NODE_ENV&&t[e[n].name]&&!isIE&&warn$2("duplicate attribute: "+e[n].name),t[e[n].name]=e[n].value;return t}function isForbiddenTag(e){return"style"===e.tag||"script"===e.tag&&(!e.attrsMap.type||"text/javascript"===e.attrsMap.type)}function guardIESVGBug(e){for(var t=[],n=0;n<e.length;n++){var r=e[n];ieNSBug.test(r.name)||(r.name=r.name.replace(ieNSPrefix,""),t.push(r))}return t}function checkForAliasModel(e,t){for(var n=e;n;)n.for&&n.alias===t&&warn$2("<"+e.tag+' v-model="'+t+'">: You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instead.'),n=n.parent}function optimize(e,t){e&&(isStaticKey=genStaticKeysCached(t.staticKeys||""),isPlatformReservedTag=t.isReservedTag||no,markStatic$1(e),markStaticRoots(e,!1))}function genStaticKeys$1(e){return makeMap("type,tag,attrsList,attrsMap,plain,parent,children,attrs"+(e?","+e:""))}function markStatic$1(e){if(e.static=isStatic(e),1===e.type){if(!isPlatformReservedTag(e.tag)&&"slot"!==e.tag&&null==e.attrsMap["inline-template"])return;for(var t=0,n=e.children.length;t<n;t++){var r=e.children[t];markStatic$1(r),r.static||(e.static=!1)}}}function markStaticRoots(e,t){if(1===e.type){if((e.static||e.once)&&(e.staticInFor=t),e.static&&e.children.length&&(1!==e.children.length||3!==e.children[0].type))return void(e.staticRoot=!0);if(e.staticRoot=!1,e.children)for(var n=0,r=e.children.length;n<r;n++)markStaticRoots(e.children[n],t||!!e.for);e.ifConditions&&walkThroughConditionsBlocks(e.ifConditions,t)}}function walkThroughConditionsBlocks(e,t){for(var n=1,r=e.length;n<r;n++)markStaticRoots(e[n].block,t)}function isStatic(e){return 2!==e.type&&(3===e.type||!(!e.pre&&(e.hasBindings||e.if||e.for||isBuiltInTag(e.tag)||!isPlatformReservedTag(e.tag)||isDirectChildOfTemplateFor(e)||!Object.keys(e).every(isStaticKey))))}function isDirectChildOfTemplateFor(e){for(;e.parent;){if(e=e.parent,"template"!==e.tag)return!1;if(e.for)return!0}return!1}function genHandlers(e,t){var n=t?"nativeOn:{":"on:{";for(var r in e)n+='"'+r+'":'+genHandler(r,e[r])+",";return n.slice(0,-1)+"}"}function genHandler(e,t){if(t){if(Array.isArray(t))return"["+t.map(function(t){return genHandler(e,t)}).join(",")+"]";if(t.modifiers){var n="",r=[];for(var o in t.modifiers)modifierCode[o]?n+=modifierCode[o]:r.push(o);r.length&&(n=genKeyFilter(r)+n);var i=simplePathRE.test(t.value)?t.value+"($event)":t.value;return"function($event){"+n+i+"}"}return fnExpRE.test(t.value)||simplePathRE.test(t.value)?t.value:"function($event){"+t.value+"}"}return"function(){}"}function genKeyFilter(e){return"if("+e.map(genFilterCode).join("&&")+")return null;"}function genFilterCode(e){var t=parseInt(e,10);if(t)return"$event.keyCode!=="+t;var n=keyCodes[e];return"_k($event.keyCode,"+JSON.stringify(e)+(n?","+JSON.stringify(n):"")+")"}function bind$1(e,t){e.wrapData=function(n){return"_b("+n+",'"+e.tag+"',"+t.value+(t.modifiers&&t.modifiers.prop?",true":"")+")"}}function generate(e,t){var n=staticRenderFns,r=staticRenderFns=[],o=onceCount;onceCount=0,currentOptions=t,warn$3=t.warn||baseWarn,transforms$1=pluckModuleFunction(t.modules,"transformCode"),dataGenFns=pluckModuleFunction(t.modules,"genData"),platformDirectives$1=t.directives||{},isPlatformReservedTag$1=t.isReservedTag||no;var i=e?genElement(e):'_c("div")';return staticRenderFns=n,onceCount=o,{render:"with(this){return "+i+"}",staticRenderFns:r}}function genElement(e){if(e.staticRoot&&!e.staticProcessed)return genStatic(e);if(e.once&&!e.onceProcessed)return genOnce(e);if(e.for&&!e.forProcessed)return genFor(e);if(e.if&&!e.ifProcessed)return genIf(e);if("template"!==e.tag||e.slotTarget){if("slot"===e.tag)return genSlot(e);var t;if(e.component)t=genComponent(e.component,e);else{var n=e.plain?void 0:genData(e),r=e.inlineTemplate?null:genChildren(e,!0);t="_c('"+e.tag+"'"+(n?","+n:"")+(r?","+r:"")+")"}for(var o=0;o<transforms$1.length;o++)t=transforms$1[o](e,t);return t}return genChildren(e)||"void 0"}function genStatic(e){return e.staticProcessed=!0,staticRenderFns.push("with(this){return "+genElement(e)+"}"),"_m("+(staticRenderFns.length-1)+(e.staticInFor?",true":"")+")"}function genOnce(e){if(e.onceProcessed=!0,e.if&&!e.ifProcessed)return genIf(e);if(e.staticInFor){for(var t="",n=e.parent;n;){if(n.for){t=n.key;break}n=n.parent}return t?"_o("+genElement(e)+","+onceCount++ +(t?","+t:"")+")":("production"!==process.env.NODE_ENV&&warn$3("v-once can only be used inside v-for that is keyed. "),genElement(e))}return genStatic(e)}function genIf(e){return e.ifProcessed=!0,genIfConditions(e.ifConditions.slice())}function genIfConditions(e){function t(e){return e.once?genOnce(e):genElement(e)}if(!e.length)return"_e()";var n=e.shift();return n.exp?"("+n.exp+")?"+t(n.block)+":"+genIfConditions(e):""+t(n.block)}function genFor(e){var t=e.for,n=e.alias,r=e.iterator1?","+e.iterator1:"",o=e.iterator2?","+e.iterator2:"";return"production"!==process.env.NODE_ENV&&maybeComponent(e)&&"slot"!==e.tag&&"template"!==e.tag&&!e.key&&warn$3("<"+e.tag+' v-for="'+n+" in "+t+'">: component lists rendered with v-for should have explicit keys. See https://vuejs.org/guide/list.html#key for more info.',!0),e.forProcessed=!0,"_l(("+t+"),function("+n+r+o+"){return "+genElement(e)+"})"}function genData(e){var t="{",n=genDirectives(e);n&&(t+=n+","),e.key&&(t+="key:"+e.key+","),e.ref&&(t+="ref:"+e.ref+","),e.refInFor&&(t+="refInFor:true,"),e.pre&&(t+="pre:true,"),e.component&&(t+='tag:"'+e.tag+'",');for(var r=0;r<dataGenFns.length;r++)t+=dataGenFns[r](e);if(e.attrs&&(t+="attrs:{"+genProps(e.attrs)+"},"),e.props&&(t+="domProps:{"+genProps(e.props)+"},"),e.events&&(t+=genHandlers(e.events)+","),e.nativeEvents&&(t+=genHandlers(e.nativeEvents,!0)+","),e.slotTarget&&(t+="slot:"+e.slotTarget+","),e.scopedSlots&&(t+=genScopedSlots(e.scopedSlots)+","),e.model&&(t+="model:{value:"+e.model.value+",callback:"+e.model.callback+"},"),e.inlineTemplate){var o=genInlineTemplate(e);o&&(t+=o+",")}return t=t.replace(/,$/,"")+"}",e.wrapData&&(t=e.wrapData(t)),t}function genDirectives(e){var t=e.directives;if(t){var n,r,o,i,a="directives:[",s=!1;for(n=0,r=t.length;n<r;n++){o=t[n],i=!0;var c=platformDirectives$1[o.name]||baseDirectives[o.name];c&&(i=!!c(e,o,warn$3)),i&&(s=!0,a+='{name:"'+o.name+'",rawName:"'+o.rawName+'"'+(o.value?",value:("+o.value+"),expression:"+JSON.stringify(o.value):"")+(o.arg?',arg:"'+o.arg+'"':"")+(o.modifiers?",modifiers:"+JSON.stringify(o.modifiers):"")+"},")}return s?a.slice(0,-1)+"]":void 0}}function genInlineTemplate(e){var t=e.children[0];if("production"!==process.env.NODE_ENV&&(e.children.length>1||1!==t.type)&&warn$3("Inline-template components must have exactly one child element."),1===t.type){var n=generate(t,currentOptions);return"inlineTemplate:{render:function(){"+n.render+"},staticRenderFns:["+n.staticRenderFns.map(function(e){return"function(){"+e+"}"}).join(",")+"]}"}}function genScopedSlots(e){return"scopedSlots:_u(["+Object.keys(e).map(function(t){return genScopedSlot(t,e[t])}).join(",")+"])"}function genScopedSlot(e,t){return"["+e+",function("+String(t.attrsMap.scope)+"){return "+("template"===t.tag?genChildren(t)||"void 0":genElement(t))+"}]"}function genChildren(e,t){var n=e.children;if(n.length){var r=n[0];if(1===n.length&&r.for&&"template"!==r.tag&&"slot"!==r.tag)return genElement(r);var o=getNormalizationType(n);return"["+n.map(genNode).join(",")+"]"+(t&&o?","+o:"")}}function getNormalizationType(e){for(var t=0,n=0;n<e.length;n++){var r=e[n];if(1===r.type){if(needsNormalization(r)||r.ifConditions&&r.ifConditions.some(function(e){return needsNormalization(e.block)})){t=2;break}(maybeComponent(r)||r.ifConditions&&r.ifConditions.some(function(e){return maybeComponent(e.block)}))&&(t=1)}}return t}function needsNormalization(e){return void 0!==e.for||"template"===e.tag||"slot"===e.tag}function maybeComponent(e){return!isPlatformReservedTag$1(e.tag)}function genNode(e){return 1===e.type?genElement(e):genText(e)}function genText(e){return"_v("+(2===e.type?e.expression:transformSpecialNewlines(JSON.stringify(e.text)))+")"}function genSlot(e){var t=e.slotName||'"default"',n=genChildren(e),r="_t("+t+(n?","+n:""),o=e.attrs&&"{"+e.attrs.map(function(e){return camelize(e.name)+":"+e.value}).join(",")+"}",i=e.attrsMap["v-bind"];return!o&&!i||n||(r+=",null"),o&&(r+=","+o),i&&(r+=(o?"":",null")+","+i),r+")"}function genComponent(e,t){var n=t.inlineTemplate?null:genChildren(t,!0);return"_c("+e+","+genData(t)+(n?","+n:"")+")"}function genProps(e){for(var t="",n=0;n<e.length;n++){var r=e[n];t+='"'+r.name+'":'+transformSpecialNewlines(r.value)+","}return t.slice(0,-1)}function transformSpecialNewlines(e){return e.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function detectErrors(e){var t=[];return e&&checkNode(e,t),t}function checkNode(e,t){if(1===e.type){for(var n in e.attrsMap)if(dirRE.test(n)){var r=e.attrsMap[n];r&&("v-for"===n?checkFor(e,'v-for="'+r+'"',t):checkExpression(r,n+'="'+r+'"',t))}if(e.children)for(var o=0;o<e.children.length;o++)checkNode(e.children[o],t)}else 2===e.type&&checkExpression(e.expression,e.text,t)}function checkFor(e,t,n){checkExpression(e.for||"",t,n),checkIdentifier(e.alias,"v-for alias",t,n),checkIdentifier(e.iterator1,"v-for iterator",t,n),checkIdentifier(e.iterator2,"v-for iterator",t,n)}function checkIdentifier(e,t,n,r){"string"!=typeof e||identRE.test(e)||r.push("invalid "+t+' "'+e+'" in expression: '+n.trim())}function checkExpression(e,t,n){try{new Function("return "+e)}catch(o){var r=e.replace(stripStringRE,"").match(prohibitedKeywordRE);r?n.push('avoid using JavaScript keyword as property name: "'+r[0]+'" in expression '+t.trim()):n.push("invalid expression: "+t.trim())}}function baseCompile(e,t){var n=parse(e.trim(),t);optimize(n,t);var r=generate(n,t);return{ast:n,render:r.render,staticRenderFns:r.staticRenderFns}}function makeFunction(e,t){try{return new Function(e)}catch(n){return t.push({err:n,code:e}),noop}}function createCompiler(e){function t(t,n){var r=Object.create(e),o=[],i=[];if(r.warn=function(e,t){(t?i:o).push(e)},n){n.modules&&(r.modules=(e.modules||[]).concat(n.modules)),n.directives&&(r.directives=extend(Object.create(e.directives),n.directives));for(var a in n)"modules"!==a&&"directives"!==a&&(r[a]=n[a])}var s=baseCompile(t,r);return"production"!==process.env.NODE_ENV&&o.push.apply(o,detectErrors(s.ast)),s.errors=o,s.tips=i,s}function n(e,n,o){if(n=n||{},"production"!==process.env.NODE_ENV)try{new Function("return 1")}catch(e){e.toString().match(/unsafe-eval|CSP/)&&warn("It seems you are using the standalone build of Vue.js in an environment with Content Security Policy that prohibits unsafe-eval. The template compiler cannot work in this environment. Consider relaxing the policy to allow unsafe-eval or pre-compiling your templates into render functions.")}var i=n.delimiters?String(n.delimiters)+e:e;if(r[i])return r[i];var a=t(e,n);"production"!==process.env.NODE_ENV&&(a.errors&&a.errors.length&&warn("Error compiling template:\n\n"+e+"\n\n"+a.errors.map(function(e){return"- "+e}).join("\n")+"\n",o),a.tips&&a.tips.length&&a.tips.forEach(function(e){return tip(e,o)}));var s={},c=[];s.render=makeFunction(a.render,c);var l=a.staticRenderFns.length;s.staticRenderFns=new Array(l);for(var d=0;d<l;d++)s.staticRenderFns[d]=makeFunction(a.staticRenderFns[d],c);return"production"!==process.env.NODE_ENV&&(a.errors&&a.errors.length||!c.length||warn("Failed to generate render function:\n\n"+c.map(function(e){var t=e.err,n=e.code;return t.toString()+" in\n\n"+n+"\n"}).join("\n"),o)),r[i]=s}var r=Object.create(null);return{compile:t,compileToFunctions:n}}function transformNode(e,t){var n=t.warn||baseWarn,r=getAndRemoveAttr(e,"class");if("production"!==process.env.NODE_ENV&&r){var o=parseText(r,t.delimiters);o&&n('class="'+r+'": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div class="{{ val }}">, use <div :class="val">.')}r&&(e.staticClass=JSON.stringify(r));var i=getBindingAttr(e,"class",!1);i&&(e.classBinding=i)}function genData$1(e){var t="";return e.staticClass&&(t+="staticClass:"+e.staticClass+","),e.classBinding&&(t+="class:"+e.classBinding+","),t}function transformNode$1(e,t){var n=t.warn||baseWarn,r=getAndRemoveAttr(e,"style");if(r){if("production"!==process.env.NODE_ENV){var o=parseText(r,t.delimiters);o&&n('style="'+r+'": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div style="{{ val }}">, use <div :style="val">.')}e.staticStyle=JSON.stringify(parseStyleText(r))}var i=getBindingAttr(e,"style",!1);i&&(e.styleBinding=i)}function genData$2(e){var t="";return e.staticStyle&&(t+="staticStyle:"+e.staticStyle+","),e.styleBinding&&(t+="style:("+e.styleBinding+"),"),t}function text(e,t){t.value&&addProp(e,"textContent","_s("+t.value+")")}function html(e,t){t.value&&addProp(e,"innerHTML","_s("+t.value+")")}function getOuterHTML(e){if(e.outerHTML)return e.outerHTML;var t=document.createElement("div");return t.appendChild(e.cloneNode(!0)),t.innerHTML}var isBuiltInTag=makeMap("slot,component",!0),hasOwnProperty=Object.prototype.hasOwnProperty,camelizeRE=/-(\w)/g,camelize=cached(function(e){return e.replace(camelizeRE,function(e,t){return t?t.toUpperCase():""})}),capitalize=cached(function(e){return e.charAt(0).toUpperCase()+e.slice(1)}),hyphenateRE=/([^-])([A-Z])/g,hyphenate=cached(function(e){return e.replace(hyphenateRE,"$1-$2").replace(hyphenateRE,"$1-$2").toLowerCase()}),toString=Object.prototype.toString,OBJECT_STRING="[object Object]",no=function(){return!1},identity=function(e){return e},config={optionMergeStrategies:Object.create(null),silent:!1,productionTip:"production"!==process.env.NODE_ENV,devtools:"production"!==process.env.NODE_ENV,performance:"production"!==process.env.NODE_ENV,errorHandler:null,ignoredElements:[],keyCodes:Object.create(null),isReservedTag:no,isUnknownElement:no,getTagNamespace:noop,parsePlatformTagName:identity,mustUseProp:no,_assetTypes:["component","directive","filter"],_lifecycleHooks:["beforeCreate","created","beforeMount","mounted","beforeUpdate","updated","beforeDestroy","destroyed","activated","deactivated"],_maxUpdateCount:100},hasProto="__proto__"in{},inBrowser="undefined"!=typeof window,UA=inBrowser&&window.navigator.userAgent.toLowerCase(),isIE=UA&&/msie|trident/.test(UA),isIE9=UA&&UA.indexOf("msie 9.0")>0,isEdge=UA&&UA.indexOf("edge/")>0,isAndroid=UA&&UA.indexOf("android")>0,isIOS=UA&&/iphone|ipad|ipod|ios/.test(UA),isChrome=UA&&/chrome\/\d+/.test(UA)&&!isEdge,_isServer,isServerRendering=function(){return void 0===_isServer&&(_isServer=!inBrowser&&"undefined"!=typeof global&&"server"===global.process.env.VUE_ENV),_isServer},devtools=inBrowser&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__,nextTick=function(){function e(){r=!1;var e=n.slice(0);n.length=0;for(var t=0;t<e.length;t++)e[t]()}var t,n=[],r=!1;if("undefined"!=typeof Promise&&isNative(Promise)){var o=Promise.resolve(),i=function(e){console.error(e)};t=function(){o.then(e).catch(i),isIOS&&setTimeout(noop)}}else if("undefined"==typeof MutationObserver||!isNative(MutationObserver)&&"[object MutationObserverConstructor]"!==MutationObserver.toString())t=function(){setTimeout(e,0)};else{var a=1,s=new MutationObserver(e),c=document.createTextNode(String(a));s.observe(c,{characterData:!0}),t=function(){a=(a+1)%2,c.data=String(a)}}return function(e,o){var i;if(n.push(function(){e&&e.call(o),i&&i(o)}),r||(r=!0,t()),!e&&"undefined"!=typeof Promise)return new Promise(function(e){i=e})}}(),_Set;_Set="undefined"!=typeof Set&&isNative(Set)?Set:function(){function e(){this.set=Object.create(null)}return e.prototype.has=function(e){return this.set[e]===!0},e.prototype.add=function(e){this.set[e]=!0},e.prototype.clear=function(){this.set=Object.create(null)},e}();var perf;"production"!==process.env.NODE_ENV&&(perf=inBrowser&&window.performance,!perf||perf.mark&&perf.measure||(perf=void 0));var emptyObject=Object.freeze({}),bailRE=/[^\w.$]/,warn=noop,tip=noop,formatComponentName;if("production"!==process.env.NODE_ENV){var hasConsole="undefined"!=typeof console,classifyRE=/(?:^|[-_])(\w)/g,classify=function(e){return e.replace(classifyRE,function(e){return e.toUpperCase()}).replace(/[-_]/g,"")};warn=function(e,t){hasConsole&&!config.silent&&console.error("[Vue warn]: "+e+" "+(t?formatLocation(formatComponentName(t)):""))},tip=function(e,t){hasConsole&&!config.silent&&console.warn("[Vue tip]: "+e+" "+(t?formatLocation(formatComponentName(t)):""))},formatComponentName=function(e,t){if(e.$root===e)return"<Root>";var n=e._isVue?e.$options.name||e.$options._componentTag:e.name,r=e._isVue&&e.$options.__file;if(!n&&r){var o=r.match(/([^\/\\]+)\.vue$/);n=o&&o[1]}return(n?"<"+classify(n)+">":"<Anonymous>")+(r&&t!==!1?" at "+r:"")};var formatLocation=function(e){return"<Anonymous>"===e&&(e+=' - use the "name" option for better debugging messages.'),"\n(found in "+e+")"}}var uid$1=0,Dep=function(){this.id=uid$1++,this.subs=[]};Dep.prototype.addSub=function(e){this.subs.push(e)},Dep.prototype.removeSub=function(e){remove(this.subs,e)},Dep.prototype.depend=function(){Dep.target&&Dep.target.addDep(this)},Dep.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;t<n;t++)e[t].update()},Dep.target=null;var targetStack=[],arrayProto=Array.prototype,arrayMethods=Object.create(arrayProto);["push","pop","shift","unshift","splice","sort","reverse"].forEach(function(e){var t=arrayProto[e];def(arrayMethods,e,function(){for(var n=arguments,r=arguments.length,o=new Array(r);r--;)o[r]=n[r];var i,a=t.apply(this,o),s=this.__ob__;switch(e){case"push":i=o;break;case"unshift":i=o;break;case"splice":i=o.slice(2)}return i&&s.observeArray(i),s.dep.notify(),a})});var arrayKeys=Object.getOwnPropertyNames(arrayMethods),observerState={shouldConvert:!0,isSettingProps:!1},Observer=function(e){if(this.value=e,this.dep=new Dep,this.vmCount=0,def(e,"__ob__",this),Array.isArray(e)){var t=hasProto?protoAugment:copyAugment;t(e,arrayMethods,arrayKeys),this.observeArray(e)}else this.walk(e)};Observer.prototype.walk=function(e){for(var t=Object.keys(e),n=0;n<t.length;n++)defineReactive$$1(e,t[n],e[t[n]])},Observer.prototype.observeArray=function(e){for(var t=0,n=e.length;t<n;t++)observe(e[t])};var strats=config.optionMergeStrategies;"production"!==process.env.NODE_ENV&&(strats.el=strats.propsData=function(e,t,n,r){return n||warn('option "'+r+'" can only be used during instance creation with the `new` keyword.'),defaultStrat(e,t)}),strats.data=function(e,t,n){return n?e||t?function(){var r="function"==typeof t?t.call(n):t,o="function"==typeof e?e.call(n):void 0;return r?mergeData(r,o):o}:void 0:t?"function"!=typeof t?("production"!==process.env.NODE_ENV&&warn('The "data" option should be a function that returns a per-instance value in component definitions.',n),e):e?function(){return mergeData(t.call(this),e.call(this))}:t:e},config._lifecycleHooks.forEach(function(e){strats[e]=mergeHook}),config._assetTypes.forEach(function(e){strats[e+"s"]=mergeAssets}),strats.watch=function(e,t){if(!t)return Object.create(e||null);if(!e)return t;var n={};extend(n,e);for(var r in t){var o=n[r],i=t[r];o&&!Array.isArray(o)&&(o=[o]),n[r]=o?o.concat(i):[i]}return n},strats.props=strats.methods=strats.computed=function(e,t){if(!t)return Object.create(e||null);if(!e)return t;var n=Object.create(null);return extend(n,e),extend(n,t),n};var defaultStrat=function(e,t){return void 0===t?e:t},util=Object.freeze({defineReactive:defineReactive$$1,_toString:_toString,toNumber:toNumber,makeMap:makeMap,isBuiltInTag:isBuiltInTag,remove:remove,hasOwn:hasOwn,isPrimitive:isPrimitive,cached:cached,camelize:camelize,capitalize:capitalize,hyphenate:hyphenate,bind:bind,toArray:toArray,extend:extend,isObject:isObject,isPlainObject:isPlainObject,toObject:toObject,noop:noop,no:no,identity:identity,genStaticKeys:genStaticKeys,looseEqual:looseEqual,looseIndexOf:looseIndexOf,once:once,emptyObject:emptyObject,isReserved:isReserved,def:def,parsePath:parsePath,hasProto:hasProto,inBrowser:inBrowser,UA:UA,isIE:isIE,isIE9:isIE9,isEdge:isEdge,isAndroid:isAndroid,isIOS:isIOS,isChrome:isChrome,isServerRendering:isServerRendering,devtools:devtools,nextTick:nextTick,get _Set(){return _Set},mergeOptions:mergeOptions,resolveAsset:resolveAsset,get warn(){return warn},get tip(){return tip},get formatComponentName(){return formatComponentName},validateProp:validateProp,handleError:handleError}),initProxy;if("production"!==process.env.NODE_ENV){var allowedGlobals=makeMap("Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,require"),warnNonPresent=function(e,t){warn('Property or method "'+t+'" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.',e)},hasProxy="undefined"!=typeof Proxy&&Proxy.toString().match(/native code/);if(hasProxy){var isBuiltInModifier=makeMap("stop,prevent,self,ctrl,shift,alt,meta");config.keyCodes=new Proxy(config.keyCodes,{set:function(e,t,n){return isBuiltInModifier(t)?(warn("Avoid overwriting built-in modifier in config.keyCodes: ."+t),!1):(e[t]=n,!0)}})}var hasHandler={has:function e(t,n){var e=n in t,r=allowedGlobals(n)||"_"===n.charAt(0);return e||r||warnNonPresent(t,n),e||!r}},getHandler={get:function(e,t){return"string"!=typeof t||t in e||warnNonPresent(e,t),e[t]}};initProxy=function(e){if(hasProxy){var t=e.$options,n=t.render&&t.render._withStripped?getHandler:hasHandler;e._renderProxy=new Proxy(e,n)}else e._renderProxy=e}}var VNode=function(e,t,n,r,o,i,a){this.tag=e,this.data=t,this.children=n,this.text=r,this.elm=o,this.ns=void 0,this.context=i,this.functionalContext=void 0,this.key=t&&t.key,this.componentOptions=a,this.componentInstance=void 0,this.parent=void 0,this.raw=!1,this.isStatic=!1,this.isRootInsert=!0,this.isComment=!1,this.isCloned=!1,this.isOnce=!1},prototypeAccessors={child:{}};prototypeAccessors.child.get=function(){return this.componentInstance},Object.defineProperties(VNode.prototype,prototypeAccessors);var createEmptyVNode=function(){var e=new VNode;return e.text="",e.isComment=!0,e},normalizeEvent=cached(function(e){var t="~"===e.charAt(0);e=t?e.slice(1):e;var n="!"===e.charAt(0);return e=n?e.slice(1):e,{name:e,once:t,capture:n}}),target,activeInstance=null,queue=[],has={},circular={},waiting=!1,flushing=!1,index=0,uid$2=0,Watcher=function(e,t,n,r){this.vm=e,e._watchers.push(this),r?(this.deep=!!r.deep,this.user=!!r.user,this.lazy=!!r.lazy,this.sync=!!r.sync):this.deep=this.user=this.lazy=this.sync=!1,this.cb=n,this.id=++uid$2,this.active=!0,this.dirty=this.lazy,this.deps=[],this.newDeps=[],this.depIds=new _Set,this.newDepIds=new _Set,this.expression="production"!==process.env.NODE_ENV?t.toString():"","function"==typeof t?this.getter=t:(this.getter=parsePath(t),this.getter||(this.getter=function(){},"production"!==process.env.NODE_ENV&&warn('Failed watching path: "'+t+'" Watcher only accepts simple dot-delimited paths. For full control, use a function instead.',e))),this.value=this.lazy?void 0:this.get()};Watcher.prototype.get=function(){pushTarget(this);var e,t=this.vm;if(this.user)try{e=this.getter.call(t,t)}catch(e){handleError(e,t,'getter for watcher "'+this.expression+'"')}else e=this.getter.call(t,t);return this.deep&&traverse(e),popTarget(),this.cleanupDeps(),e},Watcher.prototype.addDep=function(e){var t=e.id;this.newDepIds.has(t)||(this.newDepIds.add(t),this.newDeps.push(e),this.depIds.has(t)||e.addSub(this))},Watcher.prototype.cleanupDeps=function(){for(var e=this,t=this.deps.length;t--;){var n=e.deps[t];e.newDepIds.has(n.id)||n.removeSub(e)}var r=this.depIds;this.depIds=this.newDepIds,this.newDepIds=r,this.newDepIds.clear(),r=this.deps,this.deps=this.newDeps,this.newDeps=r,this.newDeps.length=0},Watcher.prototype.update=function(){this.lazy?this.dirty=!0:this.sync?this.run():queueWatcher(this)},Watcher.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||isObject(e)||this.deep){var t=this.value;if(this.value=e,this.user)try{this.cb.call(this.vm,e,t)}catch(e){handleError(e,this.vm,'callback for watcher "'+this.expression+'"')}else this.cb.call(this.vm,e,t)}}},Watcher.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},Watcher.prototype.depend=function(){for(var e=this,t=this.deps.length;t--;)e.deps[t].depend()},Watcher.prototype.teardown=function(){var e=this;if(this.active){this.vm._isBeingDestroyed||remove(this.vm._watchers,this);for(var t=this.deps.length;t--;)e.deps[t].removeSub(e);this.active=!1}};var seenObjects=new _Set,sharedPropertyDefinition={enumerable:!0,configurable:!0,get:noop,set:noop},isReservedProp={key:1,ref:1,slot:1},computedWatcherOptions={lazy:!0},hooks={init:init,prepatch:prepatch,insert:insert,destroy:destroy},hooksToMerge=Object.keys(hooks),SIMPLE_NORMALIZE=1,ALWAYS_NORMALIZE=2,uid=0;initMixin(Vue$3),stateMixin(Vue$3),eventsMixin(Vue$3),lifecycleMixin(Vue$3),renderMixin(Vue$3);var patternTypes=[String,RegExp],KeepAlive={name:"keep-alive",abstract:!0,props:{include:patternTypes,exclude:patternTypes},created:function(){this.cache=Object.create(null)},destroyed:function(){var e=this;for(var t in e.cache)pruneCacheEntry(e.cache[t])},watch:{include:function(e){pruneCache(this.cache,function(t){return matches(e,t)})},exclude:function(e){pruneCache(this.cache,function(t){return!matches(e,t)})}},render:function(){var e=getFirstComponentChild(this.$slots.default),t=e&&e.componentOptions;if(t){var n=getComponentName(t);if(n&&(this.include&&!matches(this.include,n)||this.exclude&&matches(this.exclude,n)))return e;var r=null==e.key?t.Ctor.cid+(t.tag?"::"+t.tag:""):e.key;this.cache[r]?e.componentInstance=this.cache[r].componentInstance:this.cache[r]=e,e.data.keepAlive=!0}return e}},builtInComponents={KeepAlive:KeepAlive};initGlobalAPI(Vue$3),Object.defineProperty(Vue$3.prototype,"$isServer",{get:isServerRendering}),Vue$3.version="2.2.0-beta.2";var acceptValue=makeMap("input,textarea,option,select"),mustUseProp=function(e,t,n){return"value"===n&&acceptValue(e)&&"button"!==t||"selected"===n&&"option"===e||"checked"===n&&"input"===e||"muted"===n&&"video"===e},isEnumeratedAttr=makeMap("contenteditable,draggable,spellcheck"),isBooleanAttr=makeMap("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),xlinkNS="http://www.w3.org/1999/xlink",isXlink=function(e){ return":"===e.charAt(5)&&"xlink"===e.slice(0,5)},getXlinkProp=function(e){return isXlink(e)?e.slice(6,e.length):""},isFalsyAttrValue=function(e){return null==e||e===!1},namespaceMap={svg:"http://www.w3.org/2000/svg",math:"http://www.w3.org/1998/Math/MathML"},isHTMLTag=makeMap("html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template"),isSVG=makeMap("svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view",!0),isPreTag=function(e){return"pre"===e},isReservedTag=function(e){return isHTMLTag(e)||isSVG(e)},unknownElementCache=Object.create(null),nodeOps=Object.freeze({createElement:createElement$1,createElementNS:createElementNS,createTextNode:createTextNode,createComment:createComment,insertBefore:insertBefore,removeChild:removeChild,appendChild:appendChild,parentNode:parentNode,nextSibling:nextSibling,tagName:tagName,setTextContent:setTextContent,setAttribute:setAttribute}),ref={create:function(e,t){registerRef(t)},update:function(e,t){e.data.ref!==t.data.ref&&(registerRef(e,!0),registerRef(t))},destroy:function(e){registerRef(e,!0)}},emptyNode=new VNode("",{},[]),hooks$1=["create","activate","update","remove","destroy"],directives={create:updateDirectives,update:updateDirectives,destroy:function(e){updateDirectives(e,emptyNode)}},emptyModifiers=Object.create(null),baseModules=[ref,directives],attrs={create:updateAttrs,update:updateAttrs},klass={create:updateClass,update:updateClass},validDivisionCharRE=/[\w).+\-_$\]]/,len,str,chr,index$1,expressionPos,expressionEndPos,warn$1,RANGE_TOKEN="__r",CHECKBOX_RADIO_TOKEN="__c",target$1,events={create:updateDOMListeners,update:updateDOMListeners},domProps={create:updateDOMProps,update:updateDOMProps},parseStyleText=cached(function(e){var t={},n=/;(?![^(]*\))/g,r=/:(.+)/;return e.split(n).forEach(function(e){if(e){var n=e.split(r);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}),cssVarRE=/^--/,importantRE=/\s*!important$/,setProp=function(e,t,n){cssVarRE.test(t)?e.style.setProperty(t,n):importantRE.test(n)?e.style.setProperty(t,n.replace(importantRE,""),"important"):e.style[normalize(t)]=n},prefixes=["Webkit","Moz","ms"],testEl,normalize=cached(function(e){if(testEl=testEl||document.createElement("div"),e=camelize(e),"filter"!==e&&e in testEl.style)return e;for(var t=e.charAt(0).toUpperCase()+e.slice(1),n=0;n<prefixes.length;n++){var r=prefixes[n]+t;if(r in testEl.style)return r}}),style={create:updateStyle,update:updateStyle},autoCssTransition=cached(function(e){return{enterClass:e+"-enter",enterToClass:e+"-enter-to",enterActiveClass:e+"-enter-active",leaveClass:e+"-leave",leaveToClass:e+"-leave-to",leaveActiveClass:e+"-leave-active"}}),hasTransition=inBrowser&&!isIE9,TRANSITION="transition",ANIMATION="animation",transitionProp="transition",transitionEndEvent="transitionend",animationProp="animation",animationEndEvent="animationend";hasTransition&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(transitionProp="WebkitTransition",transitionEndEvent="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(animationProp="WebkitAnimation",animationEndEvent="webkitAnimationEnd"));var raf=inBrowser&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout,transformRE=/\b(transform|all)(,|$)/,transition=inBrowser?{create:_enter,activate:_enter,remove:function(e,t){e.data.show?t():leave(e,t)}}:{},platformModules=[attrs,klass,events,domProps,style,transition],modules=platformModules.concat(baseModules),patch=createPatchFunction({nodeOps:nodeOps,modules:modules});isIE9&&document.addEventListener("selectionchange",function(){var e=document.activeElement;e&&e.vmodel&&trigger(e,"input")});var model$1={inserted:function(e,t,n){if("select"===n.tag){var r=function(){setSelected(e,t,n.context)};r(),(isIE||isEdge)&&setTimeout(r,0)}else"textarea"!==n.tag&&"text"!==e.type||(e._vModifiers=t.modifiers,t.modifiers.lazy||(isAndroid||(e.addEventListener("compositionstart",onCompositionStart),e.addEventListener("compositionend",onCompositionEnd)),isIE9&&(e.vmodel=!0)))},componentUpdated:function(e,t,n){if("select"===n.tag){setSelected(e,t,n.context);var r=e.multiple?t.value.some(function(t){return hasNoMatchingOption(t,e.options)}):t.value!==t.oldValue&&hasNoMatchingOption(t.value,e.options);r&&trigger(e,"change")}}},show={bind:function(e,t,n){var r=t.value;n=locateNode(n);var o=n.data&&n.data.transition,i=e.__vOriginalDisplay="none"===e.style.display?"":e.style.display;r&&o&&!isIE9?(n.data.show=!0,enter(n,function(){e.style.display=i})):e.style.display=r?i:"none"},update:function(e,t,n){var r=t.value,o=t.oldValue;if(r!==o){n=locateNode(n);var i=n.data&&n.data.transition;i&&!isIE9?(n.data.show=!0,r?enter(n,function(){e.style.display=e.__vOriginalDisplay}):leave(n,function(){e.style.display="none"})):e.style.display=r?e.__vOriginalDisplay:"none"}},unbind:function(e,t,n,r,o){o||(e.style.display=e.__vOriginalDisplay)}},platformDirectives={model:model$1,show:show},transitionProps={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,Object]},Transition={name:"transition",props:transitionProps,abstract:!0,render:function(e){var t=this,n=this.$slots.default;if(n&&(n=n.filter(function(e){return e.tag}),n.length)){"production"!==process.env.NODE_ENV&&n.length>1&&warn("<transition> can only be used on a single element. Use <transition-group> for lists.",this.$parent);var r=this.mode;"production"!==process.env.NODE_ENV&&r&&"in-out"!==r&&"out-in"!==r&&warn("invalid <transition> mode: "+r,this.$parent);var o=n[0];if(hasParentTransition(this.$vnode))return o;var i=getRealChild(o);if(!i)return o;if(this._leaving)return placeholder(e,o);var a="__transition-"+this._uid+"-";i.key=null==i.key?a+i.tag:isPrimitive(i.key)?0===String(i.key).indexOf(a)?i.key:a+i.key:i.key;var s=(i.data||(i.data={})).transition=extractTransitionData(this),c=this._vnode,l=getRealChild(c);if(i.data.directives&&i.data.directives.some(function(e){return"show"===e.name})&&(i.data.show=!0),l&&l.data&&!isSameChild(i,l)){var d=l&&(l.data.transition=extend({},s));if("out-in"===r)return this._leaving=!0,mergeVNodeHook(d,"afterLeave",function(){t._leaving=!1,t.$forceUpdate()}),placeholder(e,o);if("in-out"===r){var u,p=function(){u()};mergeVNodeHook(s,"afterEnter",p),mergeVNodeHook(s,"enterCancelled",p),mergeVNodeHook(d,"delayLeave",function(e){u=e})}}return o}}},props=extend({tag:String,moveClass:String},transitionProps);delete props.mode;var TransitionGroup={props:props,render:function(e){for(var t=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,o=this.$slots.default||[],i=this.children=[],a=extractTransitionData(this),s=0;s<o.length;s++){var c=o[s];if(c.tag)if(null!=c.key&&0!==String(c.key).indexOf("__vlist"))i.push(c),n[c.key]=c,(c.data||(c.data={})).transition=a;else if("production"!==process.env.NODE_ENV){var l=c.componentOptions,d=l?l.Ctor.options.name||l.tag||"":c.tag;warn("<transition-group> children must be keyed: <"+d+">")}}if(r){for(var u=[],p=[],f=0;f<r.length;f++){var v=r[f];v.data.transition=a,v.data.pos=v.elm.getBoundingClientRect(),n[v.key]?u.push(v):p.push(v)}this.kept=e(t,null,u),this.removed=p}return e(t,null,i)},beforeUpdate:function(){this.__patch__(this._vnode,this.kept,!1,!0),this._vnode=this.kept},updated:function(){var e=this.prevChildren,t=this.moveClass||(this.name||"v")+"-move";if(e.length&&this.hasMove(e[0].elm,t)){e.forEach(callPendingCbs),e.forEach(recordPosition),e.forEach(applyTranslation);var n=document.body;n.offsetHeight;e.forEach(function(e){if(e.data.moved){var n=e.elm,r=n.style;addTransitionClass(n,t),r.transform=r.WebkitTransform=r.transitionDuration="",n.addEventListener(transitionEndEvent,n._moveCb=function e(r){r&&!/transform$/.test(r.propertyName)||(n.removeEventListener(transitionEndEvent,e),n._moveCb=null,removeTransitionClass(n,t))})}})}},methods:{hasMove:function(e,t){if(!hasTransition)return!1;if(null!=this._hasMove)return this._hasMove;var n=e.cloneNode();e._transitionClasses&&e._transitionClasses.forEach(function(e){removeClass(n,e)}),addClass(n,t),n.style.display="none",this.$el.appendChild(n);var r=getTransitionInfo(n);return this.$el.removeChild(n),this._hasMove=r.hasTransform}}},platformComponents={Transition:Transition,TransitionGroup:TransitionGroup};Vue$3.config.mustUseProp=mustUseProp,Vue$3.config.isReservedTag=isReservedTag,Vue$3.config.getTagNamespace=getTagNamespace,Vue$3.config.isUnknownElement=isUnknownElement,extend(Vue$3.options.directives,platformDirectives),extend(Vue$3.options.components,platformComponents),Vue$3.prototype.__patch__=inBrowser?patch:noop,Vue$3.prototype.$mount=function(e,t){return e=e&&inBrowser?query(e):void 0,mountComponent(this,e,t)},setTimeout(function(){config.devtools&&(devtools?devtools.emit("init",Vue$3):"production"!==process.env.NODE_ENV&&isChrome&&console[console.info?"info":"log"]("Download the Vue Devtools extension for a better development experience:\nhttps://github.com/vuejs/vue-devtools")),"production"!==process.env.NODE_ENV&&config.productionTip!==!1&&inBrowser&&"undefined"!=typeof console&&console[console.info?"info":"log"]("You are running Vue in development mode.\nMake sure to turn on production mode when deploying for production.\nSee more tips at https://vuejs.org/guide/deployment.html")},0);var shouldDecodeNewlines=!!inBrowser&&shouldDecode("\n","&#10;"),isUnaryTag=makeMap("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr",!0),canBeLeftOpenTag=makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source",!0),isNonPhrasingTag=makeMap("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track",!0),decoder,singleAttrIdentifier=/([^\s"'<>\/=]+)/,singleAttrAssign=/(?:=)/,singleAttrValues=[/"([^"]*)"+/.source,/'([^']*)'+/.source,/([^\s"'=<>`]+)/.source],attribute=new RegExp("^\\s*"+singleAttrIdentifier.source+"(?:\\s*("+singleAttrAssign.source+")\\s*(?:"+singleAttrValues.join("|")+"))?"),ncname="[a-zA-Z_][\\w\\-\\.]*",qnameCapture="((?:"+ncname+"\\:)?"+ncname+")",startTagOpen=new RegExp("^<"+qnameCapture),startTagClose=/^\s*(\/?)>/,endTag=new RegExp("^<\\/"+qnameCapture+"[^>]*>"),doctype=/^<!DOCTYPE [^>]+>/i,comment=/^<!--/,conditionalComment=/^<!\[/,IS_REGEX_CAPTURING_BROKEN=!1;"x".replace(/x(.)?/g,function(e,t){IS_REGEX_CAPTURING_BROKEN=""===t});var isScriptOrStyle=makeMap("script,style",!0),reCache={},decodingMap={"&lt;":"<","&gt;":">","&quot;":'"',"&amp;":"&","&#10;":"\n"},encodedAttr=/&(?:lt|gt|quot|amp);/g,encodedAttrWithNewLines=/&(?:lt|gt|quot|amp|#10);/g,defaultTagRE=/\{\{((?:.|\n)+?)\}\}/g,regexEscapeRE=/[-.*+?^${}()|[\]\/\\]/g,buildRegex=cached(function(e){var t=e[0].replace(regexEscapeRE,"\\$&"),n=e[1].replace(regexEscapeRE,"\\$&");return new RegExp(t+"((?:.|\\n)+?)"+n,"g")}),dirRE=/^v-|^@|^:/,forAliasRE=/(.*?)\s+(?:in|of)\s+(.*)/,forIteratorRE=/\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/,bindRE=/^:|^v-bind:/,onRE=/^@|^v-on:/,argRE=/:(.*)$/,modifierRE=/\.[^.]+/g,decodeHTMLCached=cached(decode),warn$2,platformGetTagNamespace,platformMustUseProp,platformIsPreTag,preTransforms,transforms,postTransforms,delimiters,ieNSBug=/^xmlns:NS\d+/,ieNSPrefix=/^NS\d+:/,isStaticKey,isPlatformReservedTag,genStaticKeysCached=cached(genStaticKeys$1),fnExpRE=/^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/,simplePathRE=/^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/,keyCodes={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},genGuard=function(e){return"if("+e+")return null;"},modifierCode={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:genGuard("$event.target !== $event.currentTarget"),ctrl:genGuard("!$event.ctrlKey"),shift:genGuard("!$event.shiftKey"),alt:genGuard("!$event.altKey"),meta:genGuard("!$event.metaKey"),left:genGuard("$event.button !== 0"),middle:genGuard("$event.button !== 1"),right:genGuard("$event.button !== 2")},baseDirectives={bind:bind$1,cloak:noop},warn$3,transforms$1,dataGenFns,platformDirectives$1,isPlatformReservedTag$1,staticRenderFns,onceCount,currentOptions,prohibitedKeywordRE=new RegExp("\\b"+"do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,super,throw,while,yield,delete,export,import,return,switch,default,extends,finally,continue,debugger,function,arguments".split(",").join("\\b|\\b")+"\\b"),identRE=/[A-Za-z_$][\w$]*/,stripStringRE=/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g,klass$1={staticKeys:["staticClass"],transformNode:transformNode,genData:genData$1},style$1={staticKeys:["staticStyle"],transformNode:transformNode$1,genData:genData$2},modules$1=[klass$1,style$1],directives$1={model:model,text:text,html:html},baseOptions={expectHTML:!0,modules:modules$1,directives:directives$1,isPreTag:isPreTag,isUnaryTag:isUnaryTag,mustUseProp:mustUseProp,isReservedTag:isReservedTag,getTagNamespace:getTagNamespace,staticKeys:genStaticKeys(modules$1)},ref$1=createCompiler(baseOptions),compileToFunctions=ref$1.compileToFunctions,idToTemplate=cached(function(e){var t=query(e);return t&&t.innerHTML}),mount=Vue$3.prototype.$mount;Vue$3.prototype.$mount=function(e,t){if(e=e&&query(e),e===document.body||e===document.documentElement)return"production"!==process.env.NODE_ENV&&warn("Do not mount Vue to <html> or <body> - mount to normal elements instead."),this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=idToTemplate(r),"production"===process.env.NODE_ENV||r||warn("Template element not found or is empty: "+n.template,this));else{if(!r.nodeType)return"production"!==process.env.NODE_ENV&&warn("invalid template option:"+r,this),this;r=r.innerHTML}else e&&(r=getOuterHTML(e));if(r){"production"!==process.env.NODE_ENV&&config.performance&&perf&&perf.mark("compile");var o=compileToFunctions(r,{shouldDecodeNewlines:shouldDecodeNewlines,delimiters:n.delimiters},this),i=o.render,a=o.staticRenderFns;n.render=i,n.staticRenderFns=a,"production"!==process.env.NODE_ENV&&config.performance&&perf&&(perf.mark("compile end"),perf.measure(this._name+" compile","compile","compile end"))}}return mount.call(this,e,t)},Vue$3.compile=compileToFunctions,module.exports=Vue$3; //# sourceMappingURL=vue.common.min.js.map
MobileApp/node_modules/react-native-elements/src/grid/Row.js
VowelWeb/CoinTradePros.com
import PropTypes from 'prop-types'; import React from 'react'; import { View, StyleSheet, TouchableOpacity } from 'react-native'; const Row = props => { const { containerStyle, size, onPress, activeOpacity } = props; const styles = StyleSheet.create({ container: { flex: size ? size : containerStyle && containerStyle.height ? 0 : 1, flexDirection: 'row', }, }); if (onPress) { return ( <TouchableOpacity style={[styles.container, containerStyle && containerStyle]} activeOpacity={activeOpacity} onPress={onPress} > <View {...props}> {props.children} </View> </TouchableOpacity> ); } return ( <View style={[styles.container, containerStyle && containerStyle]} {...props} > {props.children} </View> ); }; Row.propTypes = { size: PropTypes.number, containerStyle: PropTypes.any, onPress: PropTypes.func, activeOpacity: PropTypes.number, children: PropTypes.any, }; Row.defaultProps = { activeOpacity: 1, }; export default Row;
test/PaginationSpec.js
Cellule/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Pagination from '../src/Pagination'; describe('Pagination', function () { it('Should have class', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination>Item content</Pagination> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'pagination')); }); it('Should show the correct active button', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} activePage={3} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons.length, 5); React.findDOMNode(pageButtons[2]).className.should.match(/\bactive\b/); }); it('Should call onSelect when page button is selected', function (done) { function onSelect(event, selectedEvent) { assert.equal(selectedEvent.eventKey, 2); done(); } let instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} onSelect={onSelect} /> ); ReactTestUtils.Simulate.click( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a')[1] ); }); it('Should only show part of buttons and active button in the middle of buttons when given maxButtons', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination items={30} activePage={10} maxButtons={9} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // 9 visible page buttons and 1 ellipsis button assert.equal(pageButtons.length, 10); // active button is the second one assert.equal(React.findDOMNode(pageButtons[0]).firstChild.innerText, '6'); React.findDOMNode(pageButtons[4]).className.should.match(/\bactive\b/); }); it('Should show the ellipsis, first, last, prev and next button', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination first={true} last={true} prev={true} next={true} maxButtons={3} activePage={10} items={20} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // add first, last, prev, next and ellipsis button assert.equal(pageButtons.length, 8); assert.equal(React.findDOMNode(pageButtons[0]).innerText, '«'); assert.equal(React.findDOMNode(pageButtons[1]).innerText, '‹'); assert.equal(React.findDOMNode(pageButtons[5]).innerText, '...'); assert.equal(React.findDOMNode(pageButtons[6]).innerText, '›'); assert.equal(React.findDOMNode(pageButtons[7]).innerText, '»'); }); });
src/icons/LocalAirportIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class LocalAirportIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M42 32v-4L26 18V7c0-1.66-1.34-3-3-3s-3 1.34-3 3v11L4 28v4l16-5v11l-4 3v3l7-2 7 2v-3l-4-3V27l16 5z"/></svg>;} };
src/icons/favorite_icon.js
camboio/ibis
import React from 'react'; export default function FavoriteIcon(props){ return( <svg className={props.className} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 294.9 254.5"> <path className="st0" d="M140.9 244.8l-97.3-93.9C42.3 149.8 8 118.4 8 81 8 35.3 35.9 8 82.6 8c27.3 0 52.9 21.5 65.2 33.7C160.1 29.5 185.7 8 212.9 8c46.6 0 74.6 27.3 74.6 73 0 37.4-34.3 68.8-35.7 70.2l-97.2 93.6c-1.9 1.9-4.4 2.8-6.9 2.8-2.4 0-4.9-1-6.8-2.8z"/> </svg> ); }
ajax/libs/highstock/4.2.7/highstock.src.js
jonobr1/cdnjs
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highstock JS v4.2.7 (2016-09-21) * * (c) 2009-2016 Torstein Honsi * * License: www.highcharts.com/license */ (function (root, factory) { if (typeof module === 'object' && module.exports) { module.exports = root.document ? factory(root) : factory; } else { root.Highcharts = factory(root); } }(typeof window !== 'undefined' ? window : this, function (win) { // eslint-disable-line no-undef // encapsulated variables var UNDEFINED, doc = win.document, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = (win.navigator && win.navigator.userAgent) || '', isOpera = win.opera, isMS = /(msie|trident|edge)/i.test(userAgent) && !isOpera, docMode8 = doc && doc.documentMode === 8, isWebKit = !isMS && /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = doc && doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = doc && !hasSVG && !isMS && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function pathAnim, timeUnits, noop = function () {}, charts = [], chartCount = 0, PRODUCT = 'Highstock', VERSION = '4.2.7', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /[0-9]/g, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'], // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getTimezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMilliseconds, setSeconds, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; /** * Provide error messages for debugging, with links to online explanation */ function error(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw new Error(msg); } // else ... if (win.console) { console.log(msg); // eslint-disable-line no-console } } // The Highcharts namespace Highcharts = win.Highcharts ? error(16, true) : { win: win }; Highcharts.seriesTypes = seriesTypes; var timers = [], getStyle, // Previous adapter functions inArray, each, grep, offset, map, addEvent, removeEvent, fireEvent, animate, stop; /** * An animator object. One instance applies to one property (attribute or style prop) * on one element. * * @param {object} elem The element to animate. May be a DOM element or a Highcharts SVGElement wrapper. * @param {object} options Animation options, including duration, easing, step and complete. * @param {object} prop The property to animate. */ function Fx(elem, options, prop) { this.options = options; this.elem = elem; this.prop = prop; } Fx.prototype = { /** * Animating a path definition on SVGElement * @returns {undefined} */ dSetter: function () { var start = this.paths[0], end = this.paths[1], ret = [], now = this.now, i = start.length, startVal; if (now === 1) { // land on the final path without adjustment points appended in the ends ret = this.toD; } else if (i === end.length && now < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : now * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } this.elem.attr('d', ret); }, /** * Update the element with the current animation step * @returns {undefined} */ update: function () { var elem = this.elem, prop = this.prop, // if destroyed, it is null now = this.now, step = this.options.step; // Animation setter defined from outside if (this[prop + 'Setter']) { this[prop + 'Setter'](); // Other animations on SVGElement } else if (elem.attr) { if (elem.element) { elem.attr(prop, now); } // HTML styles, raw HTML content like container size } else { elem.style[prop] = now + this.unit; } if (step) { step.call(elem, now, this); } }, /** * Run an animation */ run: function (from, to, unit) { var self = this, timer = function (gotoEnd) { return timer.stopped ? false : self.step(gotoEnd); }, i; this.startTime = +new Date(); this.start = from; this.end = to; this.unit = unit; this.now = this.start; this.pos = 0; timer.elem = this.elem; if (timer() && timers.push(timer) === 1) { timer.timerId = setInterval(function () { for (i = 0; i < timers.length; i++) { if (!timers[i]()) { timers.splice(i--, 1); } } if (!timers.length) { clearInterval(timer.timerId); } }, 13); } }, /** * Run a single step in the animation * @param {Boolean} gotoEnd Whether to go to then endpoint of the animation after abort * @returns {Boolean} True if animation continues */ step: function (gotoEnd) { var t = +new Date(), ret, done, options = this.options, elem = this.elem, complete = options.complete, duration = options.duration, curAnim = options.curAnim, i; if (elem.attr && !elem.element) { // #2616, element including flag is destroyed ret = false; } else if (gotoEnd || t >= duration + this.startTime) { this.now = this.end; this.pos = 1; this.update(); curAnim[this.prop] = true; done = true; for (i in curAnim) { if (curAnim[i] !== true) { done = false; } } if (done && complete) { complete.call(elem); } ret = false; } else { this.pos = options.easing((t - this.startTime) / duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); ret = true; } return ret; }, /** * Prepare start and end values so that the path can be animated one to one */ initPath: function (elem, fromD, toD) { fromD = fromD || ''; var shift, startX = elem.startX, endX = elem.endX, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, fullLength, slice, i, start = fromD.split(' '), end = toD.slice(), // copy isArea = elem.isArea, positionFactor = isArea ? 2 : 1, reverse; /** * In splines make move points have six parameters like bezier curves */ function sixify(arr) { i = arr.length; while (i--) { if (arr[i] === M || arr[i] === L) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } } /** * Insert an array at the given position of another array */ function insertSlice(arr, subArr, index) { [].splice.apply( arr, [index, 0].concat(subArr) ); } /** * If shifting points, prepend a dummy point to the end path. */ function prepend(arr, other) { while (arr.length < fullLength) { // Move to, line to or curve to? arr[0] = other[fullLength - arr.length]; // Prepend a copy of the first point insertSlice(arr, arr.slice(0, numParams), 0); // For areas, the bottom path goes back again to the left, so we need // to append a copy of the last point. if (isArea) { insertSlice(arr, arr.slice(arr.length - numParams), arr.length); i--; } } arr[0] = 'M'; } /** * Copy and append last point until the length matches the end length */ function append(arr, other) { var i = (fullLength - arr.length) / numParams; while (i > 0 && i--) { // Pull out the slice that is going to be appended or inserted. In a line graph, // the positionFactor is 1, and the last point is sliced out. In an area graph, // the positionFactor is 2, causing the middle two points to be sliced out, since // an area path starts at left, follows the upper path then turns and follows the // bottom back. slice = arr.slice().splice( (arr.length / positionFactor) - numParams, numParams * positionFactor ); // Move to, line to or curve to? slice[0] = other[fullLength - numParams - (i * numParams)]; // Disable first control point if (bezier) { slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } // Now insert the slice, either in the middle (for areas) or at the end (for lines) insertSlice(arr, slice, arr.length / positionFactor); if (isArea) { i--; } } } if (bezier) { sixify(start); sixify(end); } // For sideways animation, find out how much we need to shift to get the start path Xs // to match the end path Xs. if (startX && endX) { for (i = 0; i < startX.length; i++) { if (startX[i] === endX[0]) { // Moving left, new points coming in on right shift = i; break; } else if (startX[0] === endX[endX.length - startX.length + i]) { // Moving right shift = i; reverse = true; break; } } if (shift === undefined) { start = []; } } if (start.length && Highcharts.isNumber(shift)) { // The common target length for the start and end array, where both // arrays are padded in opposite ends fullLength = end.length + shift * positionFactor * numParams; if (!reverse) { prepend(end, start); append(start, end); } else { prepend(start, end); append(end, start); } } return [start, end]; } }; // End of Fx prototype /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ var extend = Highcharts.extend = function (a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; }; /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (Highcharts.isObject(value, true) && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { var str = Object.prototype.toString.call(obj); return str === '[object Array]' || str === '[object Array Iterator]'; } /** * Check for object * @param {Object} obj * @param {Boolean} strict Also checks that the object is not an array */ var isObject = Highcharts.isObject = function (obj, strict) { //debugger; return obj && typeof obj === 'object' && (!strict || !isArray(obj)); }; /** * Check for number * @param {Object} n */ var isNumber = Highcharts.isNumber = function isNumber(n) { return typeof n === 'number' && !isNaN(n); }; /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Set a timeout if the delay is given, otherwise perform the function synchronously * @param {Function} fn The function to perform * @param {Number} delay Delay in milliseconds * @param {Ojbect} context The context * @returns {Nubmer} An identifier for the timeout */ function syncTimeout(fn, delay, context) { if (delay) { return setTimeout(fn, delay, context); } fn.call(0, context); } /** * Return the first value that is defined. */ var pick = Highcharts.pick = function () { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== UNDEFINED && arg !== null) { return arg; } } }; /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isMS && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, { padding: 0, border: 'none', margin: 0 }); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(Parent, members) { var object = function () { }; object.prototype = new Parent(); extend(object.prototype, members); return object; } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length, padder) { return new Array((length || 2) + 1 - String(number).length).join(padder || 0) + number; } /** * Return a length based on either the integer value, or a percentage of a base. */ function relativeLength(value, base) { return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value); } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ var wrap = Highcharts.wrap = function (obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; }; function getTZOffset(timestamp) { return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return defaultOptions.lang.invalidDate || ''; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - getTZOffset(timestamp)), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, shortWeekdays = lang.shortWeekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': shortWeekdays ? shortWeekdays[day] : langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': pad(dayOfMonth, 2, ' '), // Day of the month, 1 through 31 'w': day, // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'k': hours, // Hours in 24h format, 0 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = Highcharts.numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) { var normalized, i, retInterval = interval; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { retInterval = multiples[i]; if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) { break; } } // multiply back to the correct magnitude retInterval *= magnitude; return retInterval; } /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].safeI = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.safeI - b.safeI : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].safeI; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num, prec) { return parseFloat( num.toPrecision(prec || 14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { chart.renderer.globalAnimation = pick(animation, chart.animation); } /** * Get the animation in object form, where a disabled animation is always * returned with duration: 0 */ function animObject(animation) { return isObject(animation) ? merge(animation) : { duration: animation ? 500 : 0 }; } /** * The time unit lookup */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 28 * 24 * 3600000, year: 364 * 24 * 3600000 }; /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decimalPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ Highcharts.numberFormat = function (number, decimals, decimalPoint, thousandsSep) { number = +number || 0; decimals = +decimals; var lang = defaultOptions.lang, origDec = (number.toString().split('.')[1] || '').length, decimalComponent, strinteger, thousands, absNumber = Math.abs(number), ret; if (decimals === -1) { decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793). } else if (!isNumber(decimals)) { decimals = 2; } // A string containing the positive integer component of the number strinteger = String(pInt(absNumber.toFixed(decimals))); // Leftover after grouping into thousands. Can be 0, 1 or 3. thousands = strinteger.length > 3 ? strinteger.length % 3 : 0; // Language decimalPoint = pick(decimalPoint, lang.decimalPoint); thousandsSep = pick(thousandsSep, lang.thousandsSep); // Start building the return ret = number < 0 ? '-' : ''; // Add the leftover after grouping into thousands. For example, in the number 42 000 000, // this line adds 42. ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : ''; // Add the remaining thousands groups, joined by the thousands separator ret += strinteger.substr(thousands).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep); // Add the decimal point and the decimal component if (decimals) { // Get the decimal component, and add power to avoid rounding errors with float numbers (#4573) decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1)); ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2); } return ret; }; /** * Easing definition * @param {Number} pos Current position, ranging from 0 to 1 */ Math.easeInOutSine = function (pos) { return -0.5 * (Math.cos(Math.PI * pos) - 1); }; /** * Internal method to return CSS value for given element and property */ getStyle = function (el, prop) { var style; // For width and height, return the actual inner pixel size (#4913) if (prop === 'width') { return Math.min(el.offsetWidth, el.scrollWidth) - getStyle(el, 'padding-left') - getStyle(el, 'padding-right'); } else if (prop === 'height') { return Math.min(el.offsetHeight, el.scrollHeight) - getStyle(el, 'padding-top') - getStyle(el, 'padding-bottom'); } // Otherwise, get the computed style style = win.getComputedStyle(el, undefined); return style && pInt(style.getPropertyValue(prop)); }; /** * Return the index of an item in an array, or -1 if not found */ inArray = function (item, arr) { return arr.indexOf ? arr.indexOf(item) : [].indexOf.call(arr, item); }; /** * Filter an array */ grep = function (elements, callback) { return [].filter.call(elements, callback); }; /** * Map an array */ map = function (arr, fn) { var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }; /** * Get the element's offset position, corrected by overflow:auto. */ offset = function (el) { var docElem = doc.documentElement, box = el.getBoundingClientRect(); return { top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) }; }; /** * Stop running animation. * A possible extension to this would be to stop a single property, when * we want to continue animating others. Then assign the prop to the timer * in the Fx.run method, and check for the prop here. This would be an improvement * in all cases where we stop the animation from .attr. Instead of stopping * everything, we can just stop the actual attributes we're setting. */ stop = function (el) { var i = timers.length; // Remove timers related to this element (#4519) while (i--) { if (timers[i].elem === el) { timers[i].stopped = true; // #4667 } } }; /** * Utility for iterating over an array. * @param {Array} arr * @param {Function} fn */ each = function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); }; /** * Add an event listener */ addEvent = function (el, type, fn) { var events = el.hcEvents = el.hcEvents || {}; function wrappedFn(e) { e.target = e.srcElement || win; // #2820 fn.call(el, e); } // Handle DOM events in modern browsers if (el.addEventListener) { el.addEventListener(type, fn, false); // Handle old IE implementation } else if (el.attachEvent) { if (!el.hcEventsIE) { el.hcEventsIE = {}; } // Link wrapped fn with original fn, so we can get this in removeEvent el.hcEventsIE[fn.toString()] = wrappedFn; el.attachEvent('on' + type, wrappedFn); } if (!events[type]) { events[type] = []; } events[type].push(fn); }; /** * Remove event added with addEvent */ removeEvent = function (el, type, fn) { var events, hcEvents = el.hcEvents, index; function removeOneEvent(type, fn) { if (el.removeEventListener) { el.removeEventListener(type, fn, false); } else if (el.attachEvent) { fn = el.hcEventsIE[fn.toString()]; el.detachEvent('on' + type, fn); } } function removeAllEvents() { var types, len, n; if (!el.nodeName) { return; // break on non-DOM events } if (type) { types = {}; types[type] = true; } else { types = hcEvents; } for (n in types) { if (hcEvents[n]) { len = hcEvents[n].length; while (len--) { removeOneEvent(n, hcEvents[n][len]); } } } } if (hcEvents) { if (type) { events = hcEvents[type] || []; if (fn) { index = inArray(fn, events); if (index > -1) { events.splice(index, 1); hcEvents[type] = events; } removeOneEvent(type, fn); } else { removeAllEvents(); hcEvents[type] = []; } } else { removeAllEvents(); el.hcEvents = {}; } } }; /** * Fire an event on a custom object */ fireEvent = function (el, type, eventArguments, defaultFunction) { var e, hcEvents = el.hcEvents, events, len, i, fn; eventArguments = eventArguments || {}; if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) { e = doc.createEvent('Events'); e.initEvent(type, true, true); e.target = el; extend(e, eventArguments); if (el.dispatchEvent) { el.dispatchEvent(e); } else { el.fireEvent(type, e); } } else if (hcEvents) { events = hcEvents[type] || []; len = events.length; // Attach a simple preventDefault function to skip default handler if called. // The built-in defaultPrevented property is not overwritable (#5112) if (!eventArguments.preventDefault) { eventArguments.preventDefault = function () { eventArguments.defaultPrevented = true; }; } eventArguments.target = el; // If the type is not set, we're running a custom event (#2297). If it is set, // we're running a browser event, and setting it will cause en error in // IE8 (#2465). if (!eventArguments.type) { eventArguments.type = type; } for (i = 0; i < len; i++) { fn = events[i]; // If the event handler return false, prevent the default handler from executing if (fn && fn.call(el, eventArguments) === false) { eventArguments.preventDefault(); } } } // Run the default if not prevented if (defaultFunction && !eventArguments.defaultPrevented) { defaultFunction(eventArguments); } }; /** * The global animate method, which uses Fx to create individual animators. */ animate = function (el, params, opt) { var start, unit = '', end, fx, args, prop; if (!isObject(opt)) { // Number or undefined/null args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (!isNumber(opt.duration)) { opt.duration = 400; } opt.easing = typeof opt.easing === 'function' ? opt.easing : (Math[opt.easing] || Math.easeInOutSine); opt.curAnim = merge(params); for (prop in params) { fx = new Fx(el, opt, prop); end = null; if (prop === 'd') { fx.paths = fx.initPath( el, el.d, params.d ); fx.toD = params.d; start = 0; end = 1; } else if (el.attr) { start = el.attr(prop); } else { start = parseFloat(getStyle(el, prop)) || 0; if (prop !== 'opacity') { unit = 'px'; } } if (!end) { end = params[prop]; } if (end.match && end.match('px')) { end = end.replace(/px/g, ''); // #4351 } fx.run(start, end, unit); } }; /** * Register Highcharts as a plugin in jQuery */ if (win.jQuery) { win.jQuery.fn.highcharts = function () { var args = [].slice.call(arguments); if (this[0]) { // this[0] is the renderTo div // Create the chart if (args[0]) { new Highcharts[ // eslint-disable-line no-new isString(args[0]) ? args.shift() : 'Chart' // Constructor defaults to Chart ](this[0], args[0], args[1]); return this; } // When called without parameters or with the return argument, return an existing chart return charts[attr(this[0], 'data-highcharts-chart')]; } }; } /** * Compatibility section to add support for legacy IE. This can be removed if old IE * support is not needed. */ if (doc && !doc.defaultView) { getStyle = function (el, prop) { var val, alias = { width: 'clientWidth', height: 'clientHeight' }[prop]; if (el.style[prop]) { return pInt(el.style[prop]); } if (prop === 'opacity') { prop = 'filter'; } // Getting the rendered width and height if (alias) { el.style.zoom = 1; return Math.max(el[alias] - 2 * getStyle(el, 'padding'), 0); } val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b) { return b.toUpperCase(); })]; if (prop === 'filter') { val = val.replace( /alpha\(opacity=([0-9]+)\)/, function (a, b) { return b / 100; } ); } return val === '' ? 1 : pInt(val); }; } if (!Array.prototype.forEach) { each = function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; } if (!Array.prototype.indexOf) { inArray = function (item, arr) { var len, i = 0; if (arr) { len = arr.length; for (; i < len; i++) { if (arr[i] === item) { return i; } } } return -1; }; } if (!Array.prototype.filter) { grep = function (elements, fn) { var ret = [], i = 0, length = elements.length; for (; i < length; i++) { if (fn(elements[i], i)) { ret.push(elements[i]); } } return ret; }; } //--- End compatibility section --- // Expose utilities Highcharts.Fx = Fx; Highcharts.inArray = inArray; Highcharts.each = each; Highcharts.grep = grep; Highcharts.offset = offset; Highcharts.map = map; Highcharts.addEvent = addEvent; Highcharts.removeEvent = removeEvent; Highcharts.fireEvent = fireEvent; Highcharts.animate = animate; Highcharts.animObject = animObject; Highcharts.stop = stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // invalidDate: '', decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ' ' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/stock/4.2.7/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' }, width: null, height: null }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', fontSize: '18px' }, widthAdjust: -44 }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' }, widthAdjust: -44 }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: { align: 'center', // defer: true, // enabled: false, formatter: function () { return this.y === null ? '' : Highcharts.numberFormat(this.y, -1); }, style: { color: 'contrast', fontSize: '11px', fontWeight: 'bold', textShadow: '0 0 6px contrast, 0 0 3px contrast' }, verticalAlign: 'bottom', // above singular point x: 0, y: 0, // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, padding: 5 // shadow: false }, cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series softThreshold: true, states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, footerFormat: '', //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', pointerEvents: 'none', // #1686 http://caniuse.com/#feat=pointer-events whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var globalOptions = defaultOptions.global, useUTC = globalOptions.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; Date = globalOptions.Date || win.Date; timezoneOffset = useUTC && globalOptions.timezoneOffset; getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset; makeTime = function (year, month, date, hours, minutes, seconds) { var d; if (useUTC) { d = Date.UTC.apply(0, arguments); d += getTZOffset(d); } else { d = new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); } return d; }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMilliseconds = SET + 'Milliseconds'; setSeconds = SET + 'Seconds'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ function Color(input) { // Backwards compatibility, allow instanciation without new if (!(this instanceof Color)) { return new Color(input); } // Initialize this.init(input); } Color.prototype = { // Collection of parsers. This can be extended from the outside by pushing parsers // to Highcharts.Colors.prototype.parsers. parsers: [{ // RGBA color regex: /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, parse: function (result) { return [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } }, { // HEX color regex: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, parse: function (result) { return [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } }, { // RGB color regex: /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/, parse: function (result) { return [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } }], /** * Parse the input color to rgba array * @param {String} input */ init: function (input) { var result, rgba, i, parser; this.input = input; // Gradients if (input && input.stops) { this.stops = map(input.stops, function (stop) { return new Color(stop[1]); }); // Solid colors } else { i = this.parsers.length; while (i-- && !rgba) { parser = this.parsers[i]; result = parser.regex.exec(input); if (result) { rgba = parser.parse(result); } } } this.rgba = rgba || []; }, /** * Return the color a specified format * @param {String} format */ get: function (format) { var input = this.input, rgba = this.rgba, ret; if (this.stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(this.stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && isNumber(rgba[0])) { if (format === 'rgb' || (!format && rgba[3] === 1)) { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; }, /** * Brighten the color * @param {Number} alpha */ brighten: function (alpha) { var i, rgba = this.rgba; if (this.stops) { each(this.stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; }, /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ setOpacity: function (alpha) { this.rgba[3] = alpha; return this; } }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color', 'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options Options include duration, easing, step and complete * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, this.renderer.globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params, null, complete); } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, radAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = [], value; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { radAttr = gradAttr; // Save the radial attributes for updating gradAttr = merge(gradAttr, renderer.getRadialAttr(radialReference, radAttr), { gradientUnits: 'userSpaceOnUse' } ); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); gradientObject.radAttr = radAttr; // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object value = 'url(' + renderer.url + '#' + id + ')'; elem.setAttribute(prop, value); elem.gradient = key; // Allow the color to be concatenated into tooltips formatters etc. (#2995) color.toString = function () { return value; }; } }, /** * Apply a polyfill to the text-stroke CSS property, by copying the text element * and apply strokes to the copy. * * Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/ */ applyTextShadow: function (textShadow) { var elem = this.element, tspans, hasContrast = textShadow.indexOf('contrast') !== -1, styles = {}, forExport = this.renderer.forExport, // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check // this again with new IE release. In exports, the rendering is passed to PhantomJS. supports = forExport || (elem.style.textShadow !== UNDEFINED && !isMS); // When the text shadow is set to contrast, use dark stroke for light text and vice versa if (hasContrast) { styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill)); } // Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this, // it removes the text shadows. if (isWebKit || forExport) { styles.textRendering = 'geometricPrecision'; } /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/) if (elem.textContent.indexOf('2.') === 0) { elem.style['text-shadow'] = 'none'; supports = false; } // */ // No reason to polyfill, we've got native support if (supports) { this.css(styles); // Apply altered textShadow or textRendering workaround } else { this.fakeTS = true; // Fake text shadow // In order to get the right y position of the clones, // copy over the y setter this.ySetter = this.xSetter; tspans = [].slice.call(elem.getElementsByTagName('tspan')); each(textShadow.split(/\s?,\s?/g), function (textShadow) { var firstChild = elem.firstChild, color, strokeWidth; textShadow = textShadow.split(' '); color = textShadow[textShadow.length - 1]; // Approximately tune the settings to the text-shadow behaviour strokeWidth = textShadow[textShadow.length - 2]; if (strokeWidth) { each(tspans, function (tspan, y) { var clone; // Let the first line start at the correct X position if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); y = elem.getAttribute('y'); tspan.setAttribute('y', y || 0); if (y === null) { elem.setAttribute('y', 0); } } // Create the clone and apply shadow properties clone = tspan.cloneNode(1); attr(clone, { 'class': PREFIX + 'text-shadow', 'fill': color, 'stroke': color, 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3), 'stroke-width': strokeWidth, 'stroke-linejoin': 'round' }); elem.insertBefore(clone, firstChild); }); } }); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val, complete) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr, setter; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { setter = this[key + 'Setter'] || this._defaultSetter; setter.call(this, value, key, element); // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value, setter); } } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } // In accordance with animate, run a complete callback if (complete) { complete(); } return ret; }, /** * Update the shadow elements with new attributes * @param {String} key The attribute name * @param {String|Number} value The value of the attribute * @param {Function} setter The setter function, inherited from the parent wrapper * @returns {undefined} */ updateShadows: function (key, value, setter) { var shadows = this.shadows, i = shadows.length; while (i--) { setter.call( shadows[i], key === 'height' ? Math.max(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value, key, shadows[i] ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) || elemWrapper.textWidth; // #3501 // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isMS && !hasSVG) { css(elemWrapper.element, styles); } else { hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { var existingGradient = this.renderer.gradients[this.element.gradient]; this.element.radialReference = coordinates; // On redrawing objects with an existing gradient, the gradient needs // to be repositioned (#3801) if (existingGradient && existingGradient.radAttr) { existingGradient.animate( this.renderer.getRadialAttr( coordinates, existingGradient.radAttr ) ); } return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); // Delete bBox memo when the rotation changes //delete wrapper.bBox; } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function (reload, rot) { var wrapper = this, bBox, // = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation, rad, element = wrapper.element, styles = wrapper.styles, textStr = wrapper.textStr, textShadow, elemStyle = element.style, toggleTextShadowShim, cache = renderer.cache, cacheKeys = renderer.cacheKeys, cacheKey; rotation = pick(rot, wrapper.rotation); rad = rotation * deg2rad; if (textStr !== UNDEFINED) { cacheKey = // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. textStr.toString().replace(numRegex, '0') + // Properties that affect bounding box ['', rotation || 0, styles && styles.fontSize, element.style.width].join(','); } if (cacheKey && !reload) { bBox = cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. // When the text shadow shim is used, we need to hide the fake shadows // to get the correct bounding box (#3872) toggleTextShadowShim = this.fakeTS && function (display) { each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) { tspan.style.display = display; }); }; // Workaround for #3842, Firefox reporting wrong bounding box for shadows if (isFirefox && elemStyle.textShadow) { textShadow = elemStyle.textShadow; elemStyle.textShadow = ''; } else if (toggleTextShadowShim) { toggleTextShadowShim(NONE); } bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; // #3842 if (textShadow) { elemStyle.textShadow = textShadow; } else if (toggleTextShadowShim) { toggleTextShadowShim(''); } } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it. When loading a chart in a hidden iframe in Firefox and IE/Edge, the // bounding box height is 0, so don't cache it (#5620). if (cacheKey && bBox.height > 0) { // Rotate (#4681) while (cacheKeys.length > 250) { delete cache[cacheKeys.shift()]; } if (!cache[cacheKey]) { cacheKeys.push(cacheKey); } cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function (inherit) { return this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, element = this.element, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // Mark as added this.added = true; // If we're adding to renderer root, or other elements in the group // have a z index, we need to handle it if (!parent || parent.handleZ || this.zIndex) { inserted = this.zIndexSetter(); } // If zIndex is not handled, append at the end if (!inserted) { (parent ? parent.element : renderer.box).appendChild(element); } // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i, strokeWidth = this['stroke-width']; // If "inherit", like maps in IE, assume 1 (#4981). With HC5 and the new strokeWidth // function, we should be able to use that instead. if (strokeWidth === 'inherit') { strokeWidth = 1; } value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * strokeWidth; } value = value.join(',') .replace(/NaN/g, 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } // Remove text content if it exists if (titleNode.firstChild) { titleNode.removeChild(titleNode.firstChild); } titleNode.appendChild( doc.createTextNode( (String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895 ) ); }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, visibilitySetter: function (value, key, element) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909) if (value === 'inherit') { element.removeAttribute(key); } else { element.setAttribute(key, value); } }, zIndexSetter: function (value, key) { var renderer = this.renderer, parentGroup = this.parentGroup, parentWrapper = parentGroup || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, otherElement, otherZIndex, element = this.element, inserted, run = this.added, i; if (defined(value)) { element.zIndex = value; // So we can read it for other elements in the group value = +value; if (this[key] === value) { // Only update when needed (#3865) run = false; } this[key] = value; } // Insert according to this and other elements' zIndex. Before .add() is called, // nothing is done. Then on add, or by later calls to zIndexSetter, the node // is placed on the right place in the DOM. if (run) { value = this.zIndex; if (value && parentGroup) { parentGroup.handleZ = true; } childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length && !inserted; i++) { otherElement = childNodes[i]; otherZIndex = otherElement.zIndex; if (otherElement !== element && ( // Insert before the first element with a higher zIndex pInt(otherZIndex) > value || // If no zIndex given, insert before the first element with a zIndex (!defined(value) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; } } if (!inserted) { parentNode.appendChild(element); } } return inserted; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // These setters both set the key on the instance itself plus as an attribute SVGElement.prototype.opacitySetter = SVGElement.prototype.displaySetter = function (value, key, element) { this[key] = value; element.setAttribute(key, value); }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport, allowHTML) { var renderer = this, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? win.location.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.allowHTML = allowHTML; renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.cacheKeys = []; renderer.imgCount = 0; renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style); return this.style; }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Get converted radial gradient attributes */ getRadialAttr: function (radialReference, gradAttr) { return { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2] }; }, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, wasTooLong, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textShadow = textStyles && textStyles.textShadow, ellipsis = textStyles && textStyles.textOverflow === 'ellipsis', i = childNodes.length, tempParent = width && !wrapper.added && this.box, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }, unescapeAngleBrackets = function (inputStr) { return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textShadow && !ellipsis && !width && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr))); // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (tempParent) { tempParent.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // Trim empty lines (#5261) lines = grep(lines, function (line) { return line !== ''; }); // build the lines each(lines, function buildTextLines(line, lineNo) { var spans, spanNo = 0; line = line .replace(/^\s+|\s+$/g, '') // Trim to prevent useless/costly process on the spaces (#5258) .replace(/<span/g, '|||<span') .replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function buildTextSpans(span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' '); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } /*if (width) { renderer.breakText(wrapper, width); }*/ // Check width and apply soft breaks or ellipsis if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 noWrap = textStyles.whiteSpace === 'nowrap', hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && !noWrap), tooLong, actualWidth, rest = [], dy = getLineHeight(tspan), softLineNo = 1, rotation = wrapper.rotation, wordStr = span, // for ellipsis cursor = wordStr.length, // binary search cursor bBox; while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) { wrapper.rotation = 0; // discard rotation when computing box bBox = wrapper.getBBox(true); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; // For ellipsis, do a binary search for the correct string length if (wasTooLong === undefined) { wasTooLong = tooLong; // First time } if (ellipsis && wasTooLong) { cursor /= 2; if (wordStr === '' || (!tooLong && cursor < 0.5)) { words = []; // All ok, break out } else { wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor)); words = [wordStr + (width > 3 ? '\u2026' : '')]; tspan.removeChild(tspan.firstChild); } // Looping down, this is the first word sequence that is not too long, // so we can move on to build the next line. } else if (!tooLong || words.length === 1) { words = rest; rest = []; if (words.length && !noWrap) { softLineNo++; tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } wrapper.rotation = rotation; } spanNo++; } } }); }); if (wasTooLong) { wrapper.attr('title', wrapper.textStr); } if (tempParent) { tempParent.removeChild(textNode); // attach it to the DOM to read offset width } // Apply the text shadow if (textShadow && wrapper.applyTextShadow) { wrapper.applyTextShadow(textShadow); } } }, /* breakText: function (wrapper, width) { var bBox = wrapper.getBBox(), node = wrapper.element, textLength = node.textContent.length, pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width increment = 0, finalPos; if (bBox.width > width) { while (finalPos === undefined) { textLength = node.getSubStringLength(0, pos); if (textLength <= width) { if (increment === -1) { finalPos = pos; } else { increment = 1; } } else { if (increment === 1) { finalPos = pos - 1; } else { increment = -1; } } pos += increment; } } console.log('width', width, 'stringWidth', node.getSubStringLength(0, finalPos)) }, */ /** * Returns white for dark colors and black for bright colors */ getContrast: function (color) { color = Color(color).rgba; return color[0] + color[1] + color[2] > 384 ? '#000000' : '#FFFFFF'; }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function (e) { if (curState !== 3) { callback.call(label, e); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); // Setting x or y translates to cx and cy wrapper.xSetter = wrapper.ySetter = function (value, key, element) { element.setAttribute('c' + key, value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { wrapper.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value, key, element) { attr(element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var ren = this, obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]); // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). createElement('img', { onload: function () { var chart = charts[ren.chartIndex]; // Special case for SVGs on IE11, the width is not accessible until the image is // part of the DOM (#2854). if (this.width === 0) { css(this, { position: ABSOLUTE, top: '-999em' }); doc.body.appendChild(this); } // Center the image centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); // Clean up after #2854 workaround. if (this.parentNode) { this.parentNode.removeChild(this); } // Fire the load event when all external images are loaded ren.imgCount--; if (!ren.imgCount && chart && chart.onload) { chart.onload(); } }, src: imageSrc }); this.imgCount++; } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; wrapper.count = 0; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && (renderer.allowHTML || !renderer.forExport)) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { var lineHeight, baseline, style; fontSize = fontSize || this.style.fontSize; if (!fontSize && elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement style = win.getComputedStyle(elem, ''); fontSize = style && style.fontSize; // #4309, the style doesn't exist inside a hidden iframe in Firefox } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2); baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Correct X and Y positioning of a label for rotation (#1764) */ rotCorr: function (baseline, rotation, alterY) { var y = baseline; if (rotation && alterY) { y = mathMax(y * mathCos(rotation * deg2rad), 4); } return { x: (-baseline / 3) * mathSin(rotation * deg2rad), y: y }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, hasBGImage = /^url\((.*?)\)$/.test(shape), needsBox = hasBGImage, updateBoxSize, updateTextPadding, boxAttr; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ updateBoxSize = function () { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) && text.getBBox(); //#3295 && 3514 box failure when string equals 0 wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { if (!box) { // create the border box if it is not already present boxX = crispAdjust; boxY = (baseline ? -baselineOffset : 0) + crispAdjust; wrapper.box = box = renderer.symbols[shape] || hasBGImage ? // Symbol definition exists (#5324) renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); if (!box.isImg) { // #4324, fill "none" causes it to be ignored by mouse events in IE box.attr('fill', NONE); } box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } }; /** * This function runs after setting text or padding, but only if padding is changed */ updateTextPadding = function () { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding, y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; }; /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ boxAttr = function (key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } }; /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = wrapper.padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { value = { left: 0, center: 0.5, right: 1 }[value]; if (value !== alignFactor) { alignFactor = value; if (bBox) { // Bounding box exists, means we're dynamically changing wrapper.attr({ x: wrapperX }); // #5134 } } }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, mathRound(value) - crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + 2 * padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } if (styles && styles.textOverflow === 'ellipsis') { styles.whiteSpace = 'nowrap'; styles.overflow = 'hidden'; } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element; // faking getBBox in exported SVG in legacy IE // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows, styles = wrapper.styles; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), whiteSpace = styles && styles.whiteSpace, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } // Reset multiline/ellipsis in order to read width (#4928, #5417) css(elem, { width: '', whiteSpace: whiteSpace || 'nowrap' }); // Update textWidth if (elem.offsetWidth > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: whiteSpace || 'normal' // #3331 }); } wrapper.getSpanCorrection(elem.offsetWidth, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for lint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer, isSVG = renderer.isSVG, addSetters = function (element, style) { // These properties are set as attributes on the SVG group, and as // identical CSS properties on the div. (#3542) each(['display', 'opacity', 'visibility'], function (prop) { wrap(element, prop + 'Setter', function (proceed, value, key, elem) { proceed.call(this, value, key, elem); style[key] = value; }); }); }; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; wrapper.htmlUpdateTransform(); }; // Add setters for the element itself (#4938) if (isSVG) { // #4938, only for HTML within SVG addSetters(wrapper, wrapper.element.style); } // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper .attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Keep the whiteSpace style outside the wrapper.styles collection element.style.whiteSpace = 'nowrap'; // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle, cls = attr(parentGroup.element, 'class'); if (cls) { cls = { className: cls }; } // else null // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, cls, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX, display: parentGroup.display, opacity: parentGroup.opacity, // #5075 pointerEvents: parentGroup.styles && parentGroup.styles.pointerEvents // #5595 }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; } }); addSetters(parentGroup, htmlGroupStyle); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; if (parent) { this.parentGroup = parent; } // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, 'fill-opacitySetter': function (value, key, element) { createElement( this.renderer.prepVML(['<', key.split('-')[0], ' opacity="', value, '"/>']), null, null, element ); }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key, this)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, displaySetter: function (value, key, element) { element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; VMLElement['stroke-opacitySetter'] = VMLElement['fill-opacitySetter']; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: 'relative' })); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.gradients = {}; renderer.cache = {}; // Cache for numerical bounding boxes renderer.cacheKeys = []; renderer.imgCount = 0; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], count: 0, left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // If the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); wrapper[prop + '-opacitySetter'](colorObject.get('a'), prop, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x, // - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ function getScript(scriptLocation, callback) { var head = doc.getElementsByTagName('head')[0], script = doc.createElement('script'); script.type = 'text/javascript'; script.src = scriptLocation; script.onload = callback; head.appendChild(script); } if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(axis.lin2log(value)) : value }); // prepare CSS //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; // first call if (!defined(label)) { tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) //.attr(attr) // without position absolute, IE export sometimes is wrong .css(merge(labelOptions.style)) .add(axis.labelGroup) : null; tick.labelLength = label && label.getBBox().width; // Un-rotated length tick.rotation = 0; // Base value to detect change for new calls to getBBox // update } else if (label) { label.attr({ text: str }); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { return this.label ? this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] : 0; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (xy) { var axis = this.axis, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, mathMin(axis.pos, spacing[3])), rightBound = pick(axis.labelRight, mathMax(axis.pos + axis.len, chartWidth - spacing[1])), label = this.label, rotation = this.rotation, factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign], labelWidth = label.getBBox().width, slotWidth = axis.getSlotWidth(), modifiedSlotWidth = slotWidth, xCorrection = factor, goRight = 1, leftPos, rightPos, textWidth, css = {}; // Check if the label overshoots the chart spacing box. If it does, move it. // If it now overshoots the slotWidth, add ellipsis. if (!rotation) { leftPos = pxPos - factor * labelWidth; rightPos = pxPos + (1 - factor) * labelWidth; if (leftPos < leftBound) { modifiedSlotWidth = xy.x + modifiedSlotWidth * (1 - factor) - leftBound; } else if (rightPos > rightBound) { modifiedSlotWidth = rightBound - xy.x + modifiedSlotWidth * factor; goRight = -1; } modifiedSlotWidth = mathMin(slotWidth, modifiedSlotWidth); // #4177 if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') { xy.x += goRight * (slotWidth - modifiedSlotWidth - xCorrection * (slotWidth - mathMin(labelWidth, modifiedSlotWidth))); } // If the label width exceeds the available space, set a text width to be // picked up below. Also, if a width has been set before, we need to set a new // one because the reported labelWidth will be limited by the box (#3938). if (labelWidth > modifiedSlotWidth || (axis.autoRotation && label.styles.width)) { textWidth = modifiedSlotWidth; } // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) { textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound); } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) { textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad)); } if (textWidth) { css.width = textWidth; if (!axis.options.labels.style.textOverflow) { css.textOverflow = 'ellipsis'; } label.css(css); } }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = labelOptions.y, line; if (!defined(yOffset)) { if (axis.side === 0) { yOffset = label.rotation ? -8 : -label.getBBox().height; } else if (axis.side === 2) { yOffset = rotCorr.y + 8; } else { // #3140, #3140 yOffset = mathCos(label.rotation * deg2rad) * (rotCorr.y - label.getBBox(false, 0).height / 2); } } x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { line = (index / (step || 1) % staggerLines); if (axis.opposite) { line = staggerLines - line - 1; } y += line * (axis.labelOffset / staggerLines); } return { x: x, y: mathRound(y) }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickSize = axis.tickSize(tickPrefix), tickColor = options[tickPrefix + 'Color'], gridLinePath, mark = tick.mark, markPath, step = /*axis.labelStep || */labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickSize) { if (axis.opposite) { tickSize[0] = -tickSize[0]; } markPath = tick.getMarkPath(x, y, tickSize[0], tickSize[1] * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickSize[1], opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && isNumber(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { tick.handleOverflow(xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && isNumber(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); } else { stop(label); // #5332 label.attr('y', -9999); // #1338 } tick.isNew = false; } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ Highcharts.PlotLineOrBand = function (axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; Highcharts.PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, color = options.color, zIndex = pick(options.zIndex, 0), events = options.events, attribs = {}, renderer = axis.chart.renderer, log2lin = axis.log2lin; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band path = axis.getPlotBandPath(from, to, options); if (color) { attribs.fill = color; } if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex attribs.zIndex = zIndex; // common for lines and bands if (svgElem) { if (path) { svgElem.show(); svgElem.animate({ d: path }); } else { svgElem.hide(); if (label) { plotLine.label = label = label.destroy(); } } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0 && !path.flat) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign: !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); this.renderLabel(optionsLabel, path, isBand, zIndex); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Render and align label for plot line or band. */ renderLabel: function (optionsLabel, path, isBand, zIndex) { var plotLine = this, label = plotLine.label, renderer = plotLine.axis.chart.renderer, attribs, xs, ys, x, y; // add the SVG element if (!label) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation }; attribs.zIndex = zIndex; plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .css(optionsLabel.style) .add(); } // get the bounding box and align the label // #3000 changed to better handle choice between plotband or plotline xs = [path[1], path[4], (isBand ? path[6] : path[1])]; ys = [path[2], path[5], (isBand ? path[7] : path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); }, /** * Remove the plot line or band */ destroy: function () { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * Object with members for extending the Axis prototype */ AxisPlotLineOrBandExtension = { /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true); if (path && toPath) { // Flat paths don't need labels (#3836) path.flat = path.toString() === toPath.toString(); path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, addPlotBand: function (options) { return this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { return this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new Highcharts.PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ var Axis = Highcharts.Axis = function () { this.init.apply(this, arguments); }; Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#D8D8D8', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: { enabled: true, // rotation: 0, // align: 'center', // step: null, style: { color: '#606060', cursor: 'default', fontSize: '11px' }, x: 0 //y: undefined /*formatter: function () { return this.value; },*/ }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', //tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime //visible: true }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, //tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return Highcharts.numberFormat(this.total, -1); }, style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' }) } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15 }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15 }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { autoRotation: [-45], x: 0 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for top axes */ defaultTopAxisOptions: { labels: { autoRotation: [-45], x: 0 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; axis.chart = chart; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = axis.coll || (isXAxis ? 'xAxis' : 'yAxis'); axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; axis.reversed = options.reversed; axis.visible = options.visible !== false; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.hasNames = type === 'category' || options.categories === true; axis.categories = options.categories || axis.hasNames; axis.names = axis.names || []; // Preserve on update (#3830) // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; axis.stacksTouched = 0; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = axis.log2lin; axis.lin2val = axis.lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.coll === 'yAxis' && this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null && value !== 0) { // #5480 ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = Highcharts.numberFormat(value, -1); } else { // small numbers ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.threshold = null; axis.softThreshold = !axis.isXAxis; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { // If xData contains values which is not numbers, then filter them out. // To prevent performance hit, we only do this after we have already // found seriesDataMin because in most cases all data is valid. #5234. seriesDataMin = arrayMin(xData); if (!isNumber(seriesDataMin) && !(seriesDataMin instanceof Date)) { // Date for #5010 xData = grep(xData, function (x) { return isNumber(x); }); seriesDataMin = arrayMin(xData); // Do it again with valid data } axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { axis.threshold = threshold; } // If any series has a hard threshold, it takes precedence if (!seriesOptions.softThreshold || axis.isLog) { axis.softThreshold = false; } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this.linkedParent || this, // #1417 sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, doPostTranslate = (axis.isOrdinal || axis.isBroken || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (doPostTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (doPostTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB, /** * Check if x is between a and b. If not, either move to a/b or skip, * depending on the force parameter. */ between = function (x, a, b) { if (x < a || x > b) { if (force) { x = mathMin(mathMax(a, x), b); } else { skip = true; } } return x; }; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (!isNumber(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; x1 = x2 = between(x1, axisLeft, axisLeft + axis.width); } else { x1 = axisLeft; x2 = cWidth - axis.right; y1 = y2 = between(y1, axisTop, axisTop + axis.height); } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, pointRangePadding = axis.pointRangePadding || 0, min = axis.min - pointRangePadding, // #1498 max = axis.max + pointRangePadding, // #1498 range = max - min, len; // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them. if (range && range / minorTickInterval < axis.len / 3) { // #3875 if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), min, max, options.startOfWeek ) ); } else { for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) { minorTickPositions.push(pos); } } } if (minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498 } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs, minRange; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.isLog ? axis.log2lin(axis.dataMin) : axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.isLog ? axis.log2lin(axis.dataMax) : axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Find the closestPointRange across all series */ getClosest: function () { var ret; if (this.categories) { ret = 1; } else { each(this.series, function (series) { var seriesClosest = series.closestPointRange; if (!series.noSharedTooltip && defined(seriesClosest)) { ret = defined(ret) ? mathMin(ret, seriesClosest) : seriesClosest; } }); } return ret; }, /** * When a point name is given and no x, search for the name in the existing categories, * or if categories aren't provided, search names or create a new category (#2522). */ nameToX: function (point) { var explicitCategories = isArray(this.categories), names = explicitCategories ? this.categories : this.names, nameX = point.options.x, x; point.series.requireSorting = false; if (!defined(nameX)) { nameX = this.options.nameToX === false ? point.series.autoIncrement() : inArray(point.name, names); } if (nameX === -1) { // The name is not found in currenct categories if (!explicitCategories) { x = names.length; } } else { x = nameX; } // Write the last point's name to the names array this.names[x] = point.name; return x; }, /** * When changes have been done to series data, update the axis.names. */ updateNames: function () { var axis = this; if (this.names.length > 0) { this.names.length = 0; this.minRange = undefined; each(this.series || [], function (series) { // When adding a series, points are not yet generated if (!series.processedXData) { series.processData(); series.generatePoints(); } each(series.points, function (point, i) { var x; if (point.options && point.options.x === undefined) { x = axis.nameToX(point); if (x !== point.x) { point.x = x; series.xData[i] = x; } } }); }); } }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA, isXAxis = axis.isXAxis; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { // Get the closest points closestPointRange = axis.getClosest(); each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (isXAxis ? pick(series.options.pointRange, closestPointRange, 0) : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement; pointRange = mathMax(pointRange, seriesPointRange); if (!axis.single) { // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value if (isXAxis) { axis.closestPointRange = closestPointRange; } } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, minFromRange: function () { return this.max - this.range; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickInterval: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, log2lin = axis.log2lin, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, categories = axis.categories, threshold = axis.threshold, softThreshold = axis.softThreshold, thresholdMin, thresholdMax, hardMin, hardMax; if (!isDatetimeAxis && !categories && !isLinked) { this.getTickAmount(); } // Min or max set either by zooming/setExtremes or initial options hardMin = pick(axis.userMin, options.min); hardMax = pick(axis.userMax, options.max); // Linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } // Initial min and max from the extreme data values } else { // Adjust to hard threshold if (!softThreshold && defined(threshold)) { if (axis.dataMin >= threshold) { thresholdMin = threshold; minPadding = 0; } else if (axis.dataMax <= threshold) { thresholdMax = threshold; maxPadding = 0; } } axis.min = pick(hardMin, thresholdMin, axis.dataMin); axis.max = pick(hardMax, thresholdMax, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } // The correctFloat cures #934, float errors on full tens. But it // was too aggressive for #4360 because of conversion back to lin, // therefore use precision 15. axis.min = correctFloat(log2lin(axis.min), 15); axis.max = correctFloat(log2lin(axis.max), 15); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = hardMin = mathMax(axis.min, axis.minFromRange()); // #618 axis.userMax = hardMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for Highstock Scroller. Consider combining with beforePadding. fireEvent(axis, 'foundExtremes'); // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(hardMin) && minPadding) { axis.min -= length * minPadding; } if (!defined(hardMax) && maxPadding) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // When the threshold is soft, adjust the extreme value only if // the data extreme and the padded extreme land on either side of the threshold. For example, // a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the // default minPadding and startOnTick options. This is prevented by the softThreshold // option. if (softThreshold && defined(axis.dataMin)) { threshold = threshold || 0; if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) { axis.min = threshold; } else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) { axis.max = threshold; } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943, #4184) if (axis.pointRange && !tickIntervalOption) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange); if (!tickIntervalOption && axis.tickInterval < minTickInterval) { axis.tickInterval = minTickInterval; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog && !tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 0.5 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount ); } // Prevent ticks from getting so close that we can't draw the labels if (!this.tickAmount) { axis.tickInterval = axis.unsquish(); } this.setTickPositions(); }, /** * Now we have computed the normalized tickInterval, get the tick positions */ setTickPositions: function () { var options = this.options, tickPositions, tickPositionsOption = options.tickPositions, tickPositioner = options.tickPositioner, startOnTick = options.startOnTick, endOnTick = options.endOnTick, single; // Set the tickmarkOffset this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' && this.tickInterval === 1) ? 0.5 : 0; // #3202 // get minorTickInterval this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ? this.tickInterval / 5 : options.minorTickInterval; // Find the tick positions this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565) if (!tickPositions) { if (this.isDatetimeAxis) { tickPositions = this.getTimeTicks( this.normalizeTimeTickInterval(this.tickInterval, options.units), this.min, this.max, options.startOfWeek, this.ordinalPositions, this.closestPointRange, true ); } else if (this.isLog) { tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max); } else { tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max); } // Too dense ticks, keep only the first and last (#4477) if (tickPositions.length > this.len) { tickPositions = [tickPositions[0], tickPositions.pop()]; } this.tickPositions = tickPositions; // Run the tick positioner callback, that allows modifying auto tick positions. if (tickPositioner) { tickPositioner = tickPositioner.apply(this, [this.min, this.max]); if (tickPositioner) { this.tickPositions = tickPositions = tickPositioner; } } } if (!this.isLinked) { // reset min/max or remove extremes based on start/end on tick this.trimTicks(tickPositions, startOnTick, endOnTick); // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (this.min === this.max && defined(this.min) && !this.tickAmount) { // Substract half a unit (#2619, #2846, #2515, #3390) single = true; this.min -= 0.5; this.max += 0.5; } this.single = single; if (!tickPositionsOption && !tickPositioner) { this.adjustTickAmount(); } } }, /** * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max */ trimTicks: function (tickPositions, startOnTick, endOnTick) { var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = this.minPointOffset || 0; if (startOnTick) { this.min = roundedMin; } else { while (this.min - minPointOffset > tickPositions[0]) { tickPositions.shift(); } } if (endOnTick) { this.max = roundedMax; } else { while (this.max + minPointOffset < tickPositions[tickPositions.length - 1]) { tickPositions.pop(); } } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } }, /** * Check if there are multiple axes in the same pane * @returns {Boolean} There are other axes */ alignToOthers: function () { var others = {}, // Whether there is another axis to pair with this one hasOther, options = this.options; if (this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) { each(this.chart[this.coll], function (axis) { var otherOptions = axis.options, horiz = axis.horiz, key = [ horiz ? otherOptions.left : otherOptions.top, otherOptions.width, otherOptions.height, otherOptions.pane ].join(','); if (axis.series.length) { // #4442 if (others[key]) { hasOther = true; // #4201 } else { others[key] = 1; } } }); } return hasOther; }, /** * Set the max ticks of either the x and y axis collection */ getTickAmount: function () { var options = this.options, tickAmount = options.tickAmount, tickPixelInterval = options.tickPixelInterval; if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial && !this.isLog && options.startOnTick && options.endOnTick) { tickAmount = 2; } if (!tickAmount && this.alignToOthers()) { // Add 1 because 4 tick intervals require 5 ticks (including first and last) tickAmount = mathCeil(this.len / tickPixelInterval) + 1; } // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This // prevents the axis from adding ticks that are too far away from the data extremes. if (tickAmount < 4) { this.finalTickAmt = tickAmount; tickAmount = 5; } this.tickAmount = tickAmount; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var tickInterval = this.tickInterval, tickPositions = this.tickPositions, tickAmount = this.tickAmount, finalTickAmt = this.finalTickAmt, currentTickAmount = tickPositions && tickPositions.length, i, len; if (currentTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + tickInterval )); } this.transA *= (currentTickAmount - 1) / (tickAmount - 1); this.max = tickPositions[tickPositions.length - 1]; // We have too many ticks, run second pass to try to reduce ticks } else if (currentTickAmount > tickAmount) { this.tickInterval *= 2; this.setTickPositions(); } // The finalTickAmt property is set in getTickAmount if (defined(finalTickAmt)) { i = len = tickPositions.length; while (i--) { if ( (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last ) { tickPositions.splice(i, 1); } } this.finalTickAmt = UNDEFINED; } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax || axis.alignToOthers()) { if (axis.resetStacks) { axis.resetStacks(); } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickInterval(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (axis.cleanStacks) { axis.cleanStacks(); } }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true each(axis.series, function (serie) { delete serie.kdTree; }); // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options, min = mathMin(dataMin, pick(options.min, dataMin)), max = mathMax(dataMax, pick(options.max, dataMax)); // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= min) { newMin = min; } if (defined(dataMax) && newMax >= max) { newMax = max; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values. Rounding fixes problems with // column overflow and plot line filtering (#4898, #4899) if (percentRegex.test(height)) { height = Math.round(parseFloat(height) / 100 * chart.plotHeight); } if (percentRegex.test(top)) { top = Math.round(parseFloat(top) / 100 * chart.plotHeight + chart.plotTop); } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog, lin2log = axis.lin2log; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog, lin2log = axis.lin2log, realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (threshold === null) { threshold = realMin; } else if (realMin > threshold) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Get the tick length and width for the axis. * @param {String} prefix 'tick' or 'minorTick' * @returns {Array} An array of tickLength and tickWidth */ tickSize: function (prefix) { var options = this.options, tickLength = options[prefix + 'Length'], tickWidth = pick(options[prefix + 'Width'], prefix === 'tick' && this.isXAxis ? 1 : 0); // X axis defaults to 1 if (tickWidth && tickLength) { // Negate the length if (options[prefix + 'Position'] === 'inside') { tickLength = -tickLength; } return [tickLength, tickWidth]; } }, /** * Return the size of the labels */ labelMetrics: function () { return this.chart.renderer.fontMetrics( this.options.labels.style.fontSize, this.ticks[0] && this.ticks[0].label ); }, /** * Prevent the ticks from getting so close we can't draw the labels. On a horizontal * axis, this is handled by rotating the labels, removing ticks and adding ellipsis. * On a vertical axis remove ticks and add ellipsis. */ unsquish: function () { var labelOptions = this.options.labels, horiz = this.horiz, tickInterval = this.tickInterval, newTickInterval = tickInterval, slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval), rotation, rotationOption = labelOptions.rotation, labelMetrics = this.labelMetrics(), step, bestScore = Number.MAX_VALUE, autoRotation, // Return the multiple of tickInterval that is needed to avoid collision getStep = function (spaceNeeded) { var step = spaceNeeded / (slotSize || 1); step = step > 1 ? mathCeil(step) : 1; return step * tickInterval; }; if (horiz) { autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971 defined(rotationOption) ? [rotationOption] : slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation ); if (autoRotation) { // Loop over the given autoRotation options, and determine which gives the best score. The // best score is that with the lowest number of steps and a rotation closest to horizontal. each(autoRotation, function (rot) { var score; if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891 step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot))); score = step + mathAbs(rot / 360); if (score < bestScore) { bestScore = score; rotation = rot; newTickInterval = step; } } }); } } else if (!labelOptions.step) { // #4411 newTickInterval = getStep(labelMetrics.h); } this.autoRotation = autoRotation; this.labelRotation = pick(rotation, rotationOption); return newTickInterval; }, /** * Get the general slot width for this axis. This may change between the pre-render (from Axis.getOffset) * and the final tick rendering and placement (#5086). */ getSlotWidth: function () { var chart = this.chart, horiz = this.horiz, labelOptions = this.options.labels, slotCount = Math.max(this.tickPositions.length - (this.categories ? 0 : 1), 1), marginLeft = chart.margin[3]; return (horiz && (labelOptions.step || 0) < 2 && !labelOptions.rotation && // #4415 ((this.staggerLines || 1) * chart.plotWidth) / slotCount) || (!horiz && ((marginLeft && (marginLeft - chart.spacing[3])) || chart.chartWidth * 0.33)); // #1580, #1931 }, /** * Render the axis labels and determine whether ellipsis or rotation need to be applied */ renderUnsquish: function () { var chart = this.chart, renderer = chart.renderer, tickPositions = this.tickPositions, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, slotWidth = this.getSlotWidth(), innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))), attr = {}, labelMetrics = this.labelMetrics(), textOverflowOption = labelOptions.style.textOverflow, css, maxLabelLength = 0, label, i, pos; // Set rotation option unless it is "auto", like in gauges if (!isString(labelOptions.rotation)) { attr.rotation = labelOptions.rotation || 0; // #4443 } // Get the longest label length each(tickPositions, function (tick) { tick = ticks[tick]; if (tick && tick.labelLength > maxLabelLength) { maxLabelLength = tick.labelLength; } }); this.maxLabelLength = maxLabelLength; // Handle auto rotation on horizontal axis if (this.autoRotation) { // Apply rotation only if the label is too wide for the slot, and // the label is wider than its height. if (maxLabelLength > innerWidth && maxLabelLength > labelMetrics.h) { attr.rotation = this.labelRotation; } else { this.labelRotation = 0; } // Handle word-wrap or ellipsis on vertical axis } else if (slotWidth) { // For word-wrap or ellipsis css = { width: innerWidth + PX }; if (!textOverflowOption) { css.textOverflow = 'clip'; // On vertical axis, only allow word wrap if there is room for more lines. i = tickPositions.length; while (!horiz && i--) { pos = tickPositions[i]; label = ticks[pos].label; if (label) { // Reset ellipsis in order to get the correct bounding box (#4070) if (label.styles.textOverflow === 'ellipsis') { label.css({ textOverflow: 'clip' }); // Set the correct width in order to read the bounding box height (#4678, #5034) } else if (ticks[pos].labelLength > slotWidth) { label.css({ width: slotWidth + 'px' }); } if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) { label.specCss = { textOverflow: 'ellipsis' }; } } } } } // Add ellipsis if the label length is significantly longer than ideal if (attr.rotation) { css = { width: (maxLabelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX }; if (!textOverflowOption) { css.textOverflow = 'ellipsis'; } } // Set the explicit or automatic label alignment this.labelAlign = labelOptions.align || this.autoLabelAlign(this.labelRotation); if (this.labelAlign) { attr.align = this.labelAlign; } // Apply general and specific CSS each(tickPositions, function (pos) { var tick = ticks[pos], label = tick && tick.label; if (label) { label.attr(attr); // This needs to go before the CSS in old IE (#4502) if (css) { label.css(merge(css, label.specCss)); } delete label.specCss; tick.rotation = attr.rotation; } }); // Note: Why is this not part of getLabelPosition? this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side !== 0); }, /** * Return true if the axis has associated data */ hasData: function () { return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions); }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, opposite = axis.opposite, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, clip, directionFactor = [-1, 1, 1, -1][side], n, textAlign, axisParent = axis.axisParent, // Used in color axis lineHeightCorrection, tickSize = this.tickSize('tick'); // For reuse in Axis.render hasData = axis.hasData(); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(axisParent); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(axisParent); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(axisParent); } if (hasData || axis.isLinked) { // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); axis.renderUnsquish(); // Left side must be align: right and right side must have align: left for labels if (labelOptions.reserveSpace !== false && (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign || axis.labelAlign === 'center')) { each(tickPositions, function (pos) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); }); } if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset * (axis.opposite ? -1 : 1); } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { textAlign = axisTitleOptions.textAlign; if (!textAlign) { textAlign = (horiz ? { low: 'left', middle: 'center', high: 'right' } : { low: opposite ? 'right' : 'left', middle: 'center', high: opposite ? 'left' : 'right' })[axisTitleOptions.align]; } axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: textAlign }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](true); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar if (side === 0) { lineHeightCorrection = -axis.labelMetrics().h; } else if (side === 2) { lineHeightCorrection = axis.tickRotCorr.y; } else { lineHeightCorrection = 0; } // Find the padded label offset labelOffsetPadded = Math.abs(labelOffset) + titleMargin; if (labelOffset) { labelOffsetPadded -= lineHeightCorrection; labelOffsetPadded += directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + directionFactor * 8) : labelOptions.x); } axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded, // #3027 hasData && tickPositions.length && tickSize ? tickSize[0] : 0 // #4866 ); // Decide the clipping needed to keep the graph inside the plot area and axis lines clip = options.offset ? 0 : mathFloor(options.lineWidth / 2) * 2; // #4308, #4371 clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], clip); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer .crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, xOption = axisTitleOptions.x || 0, yOption = axisTitleOptions.y || 0, fontSize = this.chart.renderer.fontMetrics(axisTitleOptions.style.fontSize).f, // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption, y: horiz ? offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, lin2log = axis.lin2log, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && isNumber(axis.oldMin), showAxis = axis.showAxis, animation = animObject(renderer.globalAnimation), from, to; // Reset axis.labelEdge.length = 0; //axis.justifyToPlot = overflow === 'justify'; axis.overlap = false; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (axis.hasData() || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions, function (pos, i) { // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && (axis.min === 0 || axis.single)) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset; if (i % 2 === 0 && pos < axis.max && to <= axis.max + (chart.polar ? -tickmarkOffset : tickmarkOffset)) { // #2248, #4660 if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = animation.duration, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them syncTimeout( destroyInactiveItems, coll === alternateBands || !chart.hasRendered || !delay ? 0 : delay ); }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](true); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { if (this.visible) { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); } // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy properties each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'gridGroup', 'labelGroup', 'cross'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); this._addedPlotLB = this.chart._labelPanes = this.ordinalSlope = undefined; // #1611, #2887, #4314, #5316 }, /** * Draw the crosshair * * @param {Object} e The event arguments from the modified pointer event * @param {Object} point The Point object */ drawCrosshair: function (e, point) { var path, options = this.crosshair, pos, attribs, categorized, strokeWidth; // Use last available event when updating non-snapped crosshairs without // mouse interaction (#5287) if (!e) { e = this.cross && this.cross.e; } if ( // Disabled in options !this.crosshair || // Snap ((defined(point) || !pick(options.snap, true)) === false) ) { this.hideCrosshair(); } else { // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834 } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189 } else { path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189 } if (path === null) { this.hideCrosshair(); return; } categorized = this.categories && !this.isRadial; strokeWidth = pick(options.width, (categorized ? this.transA : 1)); // Draw the cross if (this.cross) { this.cross .attr({ d: path, visibility: 'visible', 'stroke-width': strokeWidth // #4737 }); } else { attribs = { 'pointer-events': 'none', // #5259 'stroke-width': strokeWidth, stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'), zIndex: pick(options.zIndex, 2) }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } this.cross.e = e; } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min - getTZOffset(min)), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 minDate[setMilliseconds](interval >= timeUnits.second ? 0 : // #3935 count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654 if (interval >= timeUnits.second) { // second minDate[setSeconds](interval >= timeUnits.minute ? 0 : // #3935 count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits.minute) { // minute minDate[setMinutes](interval >= timeUnits.hour ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits.hour) { // hour minDate[setHours](interval >= timeUnits.day ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits.day) { // day minDate[setDate](interval >= timeUnits.month ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits.month) { // month minDate[setMonth](interval >= timeUnits.year ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits.year) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits.week) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; if (timezoneOffset || getTimezoneOffset) { minDate = minDate.getTime(); minDate = new Date(minDate + getTZOffset(minDate)); } minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), variableDayLength = !useUTC || !!getTimezoneOffset, // #4951 localTimezoneOffset = (timeUnits.day + (useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000) ) % timeUnits.day; // #950, #3359 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits.year) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits.month) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (variableDayLength && (interval === timeUnits.day || interval === timeUnits.week)) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits.day ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset; }), function (time) { higherRanks[time] = 'day'; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; }; /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) { var units = unitsOption || [[ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1, 2] ], [ 'week', [1, 2] ], [ 'month', [1, 2, 3, 4, 6] ], [ 'year', null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits.year && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval( tickInterval / interval, multiples, unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360 ); return { unitRange: interval, count: count, unitName: unit[0] }; }; /** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, lin2log = axis.lin2log, log2lin = axis.log2lin, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; }; Axis.prototype.log2lin = function (num) { return math.log(num) / math.LN10; }; Axis.prototype.lin2log = function (num) { return math.pow(10, num); }; /** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8, display: 'none' // #2301, #2657, #3532, #5570 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add(); // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.label.attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function (delay) { var tooltip = this; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) delay = pick(delay, this.options.hideDelay, 500); if (!this.isHidden) { this.hideTimer = syncTimeout(function () { tooltip.label[delay ? 'fadeOut' : 'hide'](); tooltip.isHidden = true; }, delay); } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotLeft = chart.plotLeft, plotX = 0, plotY = 0, yAxis, xAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; xAxis = point.series.xAxis; plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0); plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, h = point.h || 0, // #4117 swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop, chart.plotTop, chart.plotTop + chart.plotHeight], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft, chart.plotLeft, chart.plotLeft + chart.plotWidth], // The far side is right or bottom preferFarSide = !this.followPointer && pick(point.ttBelow, !chart.inverted === !!point.negative), // #4984 /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point, min, max) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = mathMin(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h); } else if (roomRight) { ret[dim] = mathMax(min, alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h); } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { var retVal; // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { retVal = false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } return retVal; }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), s; // build the header s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header // build the values s = s.concat(tooltip.bodyFormatter(items)); // footer s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr({ opacity: 1, display: 'block' }).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow, h: anchor[2] || 0 }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y || 0), // can be undefined (#3977) point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Get the best X date format based on the closest point range on the axis. */ getXDateFormat: function (point, options, xAxis) { var xDateFormat, dateTimeLabelFormats = options.dateTimeLabelFormats, closestPointRange = xAxis && xAxis.closestPointRange, n, blank = '01-01 00:00:00.000', strpos = { millisecond: 15, second: 12, minute: 9, hour: 6, day: 3 }, date, lastN = 'millisecond'; // for sub-millisecond data, #4223 if (closestPointRange) { date = dateFormat('%m-%d %H:%M:%S.%L', point.x); for (n in timeUnits) { // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek && date.substr(6) === blank.substr(6)) { n = 'week'; break; } // The first format that is too great for the range if (timeUnits[n] > closestPointRange) { n = lastN; break; } // If the point is placed every day at 23:59, we need to show // the minutes as well. #2637. if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) { break; } // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition if (n !== 'week') { lastN = n; } } if (n) { xDateFormat = dateTimeLabelFormats[n]; } } else { xDateFormat = dateTimeLabelFormats.day; } return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 }, /** * Format the footer/header of the tooltip * #3397: abstraction to enable formatting of footer and header */ tooltipFooterHeaderFormatter: function (labelConfig, isFooter) { var footOrHead = isFooter ? 'footer' : 'header', series = labelConfig.series, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(labelConfig.key), formatString = tooltipOptions[footOrHead + 'Format']; // Guess the best date format based on the closest point distance (#568, #3418) if (isDateTime && !xDateFormat) { xDateFormat = this.getXDateFormat(labelConfig, tooltipOptions, xAxis); } // Insert the footer date format if any if (isDateTime && xDateFormat) { formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(formatString, { point: labelConfig, series: series }); }, /** * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item, * abstracting this functionality allows to easily overwrite and extend it. */ bodyFormatter: function (items) { return map(items, function (item) { var tooltipOptions = item.series.tooltipOptions; return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat); }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc && doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = pick(options.tooltip.followTouchMove, true); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, shared = tooltip ? tooltip.shared : false, followPointer, updatePosition = true, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, anchor, noSharedTooltip, stickToHoverSeries, directTouch, kdpoints = [], kdpointT; // For hovering over the empty parts of the plot area (hoverSeries is undefined). // If there is one series with point tracking (combo chart), don't go to nearest neighbour. if (!shared && !hoverSeries) { for (i = 0; i < series.length; i++) { if (series[i].directTouch || !series[i].options.stickyTracking) { series = []; } } } // If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on // a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise, // search the k-d tree. stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch); if (stickToHoverSeries && hoverPoint) { kdpoints = [hoverPoint]; // Handle shared tooltip or cases where a series is not yet hovered } else { // When we have non-shared tooltip and sticky tracking is disabled, // search for the closest point only on hovered series: #5533, #5476 if (!shared && hoverSeries && !hoverSeries.options.stickyTracking) { series = [hoverSeries]; } // Find nearest points on all series each(series, function (s) { // Skip hidden series noSharedTooltip = s.noSharedTooltip && shared; directTouch = !shared && s.directTouch; if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821 kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828 if (kdpointT && kdpointT.series) { // Point.series becomes null when reset and before redraw (#5197) kdpoints.push(kdpointT); } } }); // Sort kdpoints by distance to mouse pointer kdpoints.sort(function (p1, p2) { var isCloserX = p1.distX - p2.distX, isCloser = p1.dist - p2.dist, isAbove = p1.series.group.zIndex > p2.series.group.zIndex ? -1 : 1; // We have two points which are not in the same place on xAxis and shared tooltip: if (isCloserX !== 0) { return isCloserX; } // Points are not exactly in the same place on x/yAxis: if (isCloser !== 0) { return isCloser; } // The same xAxis and yAxis position, sort by z-index: return isAbove; }); } // Remove points with different x-positions, required for shared tooltip and crosshairs (#4645): if (shared) { i = kdpoints.length; while (i--) { if (kdpoints[i].clientX !== kdpoints[0].clientX || kdpoints[i].series.noSharedTooltip) { kdpoints.splice(i, 1); } } } // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200 if (kdpoints[0] && (kdpoints[0] !== pointer.hoverPoint || (tooltip && tooltip.isHidden))) { // Draw tooltip if necessary if (shared && !kdpoints[0].series.noSharedTooltip) { // Do mouseover on all points (#3919, #3985, #4410) for (i = 0; i >= 0; i--) { kdpoints[i].onMouseOver(e, kdpoints[i] !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoints[0])); } // Make sure that the hoverPoint and hoverSeries are stored for events (e.g. click), #5622 if (hoverSeries && hoverSeries.directTouch && hoverPoint && hoverPoint !== kdpoints[0]) { hoverPoint.onMouseOver(e, false); } if (kdpoints.length && tooltip) { // Keep the order of series in tooltip: tooltip.refresh(kdpoints.sort(function (p1, p2) { return p1.series.index - p2.series.index; }), e); } } else { if (tooltip) { tooltip.refresh(kdpoints[0], e); } if (!hoverSeries || !hoverSeries.directTouch) { // #4448 kdpoints[0].onMouseOver(e); } } pointer.prevKDPoint = kdpoints[0]; updatePosition = false; } // Update positions (regardless of kdpoint or hoverPoint) if (updatePosition) { followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } } // Start the event listener to pick up the tooltip and crosshairs if (!pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Crosshair. For each hover point, loop over axes and draw cross if that point // belongs to the axis (#4927). each(shared ? kdpoints : [pick(hoverPoint, kdpoints[0])], function drawPointCrosshair(point) { // #5269 each(chart.axes, function drawAxisCrosshair(axis) { // In case of snap = false, point is undefined, and we draw the crosshair anyway (#5066) if (!point || point.series && point.series[axis.coll] === axis) { // #5658 axis.drawCrosshair(e, point); } }); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, hoverPoints = chart.hoverPoints, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint; // Check if the points have moved outside the plot area (#1003, #4736, #5101) if (allowMove && tooltipPoints) { each(splat(tooltipPoints), function (point) { if (point.series.isCartesian && point.plotX === undefined) { allowMove = false; } }); } // Just move the tooltip, #349 if (allowMove) { if (tooltip && tooltipPoints) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); each(chart.axes, function (axis) { if (axis.crosshair) { axis.drawCrosshair(null, hoverPoint); } }); } } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = pointer.prevKDPoint = chart.hoverPoints = chart.hoverPoint = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, selectionMarker = this.selectionMarker, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the device supports both touch and mouse (like IE11), and we are touch-dragging // inside the plot area, don't handle the mouse event. #4339. if (selectionMarker && selectionMarker.touch) { return; } // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!selectionMarker) { this.selectionMarker = selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (selectionMarker && zoomHor) { size = chartX - mouseDownX; selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (selectionMarker && zoomVert) { size = chartY - mouseDownY; selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var pointer = this, chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { originalEvent: e, // #4890 xAxis: [], yAxis: [] }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569 var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding : 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes max: mathMax(selectionMin, selectionMax) }); runZoom = true; } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function (e) { var chart = charts[hoverChartIndex]; if (chart && (e.relatedTarget || e.toElement)) { // #4886, MS Touch end fires mouseleave but with no related target chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; if (!defined(hoverChartIndex) || !charts[hoverChartIndex] || !charts[hoverChartIndex].mouseIsDown) { hoverChartIndex = chart.index; } e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement; if (series && relatedTarget && !series.options.stickyTracking && // #4886 !this.inClass(relatedTarget, PREFIX + 'tooltip') && !this.inClass(relatedTarget, PREFIX + 'series-' + series.index)) { // #2499, #4465 series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // Don't initiate panning until the user has pinched. This prevents us from // blocking page scrolling as users scroll down a long page (#4210). if (touchesLength > 1) { self.initiated = true; } // On touch devices, only proceed to trigger click if a handler is defined if (hasZoom && self.initiated && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop, touch: true }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && self.followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, /** * General touch handler shared by touchstart and touchmove. */ touch: function (e, start) { var chart = this.chart, hasMoved, pinchDown; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) { // Run mouse events and display tooltip etc if (start) { this.runPointActions(e); } // Android fires touchmove events after the touchstart even if the // finger hasn't moved, or moved only a pixel or two. In iOS however, // the touchmove doesn't fire unless the finger moves more than ~4px. // So we emulate this behaviour in Android by checking how much it // moved, and cancelling on small distances. #3450. if (e.type === 'touchmove') { pinchDown = this.pinchDown; hasMoved = pinchDown[0] ? Math.sqrt( // #5266 Math.pow(pinchDown[0].chartX - e.chartX, 2) + Math.pow(pinchDown[0].chartY - e.chartY, 2) ) >= 4 : false; } if (pick(hasMoved, true)) { this.pinch(e); } } else if (start) { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchStart: function (e) { this.touch(e, true); }, onContainerTouchMove: function (e) { this.touch(e); }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, func) { var p; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { func(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom) { // #4014 css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding, itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding = pick(options.padding, 8); legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox, legendGroup = item.legendGroup; if (legendGroup && legendGroup.element) { legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight, titleHeight = this.titleHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = translateY + titleHeight + checkbox.y + (scrollOffset || 0) + 3; css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Set the legend item text */ setText: function (item) { var options = this.options; item.legendItem.attr({ text: options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item) }); }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( '', ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li); legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // Colorize the items legend.colorizeItem(item, item.visible); // Always update the text legend.setText(item); // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line (#915, #3976) } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Adjust the chart margins by reserving space for the legend on only one side * of the chart. If the position is set to a corner, top or bottom is reserved * for horizontal legends and left or right for vertical ones. */ adjustMargins: function (margin, spacing) { var chart = this.chart, options = this.options, // Use the first letter of each alignment option in order to detect the side alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7 if (!options.floating) { each([ /(lth|ct|rth)/, /(rtv|rm|rbv)/, /(rbh|cb|lbh)/, /(lbv|lm|ltv)/ ], function (alignments, side) { if (alignments.test(alignment) && !defined(margin[side])) { // Now we have detected on which side of the chart we should reserve space for the legend chart[marginNames[side]] = mathMax( chart[marginNames[side]], chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] + pick(options.margin, 12) + spacing[side] ); } }); } }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items legend.lastLineHeight = 0; each(allItems, function (item) { legend.renderItem(item); }); // Get the box legendWidth = (options.width || legend.offsetWidth) + padding; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); legendHeight += padding; // Draw the border and/or background if (legendBorderWidth || legendBackgroundColor) { if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, padding = this.padding, lastY, allItems = this.allItems, clipToHeight = function (height) { clipRect.attr({ height: height }); // useHTML if (legend.contentGroup.div) { legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)'; } }; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && navOptions.enabled !== false) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipToHeight(clipHeight); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipToHeight(chart.chartHeight); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - symbolHeight + 1, // #3988 legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius, markerOptions ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The Chart class * @param {String|Object} renderTo The DOM element to render to, or its id * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ var Chart = Highcharts.Chart = function () { this.getArgs.apply(this, arguments); }; Highcharts.chart = function (a, b, c) { return new Chart(a, b, c); }; Chart.prototype = { /** * Hook for modules */ callbacks: [], /** * Handle the arguments passed to the constructor * @returns {Array} Arguments without renderTo */ getArgs: function () { var args = [].slice.call(arguments); // Remove the optional first argument, renderTo, and // set it on this. if (isString(args[0]) || args[0].nodeName) { this.renderTo = args.shift(); } this.init(args[0], args[1]); }, /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // Handle updated data in the series each(series, function (serie) { if (serie.isDirty) { if (serie.options.legendType === 'point') { if (serie.updateTotals) { serie.updateTotals(); } redrawLegend = true; } } if (serie.isDirtyData) { fireEvent(serie, 'updatedData'); } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.updateNames(); axis.setScale(); }); } } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set var key = axis.min + ',' + axis.max; if (axis.extKey !== key) { // #821, #4452 axis.extKey = key; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { new Axis(chart, axisOptions); // eslint-disable-line no-new }); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, spacingBox = this.spacingBox; if (title) { title .css({ width: (titleOptions.width || spacingBox.width + titleOptions.widthAdjust) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, spacingBox); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || spacingBox.width + subtitleOptions.widthAdjust) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(subtitleOptions.style.fontSize, title).b }, subtitleOptions), false, spacingBox); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // Get inner width and height if (!defined(widthOption)) { chart.containerWidth = getStyle(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = getStyle(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { while (clone.childNodes.length) { // #5231 this.renderTo.appendChild(clone.firstChild); } discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, options = chart.options, optionsChart = options.chart, chartWidth, chartHeight, renderTo = chart.renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, Ren, containerId = 'highcharts-' + idCounter++; if (!renderTo) { chart.renderTo = renderTo = optionsChart.renderTo; } if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (isNumber(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer Ren = Highcharts[optionsChart.renderer] || Renderer; chart.renderer = new Ren( container, chartWidth, chartHeight, optionsChart.style, optionsChart.forExport, options.exporting && options.exporting.allowHTML ); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } // Add a reference to the charts index chart.renderer.chartIndex = chart.index; }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function (skipAxes) { var chart = this, spacing = chart.spacing, margin = chart.margin, titleOffset = chart.titleOffset; chart.resetMargins(); // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend if (chart.legend.display) { chart.legend.adjustMargins(margin, spacing); } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } if (!skipAxes) { this.getAxisMargins(); } }, getAxisMargins: function () { var chart = this, axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left margin = chart.margin; // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { if (axis.visible) { axis.getOffset(); } }); } // Add the axis offsets each(marginNames, function (m, side) { if (!defined(margin[side])) { chart[m] += axisOffset[side]; } }); chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, hasUserWidth = defined(optionsChart.width), width = optionsChart.width || getStyle(renderTo, 'width'), height = optionsChart.height || getStyle(renderTo, 'height'), target = e ? e.target : win; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!hasUserWidth && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093 if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); // When called from window.resize, e is set, else it's called directly (#2224) chart.reflowTimeout = syncTimeout(function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(undefined, undefined, false); } }, e ? 100 : 0); } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, renderer = chart.renderer, globalAnimation; // Handle the isResizing counter chart.isResizing += 1; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (width !== undefined) { chart.options.chart.width = width; } if (height !== undefined) { chart.options.chart.height = height; } chart.getChartSize(); // Resize the container with the global animation applied if enabled (#2503) globalAnimation = renderer.globalAnimation; (globalAnimation ? animate : css)(chart.container, { width: chart.chartWidth + PX, height: chart.chartHeight + PX }, globalAnimation); chart.setChartSize(true); renderer.setSize(chart.chartWidth, chart.chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // Fire endResize and set isResizing back. If animation is disabled, fire without delay syncTimeout(function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }, animObject(globalAnimation).duration); }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this; each(marginNames, function (m, side) { chart[m] = pick(chart.margin[side], chart.spacing[side]); }); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.strokeWidth = -plotBorderWidth; plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }) //#3282 plotBorder should be negative ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo && linkedTo.linkedParent !== series) { // #3341 avoid mutual linking linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879 } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options, tempWidth, tempHeight, redoHorizontal, redoVertical; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); // Get stacks if (chart.getStacks) { chart.getStacks(); } // Get chart margins chart.getMargins(true); chart.setChartSize(); // Record preliminary dimensions for later comparison tempWidth = chart.plotWidth; tempHeight = chart.plotHeight = chart.plotHeight - 21; // 21 is the most common correction for X axis labels // Get margins by pre-rendering axes each(axes, function (axis) { axis.setScale(); }); chart.getAxisMargins(); // If the plot area size has changed significantly, calculate tick positions again redoHorizontal = tempWidth / chart.plotWidth > 1.1; redoVertical = tempHeight / chart.plotHeight > 1.05; // Height is more sensitive if (redoHorizontal || redoVertical) { chart.maxTicks = null; // reset for second pass each(axes, function (axis) { if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) { axis.setTickInterval(true); // update to reflect the new margins } }); chart.getMargins(); // second pass to check for new labels } // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { if (axis.visible) { axis.render(); } }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { win.location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: win == win.top is required if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { // eslint-disable-line eqeqeq if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Highcharts.Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // Fire the load event if there are no external images if (!chart.renderer.imgCount && chart.onload) { chart.onload(); } // If the chart was rendered outside the top container, put it back in (#3679) chart.cloneRenderTo(true); }, /** * On chart load */ onload: function () { var chart = this; // Run callbacks each([this.callback].concat(this.callbacks), function (fn) { if (fn && chart.index !== undefined) { // Chart destroyed in its own callback (#3600) fn.apply(chart, [chart]); } }); fireEvent(chart, 'load'); // Don't run again this.onload = null; }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = { /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), i, value; for (i = 0; i < 4; ++i) { value = positions[i]; handleSlicingRoom = i < 2 || (i === 2 && /%$/.test(value)); // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 3: innerSize, relative to size positions[i] = relativeLength(value, [plotWidth, plotHeight, smallestSize, positions[2]][i]) + (handleSlicingRoom ? slicingRoom : 0); } // innerSize cannot be larger than size (#3632) if (positions[3] > positions[2]) { positions[3] = positions[2]; } return positions; } }; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.color = series.color; // #3445 point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // Since options are copied into the Point instance, some accidental options must be shielded (#5681) if (options.group) { delete point.group; } // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } point.isNull = pick( point.isValid && !point.isValid(), point.x === null || !isNumber(point.y, true) ); // #3571, check for NaN // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if ('name' in point && x === undefined && series.xAxis && series.xAxis.hasNames) { point.x = series.xAxis.nameToX(point); } if (point.x === undefined && series) { if (x === undefined) { point.x = series.autoIncrement(point); } else { point.x = x; } } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (isNumber(options) || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (!keys && options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { if (!keys || options[i] !== undefined) { // Skip undefined positions for keys ret[pointArrayMap[j]] = options[i]; } i++; j++; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { return { x: this.category, y: this.y, color: this.color, key: this.name || this.category, series: this.series, point: this, percentage: this.percentage, total: this.total || this.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera if (point.select) { // Could be destroyed by prior event handlers (#2911) point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); } }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, visible: true }; /** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = Highcharts.Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, directTouch: false, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = isNumber(i) ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var options = this.options, xIncrement = this.xIncrement, date, pointInterval, pointIntervalUnit = options.pointIntervalUnit; xIncrement = pick(xIncrement, options.pointStart, 0); this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1); // Added code for pointInterval strings if (pointIntervalUnit) { date = new Date(xIncrement); if (pointIntervalUnit === 'day') { date = +date[setDate](date[getDate]() + pointInterval); } else if (pointIntervalUnit === 'month') { date = +date[setMonth](date[getMonth]() + pointInterval); } else if (pointIntervalUnit === 'year') { date = +date[setFullYear](date[getFullYear]() + pointInterval); } pointInterval = date - xIncrement; } this.xIncrement = xIncrement + pointInterval; return xIncrement; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options, zones; this.userOptions = itemOptions; // General series options take precedence over type options because otherwise, default // type options like column.animation would be overwritten by the general option. // But issues have been raised here (#3881), and the solution may be to distinguish // between default option and userOptions like in the tooltip below. options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } // Handle color zones this.zoneAxis = options.zoneAxis; zones = this.zones = (options.zones || []).slice(); if ((options.negativeColor || options.negativeFillColor) && !options.zones) { zones.push({ value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0, color: options.negativeColor, fillColor: options.negativeFillColor }); } if (zones.length) { // Push one extra zone for the rest if (defined(zones[zones.length - 1].value)) { zones.push({ color: this.color, fillColor: this.fillColor }); } } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (this.options.colorByPoint) { this.options.color = null; // #4359, selected slice got series.color even when colorByPoint was set. } else { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) { each(data, function (point, i) { // .update doesn't exist on a linked, hidden series (#3709) if (oldData[i].update && point !== options.data[i]) { oldData[i].update(point, false, null, false); } }); } else { // Reset properties series.xIncrement = null; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers for (i = 0; i < dataLength; i++) { xData[i] = this.autoIncrement(); yData[i] = data[i]; } } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = series.userOptions.data = data; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } // Typically for pie series, points need to be processed and generated // prior to rendering the legend if (options.legendType === 'point') { this.processData(); this.generatePoints(); } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599 isCartesian = series.isCartesian, xExtremes, val2lin = xAxis && xAxis.val2lin, isLog = xAxis && xAxis.isLog, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points i = processedXData.length || 1; while (--i) { distance = isLog ? val2lin(processedXData[i]) - val2lin(processedXData[i - 1]) : processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i, j; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (j = i; j < dataLength; j++) { if (xData[j] > max) { cropEnd = j + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); points[i].dataGroup = series.groupMap[i]; } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, x, y, i, j; yData = yData || this.stackedYData || this.processedYData || []; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = (isNumber(y, true) || isArray(y)) && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = arrayMin(activeYData); this.dataMax = arrayMax(activeYData); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold, stackThreshold = options.startFromThreshold ? threshold : 0, plotX, plotY, lastPlotX, stackIndicator, closestPointRangePx = Number.MAX_VALUE; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes (#3434) if (yAxis.isLog && yValue !== null && yValue <= 0) { point.isNull = true; } // Get the plotX translation point.plotX = plotX = correctFloat( // #5236 mathMin(mathMax(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5) // #3923 ); // Calculate the bottom y value for stacked series if (stacking && series.visible && !point.isNull && stack && stack[xValue]) { stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index); pointStack = stack[xValue]; stackValues = pointStack.points[stackIndicator.key]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === stackThreshold && stackIndicator.key === stack[xValue].base) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ? mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201 UNDEFINED; point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519 plotX >= 0 && plotX <= xAxis.len; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? correctFloat(xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement)) : plotX; // #1514, #5383, #5518 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; // Determine auto enabling of markers (#3635, #5099) if (!point.isNull) { if (lastPlotX !== undefined) { closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX)); } lastPlotX = plotX; } } series.closestPointRangePx = closestPointRangePx; }, /** * Return the series points with null points filtered out */ getValidPoints: function (points, insideOnly) { var chart = this.chart; return grep(points || this.points || [], function isValidPoint(point) { // #3916, #5029 if (insideOnly && !chart.isInsidePlot(point.plotX, point.plotY, chart.inverted)) { // #5085 return false; } return !point.isNull; }); }, /** * Set the clipping for the series. For animated series it is called twice, first to initiate * animating the clip then the second time without the animation to set the final clip. */ setClip: function (animation) { var chart = this.chart, options = this.options, renderer = chart.renderer, inverted = chart.inverted, seriesClipBox = this.clipBox, clipBox = seriesClipBox || chart.clipBox, sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526 clipRect = chart[sharedClipKey], markerClipRect = chart[sharedClipKey + 'm']; // If a clipping rectangle with the same properties is currently present in the chart, use that. if (!clipRect) { // When animation is set, prepare the initial positions if (animation) { clipBox.width = 0; chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox); // Create hashmap for series indexes clipRect.count = { length: 0 }; } if (animation) { if (!clipRect.count[this.index]) { clipRect.count[this.index] = true; clipRect.count.length += 1; } } if (options.clip !== false) { this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect); this.markerGroup.clip(markerClipRect); this.sharedClipKey = sharedClipKey; } // Remove the shared clipping rectangle when all series are shown if (!animation) { if (clipRect.count[this.index]) { delete clipRect.count[this.index]; clipRect.count.length -= 1; } if (clipRect.count.length === 0 && sharedClipKey && chart[sharedClipKey]) { if (!seriesClipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } } }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, clipRect, animation = animObject(series.options.animation), sharedClipKey; // Initialize the animation. Set up the clipping rectangle. if (init) { series.setClip(animation); // Run the animation } else { sharedClipKey = this.sharedClipKey; clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { this.setClip(); fireEvent(this, 'afterAnimate'); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, xAxis = series.xAxis, globallyEnabled = pick( seriesMarkerOptions.enabled, xAxis.isRadial, series.closestPointRangePx > 2 * seriesMarkerOptions.radius ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = point.isInside; // only draw the point if y is defined if (enabled && isNumber(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .attr(pointAttr) // #4759 .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, seriesNegativeColor = series.options.negativeColor, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, j, threshold, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, zones = series.zones, zoneAxis = series.zoneAxis || 'y', zoneColor, attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = +stateOptionsHover.radius || +normalOptions.radius + +stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); // if no hover negativeColor is given, brighten the normal negativeColor stateOptionsHover.negativeColor = stateOptionsHover.negativeColor || Color(stateOptionsHover.negativeColor || seriesNegativeColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } zoneColor = null; if (zones.length) { j = 0; threshold = zones[j]; while (point[zoneAxis] >= threshold.value) { threshold = zones[++j]; } point.color = point.fillColor = zoneColor = pick(threshold.color, series.color); // #3636, #4267, #4430 - inherit color from series, when color is undefined } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker || (point.negative && !pointStateOptionsHover.fillColor && !stateOptionsHover.fillColor)) { // column, bar, point or negative threshold for series with markers (#3636) // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover[series.pointAttrToOptions.fill] = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } // Color is explicitly set to null or undefined (#1288, #4068) if (normalOptions.hasOwnProperty('color') && !normalOptions.color) { delete normalOptions.color; } // When zone is set, but series.states.hover.color is not set, apply zone color on hover, #4670: if (zoneColor && !stateOptionsHover.fillColor) { pointStateOptionsHover.fillColor = zoneColor; } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // Destroy all SVGElements associated to the series for (prop in series) { if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } } // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Get the graph path */ getGraphPath: function (points, nullsAsZeroes, connectCliffs) { var series = this, options = series.options, step = options.step, reversed, graphPath = [], xMap = [], gap; points = points || series.points; // Bottom of a stack is reversed reversed = points.reversed; if (reversed) { points.reverse(); } // Reverse the steps (#5004) step = { right: 1, center: 2 }[step] || (step && 3); if (step && reversed) { step = 4 - step; } // Remove invalid points, especially in spline (#5015) if (options.connectNulls && !nullsAsZeroes && !connectCliffs) { points = this.getValidPoints(points); } // Build the line each(points, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint = points[i - 1], pathToPoint; // the path to this point from the previous if ((point.leftCliff || (lastPoint && lastPoint.rightCliff)) && !connectCliffs) { gap = true; // ... and continue } // Line series, nullsAsZeroes is not handled if (point.isNull && !defined(nullsAsZeroes) && i > 0) { gap = !options.connectNulls; // Area series, nullsAsZeroes is set } else if (point.isNull && !nullsAsZeroes) { gap = true; } else { if (i === 0 || gap) { pathToPoint = [M, point.plotX, point.plotY]; } else if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object pathToPoint = series.getPointSpline(points, point, i); } else if (step) { if (step === 1) { // right pathToPoint = [ L, lastPoint.plotX, plotY ]; } else if (step === 2) { // center pathToPoint = [ L, (lastPoint.plotX + plotX) / 2, lastPoint.plotY, L, (lastPoint.plotX + plotX) / 2, plotY ]; } else { pathToPoint = [ L, plotX, lastPoint.plotY ]; } pathToPoint.push(L, plotX, plotY); } else { // normal line to next point pathToPoint = [ L, plotX, plotY ]; } // Prepare for animation. When step is enabled, there are two path nodes for each x value. xMap.push(point.x); if (step) { xMap.push(point.x); } graphPath.push.apply(graphPath, pathToPoint); gap = false; } }); graphPath.xMap = xMap; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color, options.dashStyle]], lineWidth = options.lineWidth, roundCap = options.linecap !== 'square', graphPath = (this.gappedPath || this.getGraphPath).call(this), zones = this.zones; each(zones, function (threshold, i) { props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]); }); // Draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { graph.endX = graphPath.xMap; graph.animate({ d: graphPath }); } else if (lineWidth && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: 'none', zIndex: 1 // #1069 }; if (prop[2]) { attribs.dashstyle = prop[2]; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } graph = series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932 } // Helpers for animation if (graph) { graph.startX = graphPath.xMap; //graph.shiftUnit = options.step ? 2 : 1; graph.isArea = graphPath.isArea; // For arearange animation } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ applyZones: function () { var series = this, chart = this.chart, renderer = chart.renderer, zones = this.zones, translatedFrom, translatedTo, clips = this.clips || [], clipAttr, graph = this.graph, area = this.area, chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight), axis = this[(this.zoneAxis || 'y') + 'Axis'], extremes, reversed, inverted = chart.inverted, horiz, pxRange, pxPosMin, pxPosMax, ignoreZones = false; if (zones.length && (graph || area) && axis && axis.min !== UNDEFINED) { reversed = axis.reversed; horiz = axis.horiz; // The use of the Color Threshold assumes there are no gaps // so it is safe to hide the original graph and area if (graph) { graph.hide(); } if (area) { area.hide(); } // Create the clips extremes = axis.getExtremes(); each(zones, function (threshold, i) { translatedFrom = reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(extremes.min)); translatedFrom = mathMin(mathMax(pick(translatedTo, translatedFrom), 0), chartSizeMax); translatedTo = mathMin(mathMax(mathRound(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax); if (ignoreZones) { translatedFrom = translatedTo = axis.toPixels(extremes.max); } pxRange = Math.abs(translatedFrom - translatedTo); pxPosMin = mathMin(translatedFrom, translatedTo); pxPosMax = mathMax(translatedFrom, translatedTo); if (axis.isXAxis) { clipAttr = { x: inverted ? pxPosMax : pxPosMin, y: 0, width: pxRange, height: chartSizeMax }; if (!horiz) { clipAttr.x = chart.plotHeight - clipAttr.x; } } else { clipAttr = { x: 0, y: inverted ? pxPosMax : pxPosMin, width: chartSizeMax, height: pxRange }; if (horiz) { clipAttr.y = chart.plotWidth - clipAttr.y; } } /// VML SUPPPORT if (inverted && renderer.isVML) { if (axis.isXAxis) { clipAttr = { x: 0, y: reversed ? pxPosMin : pxPosMax, height: clipAttr.width, width: chart.chartWidth }; } else { clipAttr = { x: clipAttr.y - chart.plotLeft - chart.spacingBox.x, y: 0, width: clipAttr.height, height: chart.chartHeight }; } } /// END OF VML SUPPORT if (clips[i]) { clips[i].animate(clipAttr); } else { clips[i] = renderer.clipRect(clipAttr); if (graph) { series['zoneGraph' + i].clip(clips[i]); } if (area) { series['zoneArea' + i].clip(clips[i]); } } // if this zone extends out of the axis, ignore the others ignoreZones = threshold.value > extremes.max; }); this.clips = clips; } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ zIndex: zIndex || 0.1 // IE8 and pointer logic use this }) .add(parent); group.addClass('highcharts-series-' + this.index); } // Place it on first and subsequent (redraw) calls group.attr({ visibility: visibility })[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = !!series.animate && chart.renderer.isSVG && animObject(options.animation).duration, visibility = series.visible ? 'inherit' : 'hidden', // #2597 zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.applyZones(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839). if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { series.animationTimeout = syncTimeout(function () { series.afterAnimate(); }, animDuration); } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirty = series.isDirty || series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.render(); if (wasDirty) { // #3868, #3945 delete this.kdTree; } }, /** * KD Tree && PointSearching Implementation */ kdDimensions: 1, kdAxisArray: ['clientX', 'plotY'], searchPoint: function (e, compareX) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, inverted = series.chart.inverted; return this.searchKDTree({ clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos, plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos }, compareX); }, buildKDTree: function () { var series = this, dimensions = series.kdDimensions; // Internal function function _kdtree(points, depth, dimensions) { var axis, median, length = points && points.length; if (length) { // alternate between the axis axis = series.kdAxisArray[depth % dimensions]; // sort point array points.sort(function (a, b) { return a[axis] - b[axis]; }); median = Math.floor(length / 2); // build and return nod return { point: points[median], left: _kdtree(points.slice(0, median), depth + 1, dimensions), right: _kdtree(points.slice(median + 1), depth + 1, dimensions) }; } } // Start the recursive build process with a clone of the points array and null points filtered out (#3873) function startRecursive() { series.kdTree = _kdtree( series.getValidPoints( null, !series.directTouch // For line-type series restrict to plot area, but column-type series not (#3916, #4511) ), dimensions, dimensions ); } delete series.kdTree; // For testing tooltips, don't build async syncTimeout(startRecursive, series.options.kdNow ? 0 : 1); }, searchKDTree: function (point, compareX) { var series = this, kdX = this.kdAxisArray[0], kdY = this.kdAxisArray[1], kdComparer = compareX ? 'distX' : 'dist'; // Set the one and two dimensional distance on the point object function setDistance(p1, p2) { var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null, y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null, r = (x || 0) + (y || 0); p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE; p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE; } function _search(search, tree, depth, dimensions) { var point = tree.point, axis = series.kdAxisArray[depth % dimensions], tdist, sideA, sideB, ret = point, nPoint1, nPoint2; setDistance(search, point); // Pick side based on distance to splitting point tdist = search[axis] - point[axis]; sideA = tdist < 0 ? 'left' : 'right'; sideB = tdist < 0 ? 'right' : 'left'; // End of tree if (tree[sideA]) { nPoint1 = _search(search, tree[sideA], depth + 1, dimensions); ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point); } if (tree[sideB]) { // compare distance to current best to splitting point to decide wether to check side B or not if (Math.sqrt(tdist * tdist) < ret[kdComparer]) { nPoint2 = _search(search, tree[sideB], depth + 1, dimensions); ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret); } } return ret; } if (!this.kdTree) { this.buildKDTree(); } if (this.kdTree) { return _search(point, this.kdTree, this.kdDimensions, this.kdDimensions); } } }; // end Series prototype /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Initialize total value this.total = null; // This will keep each points' extremes stored by series.index and point index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; this.leftCliff = 0; this.rightCliff = 0; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({ text: str, visibility: 'hidden' }); // Create new label } else { this.label = this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, reversed = axis.reversed, neg = (this.isNegative && !reversed) || (!this.isNegative && reversed), // #4056 y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true); } } }; /** * Generate stacks for each series and calculate stacks total values */ Chart.prototype.getStacks = function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }; // Stacking methods defined on the Axis prototype /** * Build the stacks from top down */ Axis.prototype.buildStacks = function () { var axisSeries = this.series, series, reversedStacks = pick(this.options.reversedStacks, true), len = axisSeries.length, i; if (!this.isXAxis) { this.usePercentage = false; i = len; while (i--) { axisSeries[reversedStacks ? i : len - i - 1].setStackedPoints(); } i = len; while (i--) { series = axisSeries[reversedStacks ? i : len - i - 1]; if (series.setStackCliffs) { series.setStackCliffs(); } } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < len; i++) { axisSeries[i].setPercentStacks(); } } } }; Axis.prototype.renderStackTotals = function () { var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } }; /** * Set all the stacks to initial states and destroy unused ones. */ Axis.prototype.resetStacks = function () { var stacks = this.stacks, type, i; if (!this.isXAxis) { for (type in stacks) { for (i in stacks[type]) { // Clean up memory after point deletion (#1044, #4320) if (stacks[type][i].touched < this.stacksTouched) { stacks[type][i].destroy(); delete stacks[type][i]; // Reset stacks } else { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } } }; Axis.prototype.cleanStacks = function () { var stacks, type, i; if (!this.isXAxis) { if (this.oldStacks) { stacks = this.stacks = this.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } }; // Stacking methods defnied for Series prototype /** * Adds series' points value to corresponding stack */ Series.prototype.setStackedPoints = function () { if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) { return; } var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackThreshold = seriesOptions.startFromThreshold ? threshold : 0, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, stackIndicator, isNegative, stack, other, key, pointKey, i, x, y; yAxis.stacksTouched += 1; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; stackIndicator = series.getStackIndicator(stackIndicator, x, series.index); pointKey = stackIndicator.key; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) isNegative = negStacks && y < (stackThreshold ? 0 : threshold); key = isNegative ? negKey : stackKey; // Create empty object for this stack if it doesn't exist yet if (!stacks[key]) { stacks[key] = {}; } // Initialize StackItem for this x if (!stacks[key][x]) { if (oldStacks[key] && oldStacks[key][x]) { stacks[key][x] = oldStacks[key][x]; stacks[key][x].total = null; } else { stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; if (y !== null) { stack.points[pointKey] = stack.points[series.index] = [pick(stack.cum, stackThreshold)]; // Record the base of the stack if (!defined(stack.cum)) { stack.base = pointKey; } stack.touched = yAxis.stacksTouched; // In area charts, if there are multiple points on the same X value, let the // area fill the full span of those points if (stackIndicator.index > 0 && series.singleStacks === false) { stack.points[pointKey][0] = stack.points[series.index + ',' + x + ',0'][0]; } } // Add value to the stack total if (stacking === 'percent') { // Percent stacked column, totals are the same for the positive and negative stacks other = isNegative ? stackKey : negKey; if (negStacks && stacks[other] && stacks[other][x]) { other = stacks[other][x]; stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0; // Percent stacked areas } else { stack.total = correctFloat(stack.total + (mathAbs(y) || 0)); } } else { stack.total = correctFloat(stack.total + (y || 0)); } stack.cum = pick(stack.cum, stackThreshold) + (y || 0); if (y !== null) { stack.points[pointKey].push(stack.cum); stackedYData[i] = stack.cum; } } if (stacking === 'percent') { yAxis.usePercentage = true; } this.stackedYData = stackedYData; // To be used in getExtremes // Reset old stacks yAxis.oldStacks = {}; }; /** * Iterate over all stacks and compute the absolute values to percent */ Series.prototype.setPercentStacks = function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData, stackIndicator; each([stackKey, '-' + stackKey], function (key) { var i = processedXData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = processedXData[i]; stackIndicator = series.getStackIndicator(stackIndicator, x, series.index); stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[stackIndicator.key]; if (pointExtremes) { totalFactor = stack.total ? 100 / stack.total : 0; pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value series.stackedYData[i] = pointExtremes[1]; } } }); }; /** * Get stack indicator, according to it's x-value, to determine points with the same x-value */ Series.prototype.getStackIndicator = function (stackIndicator, x, index) { if (!defined(stackIndicator) || stackIndicator.x !== x) { stackIndicator = { x: x, index: 0 }; } else { stackIndicator.index++; } stackIndicator.key = [index, x, stackIndicator.index].join(','); return stackIndicator; }; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, userOptions = merge(options, { index: this[key].length, isX: isX }); new Axis(this, userOptions); // eslint-disable-line no-new // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(userOptions); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (point.y === null && graphic) { // #4146 point.graphic = graphic.destroy(); } if (isObject(options, true)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic && graphic.element) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); // Record the options to options.data. If there is an object from before, // use point options, otherwise use raw options. (#4701) seriesOptions.data[i] = isObject(seriesOptions.data[i], true) ? point.options : options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.isDirtyLegend = true; } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { this.series.removePoint(inArray(this, this.series.data), redraw, animation); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, chart = series.chart, names = series.xAxis && series.xAxis.names, dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, i, x; // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(animation); // Animation is set anyway on redraw, #5665 } }, /** * Remove a point (rendered or not), by index */ removePoint: function (i, redraw, animation) { var series = this, data = series.data, point = data[i], points = series.points, chart = series.chart, remove = function () { if (points && points.length === data.length) { // #4935 points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point || { series: series }, 'splice', i, 1); if (point) { point.destroy(); } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }; setAnimation(animation, chart); redraw = pick(redraw, true); // Fire the event with a default handler of removing the point if (point) { point.firePointEvent('remove', null, remove); } else { remove(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation, withEvent) { var series = this, chart = series.chart; function remove() { // Destroy elements series.destroy(); // Redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (pick(redraw, true)) { chart.redraw(animation); } } // Fire the event with a default handler of removing the point if (withEvent !== false) { fireEvent(series, 'remove', null, remove); } else { remove(); } }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // If we're changing type or zIndex, create new groups (#3380, #3404) if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) { preserve.length = 0; } // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and delete all properties. Reinsert all methods // and properties from the new type prototype (#2270, #3719) this.remove(false, null, false); for (n in proto) { this[n] = UNDEFINED; } extend(this, seriesTypes[newOptions.type || oldType].prototype); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { softThreshold: false, threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', singleStacks: false, /** * Return an array of stacked points, where null and missing points are replaced by * dummy points in order for gaps to be drawn correctly in stacks. */ getStackPoints: function () { var series = this, segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, points = this.points, seriesIndex = series.index, yAxisSeries = yAxis.series, seriesLength = yAxisSeries.length, visibleSeries, upOrDown = pick(yAxis.options.reversedStacks, true) ? 1 : -1, i, x; if (this.options.stacking) { // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336) keys.push(x); } } keys.sort(function (a, b) { return a - b; }); visibleSeries = map(yAxisSeries, function () { return this.visible; }); each(keys, function (x, idx) { var y = 0, stackPoint, stackedValues; if (pointMap[x] && !pointMap[x].isNull) { segment.push(pointMap[x]); // Find left and right cliff. -1 goes left, 1 goes right. each([-1, 1], function (direction) { var nullName = direction === 1 ? 'rightNull' : 'leftNull', cliffName = direction === 1 ? 'rightCliff' : 'leftCliff', cliff = 0, otherStack = stack[keys[idx + direction]]; // If there is a stack next to this one, to the left or to the right... if (otherStack) { i = seriesIndex; while (i >= 0 && i < seriesLength) { // Can go either up or down, depending on reversedStacks stackPoint = otherStack.points[i]; if (!stackPoint) { // If the next point in this series is missing, mark the point // with point.leftNull or point.rightNull = true. if (i === seriesIndex) { pointMap[x][nullName] = true; // If there are missing points in the next stack in any of the // series below this one, we need to substract the missing values // and add a hiatus to the left or right. } else if (visibleSeries[i]) { stackedValues = stack[x].points[i]; if (stackedValues) { cliff -= stackedValues[1] - stackedValues[0]; } } } // When reversedStacks is true, loop up, else loop down i += upOrDown; } } pointMap[x][cliffName] = cliff; }); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { // Loop down the stack to find the series below this one that has // a value (#1991) i = seriesIndex; while (i >= 0 && i < seriesLength) { stackPoint = stack[x].points[i]; if (stackPoint) { y = stackPoint[1]; break; } // When reversedStacks is true, loop up, else loop down i += upOrDown; } y = yAxis.toPixels(y, true); segment.push({ isNull: true, plotX: xAxis.toPixels(x, true), plotY: y, yBottom: y }); } }); } return segment; }, getGraphPath: function (points) { var getGraphPath = Series.prototype.getGraphPath, graphPath, options = this.options, stacking = options.stacking, yAxis = this.yAxis, topPath, //topPoints = [], bottomPath, bottomPoints = [], graphPoints = [], seriesIndex = this.index, i, areaPath, plotX, stacks = yAxis.stacks[this.stackKey], threshold = options.threshold, translatedThreshold = yAxis.getThreshold(options.threshold), isNull, yBottom, connectNulls = options.connectNulls || stacking === 'percent', /** * To display null points in underlying stacked series, this series graph must be * broken, and the area also fall down to fill the gap left by the null point. #2069 */ addDummyPoints = function (i, otherI, side) { var point = points[i], stackedValues = stacking && stacks[point.x].points[seriesIndex], nullVal = point[side + 'Null'] || 0, cliffVal = point[side + 'Cliff'] || 0, top, bottom, isNull = true; if (cliffVal || nullVal) { top = (nullVal ? stackedValues[0] : stackedValues[1]) + cliffVal; bottom = stackedValues[0] + cliffVal; isNull = !!nullVal; } else if (!stacking && points[otherI] && points[otherI].isNull) { top = bottom = threshold; } // Add to the top and bottom line of the area if (top !== undefined) { graphPoints.push({ plotX: plotX, plotY: top === null ? translatedThreshold : yAxis.getThreshold(top), isNull: isNull }); bottomPoints.push({ plotX: plotX, plotY: bottom === null ? translatedThreshold : yAxis.getThreshold(bottom), doCurve: false // #1041, gaps in areaspline areas }); } }; // Find what points to use points = points || this.points; // Fill in missing points if (stacking) { points = this.getStackPoints(); } for (i = 0; i < points.length; i++) { isNull = points[i].isNull; plotX = pick(points[i].rectPlotX, points[i].plotX); yBottom = pick(points[i].yBottom, translatedThreshold); if (!isNull || connectNulls) { if (!connectNulls) { addDummyPoints(i, i - 1, 'left'); } if (!(isNull && !stacking && connectNulls)) { // Skip null point when stacking is false and connectNulls true graphPoints.push(points[i]); bottomPoints.push({ x: i, plotX: plotX, plotY: yBottom }); } if (!connectNulls) { addDummyPoints(i, i + 1, 'right'); } } } topPath = getGraphPath.call(this, graphPoints, true, true); bottomPoints.reversed = true; bottomPath = getGraphPath.call(this, bottomPoints, true, true); if (bottomPath.length) { bottomPath[0] = L; } areaPath = topPath.concat(bottomPath); graphPath = getGraphPath.call(this, graphPoints, false, connectNulls); // TODO: don't set leftCliff and rightCliff when connectNulls? areaPath.xMap = topPath.xMap; this.areaPath = areaPath; return graphPath; }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, zones = this.zones, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color each(zones, function (threshold, i) { props.push(['zoneArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]); }); each(props, function (prop) { var areaKey = prop[0], area = series[areaKey], attr; // Create or update the area if (area) { // update area.endX = areaPath.xMap; area.animate({ d: areaPath }); } else { // create attr = { fill: prop[2] || prop[1], zIndex: 0 // #1069 }; if (!prop[2]) { attr['fill-opacity'] = pick(options.fillOpacity, 0.75); } area = series[areaKey] = series.chart.renderer.path(areaPath) .attr(attr) .add(series.group); area.isArea = true; } area.startX = areaPath.xMap; area.shiftUnit = options.step ? 2 : 1; }); }, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.area = AreaSeries; /** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (points, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = points[i - 1], nextPoint = points[i + 1], leftContX, leftContY, rightContX, rightContY, ret; function doCurve(otherPoint) { return otherPoint && !otherPoint.isNull && otherPoint.doCurve !== false; } // Find control points if (doCurve(lastPoint) && doCurve(nextPoint)) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction = 0; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // Have the two control points make a straight line through main point if (rightContX !== leftContX) { // #5016, division by zero correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; } leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 2, fill: 'none', zIndex: 9 }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 2, zIndex: 9 }) .add(); } if (rightContX) { this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 2, fill: 'none', zIndex: 9 }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 2, zIndex: 9 }) .add(); } // */ ret = [ 'C', pick(lastPoint.rightContX, lastPoint.plotX), pick(lastPoint.rightContY, lastPoint.plotY), pick(leftContX, plotX), pick(leftContY, plotY), plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', getStackPoints: areaProto.getStackPoints, getGraphPath: areaProto.getGraphPath, setStackCliffs: areaProto.setStackCliffs, drawGraph: areaProto.drawGraph, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', //borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, softThreshold: false, startFromThreshold: true, // false doesn't work well: http://jsfiddle.net/highcharts/hz8fopan/14/ stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis, columnIndex; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, pointWidth = mathMin( options.maxPointWidth || xAxis.len, pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding)) ), pointPadding = (pointOffsetWidth - pointWidth) / 2, colIndex = (series.columnIndex || 0) + (reversedXAxis ? 1 : 0), // #1251, #3737 pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) series.columnMetrics = { width: pointWidth, offset: pointXOffset }; return series.columnMetrics; }, /** * Make the columns crisp. The edges are rounded to the nearest full pixel. */ crispCol: function (x, y, w, h) { var chart = this.chart, borderWidth = this.borderWidth, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1, right, bottom, fromTop; if (chart.inverted && chart.renderer.isVML) { yCrisp += 1; } // Horizontal. We need to first compute the exact right edge, then round it // and compute the width from there. right = Math.round(x + w) + xCrisp; x = Math.round(x) + xCrisp; w = right - x; // Vertical bottom = Math.round(y + h) + yCrisp; fromTop = mathAbs(y) <= 0.5 && bottom > 0.5; // #4504, #4656 y = Math.round(y) + yCrisp; h = bottom - y; // Top edges are exceptions if (fromTop && h) { // #5146 y -= 1; h += 1; } return { x: x, y: y, width: w, height: h }; }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset; if (chart.inverted) { translatedThreshold -= 0.5; // #3355 } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function (point) { var yBottom = mathMin(pick(point.yBottom, translatedThreshold), 9e4), // #3575 safeDistance = 999 + mathAbs(yBottom), plotY = mathMin(mathMax(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), up, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative); barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (up ? minPointLength : 0); // #1485, #4051 } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216, #424, #3648) point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH]; // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = series.crispCol.apply( series, point.isNull ? [point.plotX, yAxis.len / 2, 0, 0] : // #3169, drilldown from null must have a position to work from [barX, barY, barW, barH] ); }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (isNumber(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr).attr(pointAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); // #4267 } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(borderAttr) .attr(pointAttr) .add(point.group || series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, extend(animObject(series.options.animation), { // Do the scale synchronously to ensure smooth updating (#5030) step: function (val, fx) { series.group.attr({ scaleY: mathMax(0.001, fx.pos) // #5250 }); } })); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, marker: { enabled: true // Overrides auto-enabling in line series (#3647) }, tooltip: { headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' } }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 kdDimensions: 2, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { // #2945 return this.y === null ? undefined : this.point.name; }, // softConnector: true, x: 0 // y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; point.name = pick(point.name, 'Slice'); // add event listener for select toggleSlice = function (e) { point.slice(e.type === 'select'); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis, redraw) { var point = this, series = point.series, chart = series.chart, ignoreHiddenPoint = series.options.ignoreHiddenPoint; redraw = pick(redraw, ignoreHiddenPoint); if (vis !== point.visible) { // If called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data // Show and hide associated elements. This is performed regardless of redraw or not, // because chart.redraw only handles full series. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][vis ? 'show' : 'hide'](true); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // #4170, hide halo after hiding point if (!vis && point.state === 'hover') { point.setState(''); } // Handle ignore hidden slices if (ignoreHiddenPoint) { series.isDirty = true; } if (redraw) { chart.redraw(); } } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } }, haloPath: function (size) { var shapeArgs = this.shapeArgs, chart = this.series.chart; return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, { innerR: this.shapeArgs.r, start: shapeArgs.start, end: shapeArgs.end }); } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, directTouch: true, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], axisTypes: [], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: point.startR || (series.center[3] / 2), // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Recompute total chart sum and update percentages of points. */ updateTotals: function () { var i, total = 0, points = this.points, len = points.length, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; // Get the total sum for (i = 0; i < len; i++) { point = points[i]; // Disallow negative values (#1530, #3623, #5322) if (point.y < 0) { point.y = null; } total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } this.total = total; // Set each point's properties for (i = 0; i < len; i++) { point = points[i]; point.percentage = (total > 0 && (point.visible || !ignoreHiddenPoint)) ? point.y / total * 100 : 0; point.total = total; } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { Series.prototype.generatePoints.call(this); this.updateTotals(); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngle = options.startAngle || 0, startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90), endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90), circ = endAngleRad - startAngleRad, //2 * mathPI, points = series.points, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle start = startAngleRad + (cumulative * circ); if (!ignoreHiddenPoint || point.visible) { cumulative += point.percentage / 100; } end = startAngleRad + (cumulative * circ); // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: mathRound(start * precision) / precision, end: mathRound(end * precision) / precision }; // The angle must stay within -90 and 270 (#2645) angle = (end + start) / 2; if (angle > 1.5 * mathPI) { angle -= 2 * mathPI; } else if (angle < -mathPI / 2) { angle += 2 * mathPI; } // Center for the sliced out slice point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; } }, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, pointAttr, shapeArgs, attr; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { if (point.y !== null) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]; if (!pointAttr.stroke) { pointAttr.stroke = pointAttr.fill; } // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic .setRadialReference(series.center) .attr(pointAttr) .animate(extend(shapeArgs, groupTranslation)); } else { attr = { 'stroke-linejoin': 'round' }; if (!point.visible) { attr.visibility = 'hidden'; } point.graphic = graphic = renderer[point.shapeType](shapeArgs) .setRadialReference(series.center) .attr(pointAttr) .attr(attr) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } } }); }, searchPoint: noop, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Use a simple symbol from LegendSymbolMixin */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Use the getCenter method from drawLegendSymbol */ getCenter: CenteredSeriesMixin.getCenter, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup, defer = pick(options.defer, true), renderer = series.chart.renderer; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', defer && !hasRendered ? 'hidden' : 'visible', // #5133 options.zIndex || 6 ); if (defer) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #2597, #3023, #3024 dataLabelsGroup.show(true); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true, style, moreStyle = {}; // Determine if each data label is enabled pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled) && point.y !== null; // #2282, #4641 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); style = options.style; rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color style.color = pick(options.color, style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Get automated contrast color if (style.color === 'contrast') { moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ? renderer.getContrast(point.color || series.color) : '#000000'; } if (cursor) { moreStyle.cursor = cursor; } // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -9999, options.shape, null, null, options.useHTML ) .attr(attr) .css(extend(style, moreStyle)) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -9999), plotY = pick(point.plotY, -9999), bBox = dataLabel.getBBox(), baseline = chart.renderer.fontMetrics(options.style.fontSize).b, rotation = options.rotation, normRotation, negRotation, align = options.align, rotCorr, // rotation correction // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr, // the final position; justify = pick(options.overflow, 'justify') === 'justify'; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (rotation) { justify = false; // Not supported for rotated text rotCorr = chart.renderer.rotCorr(baseline, rotation); // #3723 alignAttr = { x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x, y: alignTo.y + options.y + { top: 0, middle: 0.5, bottom: 1 }[options.verticalAlign] * alignTo.height }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr) .attr({ // #3003 align: align }); // Compensate for the rotated label sticking out on the sides normRotation = (rotation + 720) % 360; negRotation = normRotation > 180 && normRotation < 360; if (align === 'left') { alignAttr.y -= negRotation ? bBox.height : 0; } else if (align === 'center') { alignAttr.x -= bBox.width / 2; alignAttr.y -= bBox.height / 2; } else if (align === 'right') { alignAttr.x -= bBox.width; alignAttr.y -= negRotation ? 0 : bBox.height; } } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; } // Handle justify or crop if (justify) { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); // Now check that the data label is within the plot area } else if (pick(options.crop, true)) { visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } // When we're using a shape, make it possible with a connector or an arrow pointing to thie point if (options.shape && !rotation) { dataLabel.attr({ anchorX: point.plotX, anchorY: point.plotY }); } } // Show or hide based on the final aligned position if (!visible) { stop(dataLabel); dataLabel.attr({ y: -9999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified, padding = dataLabel.box ? 0 : (dataLabel.padding || 0); // Off left off = alignAttr.x + padding; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width - padding; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y + padding; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height - padding; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 // Arrange points for detection collision halves[point.half].push(point); // Reset positions (#4905) point.dataLabel._pos = null; } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (isNumber(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : 'inherit'; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = mathMin(mathMax(0, naturalY), chart.plotHeight); } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos && point.visible) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel && point.visible) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -9999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632 this.translate(center); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var inverted = this.chart.inverted, series = point.series, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series inside = pick(options.inside, !!this.options.stacking), // draw it inside the box? overshoot; // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (alignTo.y < 0) { alignTo.height += alignTo.y; alignTo.y = 0; } overshoot = alignTo.y + alignTo.height - series.yAxis.len; if (overshoot > 0) { alignTo.height -= overshoot; } if (inverted) { alignTo = { x: series.yAxis.len - alignTo.y - alignTo.height, y: series.xAxis.len - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * Highcharts module to hide overlapping data labels. This module is included in Highcharts. */ (function (H) { var Chart = H.Chart, each = H.each, pick = H.pick, addEvent = H.addEvent; // Collect potensial overlapping data labels. Stack labels probably don't need to be // considered because they are usually accompanied by data labels that lie inside the columns. Chart.prototype.callbacks.push(function (chart) { function collectAndHide() { var labels = []; each(chart.series, function (series) { var dlOptions = series.options.dataLabels, collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866 each(collections, function (coll) { each(series.points, function (point) { if (point[coll]) { point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118 labels.push(point[coll]); } }); }); } }); chart.hideOverlappingLabels(labels); } // Do it now ... collectAndHide(); // ... and after each chart redraw addEvent(chart, 'redraw', collectAndHide); }); /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ Chart.prototype.hideOverlappingLabels = function (labels) { var len = labels.length, label, i, j, label1, label2, isIntersecting, pos1, pos2, parent1, parent2, padding, intersectRect = function (x1, y1, w1, h1, x2, y2, w2, h2) { return !( x2 > x1 + w1 || x2 + w2 < x1 || y2 > y1 + h1 || y2 + h2 < y1 ); }; // Mark with initial opacity for (i = 0; i < len; i++) { label = labels[i]; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } } // Prevent a situation in a gradually rising slope, that each label // will hide the previous one because the previous one always has // lower rank. labels.sort(function (a, b) { return (b.labelrank || 0) - (a.labelrank || 0); }); // Detect overlapping labels for (i = 0; i < len; i++) { label1 = labels[i]; for (j = i + 1; j < len; ++j) { label2 = labels[j]; if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) { pos1 = label1.alignAttr; pos2 = label2.alignAttr; parent1 = label1.parentGroup; // Different panes have different positions parent2 = label2.parentGroup; padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333) isIntersecting = intersectRect( pos1.x + parent1.translateX, pos1.y + parent1.translateY, label1.width - padding, label1.height - padding, pos2.x + parent2.translateX, pos2.y + parent2.translateY, label2.width - padding, label2.height - padding ); if (isIntersecting) { (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0; } } } } // Hide or show each(labels, function (label) { var complete, newOpacity; if (label) { newOpacity = label.newOpacity; if (label.oldOpacity !== newOpacity && label.placed) { // Make sure the label is completely hidden to avoid catching clicks (#4362) if (newOpacity) { label.show(true); } else { complete = function () { label.hide(); }; } // Animate or set the opacity label.alignAttr.opacity = newOpacity; label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete); } label.isOld = true; } }); }; }(Highcharts)); /** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points /*for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); }*/ // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width': options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { if (item.setVisible) { item.setVisible(); } }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent( item.series || item, 'checkboxClick', { // #3712 checked: target.checked, item: item }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; function zoomOut() { chart.zoomOut(); } this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var axis = chart[isX ? 'xAxis' : 'yAxis'][0], horiz = axis.horiz, mousePos = e[horiz ? 'chartX' : 'chartY'], mouseDown = horiz ? 'mouseDownX' : 'mouseDownY', startPos = chart[mouseDown], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange, goingLeft = startPos > mousePos; // #3613 if (axis.series.length && (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) && (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[mouseDown] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the default handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point * * @param {Object} e The event arguments * @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to * actually hovered points. True for other points in shared tooltip. */ onMouseOver: function (e, byProximity) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; if (chart.hoverSeries !== series) { series.onMouseOver(); } // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } if (point.series) { // It may have been destroyed, #4130 // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); if (!byProximity) { chart.hoverPoint = point; } } }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = mathFloor(point.plotX), // #4586 plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 stateMarkerGraphic.element.point = point; // #4310 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(chart.seriesGroup); } halo.attr(extend({ 'fill': point.color || series.color, 'fill-opacity': haloOptions.opacity, 'zIndex': -1 // #4929, IE8 added halo above everything }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, /** * Get the circular path definition for the halo * @param {Number} size The radius of the circular halo * @returns {Array} The path definition */ haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted, plotX = Math.floor(this.plotX); return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; chart.hoverSeries = null; // #182, set to null before the mouseOut event fires // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, stateOptions = options.states, lineWidth = options.lineWidth, attribs, i = 0; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); // #4035 } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); while (series['zoneGraph' + i]) { series['zoneGraph' + i].attr(attribs); i = i + 1; } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.options.visible = series.userOptions.visible = vis === undefined ? !oldVisibility : vis; // #5618 showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph }); /* **************************************************************************** * Start ordinal axis logic * *****************************************************************************/ wrap(Series.prototype, 'init', function (proceed) { var series = this, xAxis; // call the original function proceed.apply(this, Array.prototype.slice.call(arguments, 1)); xAxis = series.xAxis; // Destroy the extended ordinal index on updated data if (xAxis && xAxis.options.ordinal) { addEvent(series, 'updatedData', function () { delete xAxis.ordinalIndex; }); } }); /** * In an ordinal axis, there might be areas with dense consentrations of points, then large * gaps between some. Creating equally distributed ticks over this entire range * may lead to a huge number of ticks that will later be removed. So instead, break the * positions up in segments, find the tick positions for each segment then concatenize them. * This method is used from both data grouping logic and X axis tick position logic. */ wrap(Axis.prototype, 'getTimeTicks', function (proceed, normalizedInterval, min, max, startOfWeek, positions, closestDistance, findHigherRanks) { var start = 0, end, segmentPositions, higherRanks = {}, hasCrossedHigherRank, info, posLength, outsideMax, groupPositions = [], lastGroupPosition = -Number.MAX_VALUE, tickPixelIntervalOption = this.options.tickPixelInterval; // The positions are not always defined, for example for ordinal positions when data // has regular interval (#1557, #2090) if ((!this.options.ordinal && !this.options.breaks) || !positions || positions.length < 3 || min === UNDEFINED) { return proceed.call(this, normalizedInterval, min, max, startOfWeek); } // Analyze the positions array to split it into segments on gaps larger than 5 times // the closest distance. The closest distance is already found at this point, so // we reuse that instead of computing it again. posLength = positions.length; for (end = 0; end < posLength; end++) { outsideMax = end && positions[end - 1] > max; if (positions[end] < min) { // Set the last position before min start = end; } if (end === posLength - 1 || positions[end + 1] - positions[end] > closestDistance * 5 || outsideMax) { // For each segment, calculate the tick positions from the getTimeTicks utility // function. The interval will be the same regardless of how long the segment is. if (positions[end] > lastGroupPosition) { // #1475 segmentPositions = proceed.call(this, normalizedInterval, positions[start], positions[end], startOfWeek); // Prevent duplicate groups, for example for multiple segments within one larger time frame (#1475) while (segmentPositions.length && segmentPositions[0] <= lastGroupPosition) { segmentPositions.shift(); } if (segmentPositions.length) { lastGroupPosition = segmentPositions[segmentPositions.length - 1]; } groupPositions = groupPositions.concat(segmentPositions); } // Set start of next segment start = end + 1; } if (outsideMax) { break; } } // Get the grouping info from the last of the segments. The info is the same for // all segments. info = segmentPositions.info; // Optionally identify ticks with higher rank, for example when the ticks // have crossed midnight. if (findHigherRanks && info.unitRange <= timeUnits.hour) { end = groupPositions.length - 1; // Compare points two by two for (start = 1; start < end; start++) { if (dateFormat('%d', groupPositions[start]) !== dateFormat('%d', groupPositions[start - 1])) { higherRanks[groupPositions[start]] = 'day'; hasCrossedHigherRank = true; } } // If the complete array has crossed midnight, we want to mark the first // positions also as higher rank if (hasCrossedHigherRank) { higherRanks[groupPositions[0]] = 'day'; } info.higherRanks = higherRanks; } // Save the info groupPositions.info = info; // Don't show ticks within a gap in the ordinal axis, where the space between // two points is greater than a portion of the tick pixel interval if (findHigherRanks && defined(tickPixelIntervalOption)) { // check for squashed ticks var length = groupPositions.length, i = length, itemToRemove, translated, translatedArr = [], lastTranslated, medianDistance, distance, distances = []; // Find median pixel distance in order to keep a reasonably even distance between // ticks (#748) while (i--) { translated = this.translate(groupPositions[i]); if (lastTranslated) { distances[i] = lastTranslated - translated; } translatedArr[i] = lastTranslated = translated; } distances.sort(); medianDistance = distances[mathFloor(distances.length / 2)]; if (medianDistance < tickPixelIntervalOption * 0.6) { medianDistance = null; } // Now loop over again and remove ticks where needed i = groupPositions[length - 1] > max ? length - 1 : length; // #817 lastTranslated = undefined; while (i--) { translated = translatedArr[i]; distance = lastTranslated - translated; // Remove ticks that are closer than 0.6 times the pixel interval from the one to the right, // but not if it is close to the median distance (#748). if (lastTranslated && distance < tickPixelIntervalOption * 0.8 && (medianDistance === null || distance < medianDistance * 0.8)) { // Is this a higher ranked position with a normal position to the right? if (higherRanks[groupPositions[i]] && !higherRanks[groupPositions[i + 1]]) { // Yes: remove the lower ranked neighbour to the right itemToRemove = i + 1; lastTranslated = translated; // #709 } else { // No: remove this one itemToRemove = i; } groupPositions.splice(itemToRemove, 1); } else { lastTranslated = translated; } } } return groupPositions; }); // Extend the Axis prototype extend(Axis.prototype, { /** * Calculate the ordinal positions before tick positions are calculated. */ beforeSetTickPositions: function () { var axis = this, len, ordinalPositions = [], useOrdinal = false, dist, extremes = axis.getExtremes(), min = extremes.min, max = extremes.max, minIndex, maxIndex, slope, hasBreaks = axis.isXAxis && !!axis.options.breaks, isOrdinal = axis.options.ordinal, ignoreHiddenSeries = axis.chart.options.chart.ignoreHiddenSeries, i; // apply the ordinal logic if (isOrdinal || hasBreaks) { // #4167 YAxis is never ordinal ? each(axis.series, function (series, i) { if ((!ignoreHiddenSeries || series.visible !== false) && (series.takeOrdinalPosition !== false || hasBreaks)) { // concatenate the processed X data into the existing positions, or the empty array ordinalPositions = ordinalPositions.concat(series.processedXData); len = ordinalPositions.length; // remove duplicates (#1588) ordinalPositions.sort(function (a, b) { return a - b; // without a custom function it is sorted as strings }); if (len) { i = len - 1; while (i--) { if (ordinalPositions[i] === ordinalPositions[i + 1]) { ordinalPositions.splice(i, 1); } } } } }); // cache the length len = ordinalPositions.length; // Check if we really need the overhead of mapping axis data against the ordinal positions. // If the series consist of evenly spaced data any way, we don't need any ordinal logic. if (len > 2) { // two points have equal distance by default dist = ordinalPositions[1] - ordinalPositions[0]; i = len - 1; while (i-- && !useOrdinal) { if (ordinalPositions[i + 1] - ordinalPositions[i] !== dist) { useOrdinal = true; } } // When zooming in on a week, prevent axis padding for weekends even though the data within // the week is evenly spaced. if (!axis.options.keepOrdinalPadding && (ordinalPositions[0] - min > dist || max - ordinalPositions[ordinalPositions.length - 1] > dist)) { useOrdinal = true; } } // Record the slope and offset to compute the linear values from the array index. // Since the ordinal positions may exceed the current range, get the start and // end positions within it (#719, #665b) if (useOrdinal) { // Register axis.ordinalPositions = ordinalPositions; // This relies on the ordinalPositions being set. Use mathMax and mathMin to prevent // padding on either sides of the data. minIndex = axis.val2lin(mathMax(min, ordinalPositions[0]), true); maxIndex = mathMax(axis.val2lin(mathMin(max, ordinalPositions[ordinalPositions.length - 1]), true), 1); // #3339 // Set the slope and offset of the values compared to the indices in the ordinal positions axis.ordinalSlope = slope = (max - min) / (maxIndex - minIndex); axis.ordinalOffset = min - (minIndex * slope); } else { axis.ordinalPositions = axis.ordinalSlope = axis.ordinalOffset = UNDEFINED; } } axis.isOrdinal = isOrdinal && useOrdinal; // #3818, #4196, #4926 axis.groupIntervalFactor = null; // reset for next run }, /** * Translate from a linear axis value to the corresponding ordinal axis position. If there * are no gaps in the ordinal axis this will be the same. The translated value is the value * that the point would have if the axis were linear, using the same min and max. * * @param Number val The axis value * @param Boolean toIndex Whether to return the index in the ordinalPositions or the new value */ val2lin: function (val, toIndex) { var axis = this, ordinalPositions = axis.ordinalPositions, ret; if (!ordinalPositions) { ret = val; } else { var ordinalLength = ordinalPositions.length, i, distance, ordinalIndex; // first look for an exact match in the ordinalpositions array i = ordinalLength; while (i--) { if (ordinalPositions[i] === val) { ordinalIndex = i; break; } } // if that failed, find the intermediate position between the two nearest values i = ordinalLength - 1; while (i--) { if (val > ordinalPositions[i] || i === 0) { // interpolate distance = (val - ordinalPositions[i]) / (ordinalPositions[i + 1] - ordinalPositions[i]); // something between 0 and 1 ordinalIndex = i + distance; break; } } ret = toIndex ? ordinalIndex : axis.ordinalSlope * (ordinalIndex || 0) + axis.ordinalOffset; } return ret; }, /** * Translate from linear (internal) to axis value * * @param Number val The linear abstracted value * @param Boolean fromIndex Translate from an index in the ordinal positions rather than a value */ lin2val: function (val, fromIndex) { var axis = this, ordinalPositions = axis.ordinalPositions, ret; if (!ordinalPositions) { // the visible range contains only equally spaced values ret = val; } else { var ordinalSlope = axis.ordinalSlope, ordinalOffset = axis.ordinalOffset, i = ordinalPositions.length - 1, linearEquivalentLeft, linearEquivalentRight, distance; // Handle the case where we translate from the index directly, used only // when panning an ordinal axis if (fromIndex) { if (val < 0) { // out of range, in effect panning to the left val = ordinalPositions[0]; } else if (val > i) { // out of range, panning to the right val = ordinalPositions[i]; } else { // split it up i = mathFloor(val); distance = val - i; // the decimal } // Loop down along the ordinal positions. When the linear equivalent of i matches // an ordinal position, interpolate between the left and right values. } else { while (i--) { linearEquivalentLeft = (ordinalSlope * i) + ordinalOffset; if (val >= linearEquivalentLeft) { linearEquivalentRight = (ordinalSlope * (i + 1)) + ordinalOffset; distance = (val - linearEquivalentLeft) / (linearEquivalentRight - linearEquivalentLeft); // something between 0 and 1 break; } } } // If the index is within the range of the ordinal positions, return the associated // or interpolated value. If not, just return the value ret = distance !== UNDEFINED && ordinalPositions[i] !== UNDEFINED ? ordinalPositions[i] + (distance ? distance * (ordinalPositions[i + 1] - ordinalPositions[i]) : 0) : val; } return ret; }, /** * Get the ordinal positions for the entire data set. This is necessary in chart panning * because we need to find out what points or data groups are available outside the * visible range. When a panning operation starts, if an index for the given grouping * does not exists, it is created and cached. This index is deleted on updated data, so * it will be regenerated the next time a panning operation starts. */ getExtendedPositions: function () { var axis = this, chart = axis.chart, grouping = axis.series[0].currentDataGrouping, ordinalIndex = axis.ordinalIndex, key = grouping ? grouping.count + grouping.unitName : 'raw', extremes = axis.getExtremes(), fakeAxis, fakeSeries; // If this is the first time, or the ordinal index is deleted by updatedData, // create it. if (!ordinalIndex) { ordinalIndex = axis.ordinalIndex = {}; } if (!ordinalIndex[key]) { // Create a fake axis object where the extended ordinal positions are emulated fakeAxis = { series: [], chart: chart, getExtremes: function () { return { min: extremes.dataMin, max: extremes.dataMax }; }, options: { ordinal: true }, val2lin: Axis.prototype.val2lin // #2590 }; // Add the fake series to hold the full data, then apply processData to it each(axis.series, function (series) { fakeSeries = { xAxis: fakeAxis, xData: series.xData, chart: chart, destroyGroupedData: noop }; fakeSeries.options = { dataGrouping: grouping ? { enabled: true, forced: true, approximation: 'open', // doesn't matter which, use the fastest units: [[grouping.unitName, [grouping.count]]] } : { enabled: false } }; series.processData.apply(fakeSeries); fakeAxis.series.push(fakeSeries); }); // Run beforeSetTickPositions to compute the ordinalPositions axis.beforeSetTickPositions.apply(fakeAxis); // Cache it ordinalIndex[key] = fakeAxis.ordinalPositions; } return ordinalIndex[key]; }, /** * Find the factor to estimate how wide the plot area would have been if ordinal * gaps were included. This value is used to compute an imagined plot width in order * to establish the data grouping interval. * * A real world case is the intraday-candlestick * example. Without this logic, it would show the correct data grouping when viewing * a range within each day, but once moving the range to include the gap between two * days, the interval would include the cut-away night hours and the data grouping * would be wrong. So the below method tries to compensate by identifying the most * common point interval, in this case days. * * An opposite case is presented in issue #718. We have a long array of daily data, * then one point is appended one hour after the last point. We expect the data grouping * not to change. * * In the future, if we find cases where this estimation doesn't work optimally, we * might need to add a second pass to the data grouping logic, where we do another run * with a greater interval if the number of data groups is more than a certain fraction * of the desired group count. */ getGroupIntervalFactor: function (xMin, xMax, series) { var i, processedXData = series.processedXData, len = processedXData.length, distances = [], median, groupIntervalFactor = this.groupIntervalFactor; // Only do this computation for the first series, let the other inherit it (#2416) if (!groupIntervalFactor) { // Register all the distances in an array for (i = 0; i < len - 1; i++) { distances[i] = processedXData[i + 1] - processedXData[i]; } // Sort them and find the median distances.sort(function (a, b) { return a - b; }); median = distances[mathFloor(len / 2)]; // Compensate for series that don't extend through the entire axis extent. #1675. xMin = mathMax(xMin, processedXData[0]); xMax = mathMin(xMax, processedXData[len - 1]); this.groupIntervalFactor = groupIntervalFactor = (len * median) / (xMax - xMin); } // Return the factor needed for data grouping return groupIntervalFactor; }, /** * Make the tick intervals closer because the ordinal gaps make the ticks spread out or cluster */ postProcessTickInterval: function (tickInterval) { // Problem: http://jsfiddle.net/highcharts/FQm4E/1/ // This is a case where this algorithm doesn't work optimally. In this case, the // tick labels are spread out per week, but all the gaps reside within weeks. So // we have a situation where the labels are courser than the ordinal gaps, and // thus the tick interval should not be altered var ordinalSlope = this.ordinalSlope, ret; if (ordinalSlope) { if (!this.options.breaks) { ret = tickInterval / (ordinalSlope / this.closestPointRange); } else { ret = this.closestPointRange; } } else { ret = tickInterval; } return ret; } }); // Extending the Chart.pan method for ordinal axes wrap(Chart.prototype, 'pan', function (proceed, e) { var chart = this, xAxis = chart.xAxis[0], chartX = e.chartX, runBase = false; if (xAxis.options.ordinal && xAxis.series.length) { var mouseDownX = chart.mouseDownX, extremes = xAxis.getExtremes(), dataMax = extremes.dataMax, min = extremes.min, max = extremes.max, trimmedRange, hoverPoints = chart.hoverPoints, closestPointRange = xAxis.closestPointRange, pointPixelWidth = xAxis.translationSlope * (xAxis.ordinalSlope || closestPointRange), movedUnits = (mouseDownX - chartX) / pointPixelWidth, // how many ordinal units did we move? extendedAxis = { ordinalPositions: xAxis.getExtendedPositions() }, // get index of all the chart's points ordinalPositions, searchAxisLeft, lin2val = xAxis.lin2val, val2lin = xAxis.val2lin, searchAxisRight; if (!extendedAxis.ordinalPositions) { // we have an ordinal axis, but the data is equally spaced runBase = true; } else if (mathAbs(movedUnits) > 1) { // Remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (movedUnits < 0) { searchAxisLeft = extendedAxis; searchAxisRight = xAxis.ordinalPositions ? xAxis : extendedAxis; } else { searchAxisLeft = xAxis.ordinalPositions ? xAxis : extendedAxis; searchAxisRight = extendedAxis; } // In grouped data series, the last ordinal position represents the grouped data, which is // to the left of the real data max. If we don't compensate for this, we will be allowed // to pan grouped data series passed the right of the plot area. ordinalPositions = searchAxisRight.ordinalPositions; if (dataMax > ordinalPositions[ordinalPositions.length - 1]) { ordinalPositions.push(dataMax); } // Get the new min and max values by getting the ordinal index for the current extreme, // then add the moved units and translate back to values. This happens on the // extended ordinal positions if the new position is out of range, else it happens // on the current x axis which is smaller and faster. chart.fixedRange = max - min; trimmedRange = xAxis.toFixedRange(null, null, lin2val.apply(searchAxisLeft, [ val2lin.apply(searchAxisLeft, [min, true]) + movedUnits, // the new index true // translate from index ]), lin2val.apply(searchAxisRight, [ val2lin.apply(searchAxisRight, [max, true]) + movedUnits, // the new index true // translate from index ]) ); // Apply it if it is within the available data range if (trimmedRange.min >= mathMin(extremes.dataMin, min) && trimmedRange.max <= mathMax(dataMax, max)) { xAxis.setExtremes(trimmedRange.min, trimmedRange.max, true, false, { trigger: 'pan' }); } chart.mouseDownX = chartX; // set new reference for next run css(chart.container, { cursor: 'move' }); } } else { runBase = true; } // revert to the linear chart.pan version if (runBase) { // call the original function proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } }); /** * Extend getGraphPath by identifying gaps in the ordinal data so that we can draw a gap in the * line or area */ Series.prototype.gappedPath = function () { var gapSize = this.options.gapSize, points = this.points.slice(), i = points.length - 1; if (gapSize && i > 0) { // #5008 // extension for ordinal breaks while (i--) { if (points[i + 1].x - points[i].x > this.closestPointRange * gapSize) { points.splice( // insert after this one i + 1, 0, { isNull: true } ); } } } // Call base method //return proceed.call(this, points, a, b); return this.getGraphPath(points); }; /* **************************************************************************** * End ordinal axis logic * *****************************************************************************/ /** * Highstock JS v4.2.7 (2016-09-21) * Highcharts Broken Axis module * * License: www.highcharts.com/license */ (function (factory) { factory(Highcharts); }(function (H) { 'use strict'; var pick = H.pick, wrap = H.wrap, each = H.each, extend = H.extend, fireEvent = H.fireEvent, Axis = H.Axis, Series = H.Series; function stripArguments() { return Array.prototype.slice.call(arguments, 1); } extend(Axis.prototype, { isInBreak: function (brk, val) { var ret, repeat = brk.repeat || Infinity, from = brk.from, length = brk.to - brk.from, test = (val >= from ? (val - from) % repeat : repeat - ((from - val) % repeat)); if (!brk.inclusive) { ret = test < length && test !== 0; } else { ret = test <= length; } return ret; }, isInAnyBreak: function (val, testKeep) { var breaks = this.options.breaks, i = breaks && breaks.length, inbrk, keep, ret; if (i) { while (i--) { if (this.isInBreak(breaks[i], val)) { inbrk = true; if (!keep) { keep = pick(breaks[i].showPoints, this.isXAxis ? false : true); } } } if (inbrk && testKeep) { ret = inbrk && !keep; } else { ret = inbrk; } } return ret; } }); wrap(Axis.prototype, 'setTickPositions', function (proceed) { proceed.apply(this, Array.prototype.slice.call(arguments, 1)); if (this.options.breaks) { var axis = this, tickPositions = this.tickPositions, info = this.tickPositions.info, newPositions = [], i; for (i = 0; i < tickPositions.length; i++) { if (!axis.isInAnyBreak(tickPositions[i])) { newPositions.push(tickPositions[i]); } } this.tickPositions = newPositions; this.tickPositions.info = info; } }); wrap(Axis.prototype, 'init', function (proceed, chart, userOptions) { // Force Axis to be not-ordinal when breaks are defined if (userOptions.breaks && userOptions.breaks.length) { userOptions.ordinal = false; } proceed.call(this, chart, userOptions); if (this.options.breaks) { var axis = this; axis.isBroken = true; this.val2lin = function (val) { var nval = val, brk, i; for (i = 0; i < axis.breakArray.length; i++) { brk = axis.breakArray[i]; if (brk.to <= val) { nval -= brk.len; } else if (brk.from >= val) { break; } else if (axis.isInBreak(brk, val)) { nval -= (val - brk.from); break; } } return nval; }; this.lin2val = function (val) { var nval = val, brk, i; for (i = 0; i < axis.breakArray.length; i++) { brk = axis.breakArray[i]; if (brk.from >= nval) { break; } else if (brk.to < nval) { nval += brk.len; } else if (axis.isInBreak(brk, nval)) { nval += brk.len; } } return nval; }; this.setExtremes = function (newMin, newMax, redraw, animation, eventArguments) { // If trying to set extremes inside a break, extend it to before and after the break ( #3857 ) while (this.isInAnyBreak(newMin)) { newMin -= this.closestPointRange; } while (this.isInAnyBreak(newMax)) { newMax -= this.closestPointRange; } Axis.prototype.setExtremes.call(this, newMin, newMax, redraw, animation, eventArguments); }; this.setAxisTranslation = function (saveOld) { Axis.prototype.setAxisTranslation.call(this, saveOld); var breaks = axis.options.breaks, breakArrayT = [], // Temporary one breakArray = [], length = 0, inBrk, repeat, brk, min = axis.userMin || axis.min, max = axis.userMax || axis.max, start, i, j; // Min & max check (#4247) for (i in breaks) { brk = breaks[i]; repeat = brk.repeat || Infinity; if (axis.isInBreak(brk, min)) { min += (brk.to % repeat) - (min % repeat); } if (axis.isInBreak(brk, max)) { max -= (max % repeat) - (brk.from % repeat); } } // Construct an array holding all breaks in the axis for (i in breaks) { brk = breaks[i]; start = brk.from; repeat = brk.repeat || Infinity; while (start - repeat > min) { start -= repeat; } while (start < min) { start += repeat; } for (j = start; j < max; j += repeat) { breakArrayT.push({ value: j, move: 'in' }); breakArrayT.push({ value: j + (brk.to - brk.from), move: 'out', size: brk.breakSize }); } } breakArrayT.sort(function (a, b) { var ret; if (a.value === b.value) { ret = (a.move === 'in' ? 0 : 1) - (b.move === 'in' ? 0 : 1); } else { ret = a.value - b.value; } return ret; }); // Simplify the breaks inBrk = 0; start = min; for (i in breakArrayT) { brk = breakArrayT[i]; inBrk += (brk.move === 'in' ? 1 : -1); if (inBrk === 1 && brk.move === 'in') { start = brk.value; } if (inBrk === 0) { breakArray.push({ from: start, to: brk.value, len: brk.value - start - (brk.size || 0) }); length += brk.value - start - (brk.size || 0); } } axis.breakArray = breakArray; fireEvent(axis, 'afterBreaks'); axis.transA *= ((max - axis.min) / (max - min - length)); axis.min = min; axis.max = max; }; } }); wrap(Series.prototype, 'generatePoints', function (proceed) { proceed.apply(this, stripArguments(arguments)); var series = this, xAxis = series.xAxis, yAxis = series.yAxis, points = series.points, point, i = points.length, connectNulls = series.options.connectNulls, nullGap; if (xAxis && yAxis && (xAxis.options.breaks || yAxis.options.breaks)) { while (i--) { point = points[i]; nullGap = point.y === null && connectNulls === false; // respect nulls inside the break (#4275) if (!nullGap && (xAxis.isInAnyBreak(point.x, true) || yAxis.isInAnyBreak(point.y, true))) { points.splice(i, 1); if (this.data[i]) { this.data[i].destroyElements(); // removes the graphics for this point if they exist } } } } }); function drawPointsWrapped(proceed) { proceed.apply(this); this.drawBreaks(this.xAxis, ['x']); this.drawBreaks(this.yAxis, pick(this.pointArrayMap, ['y'])); } H.Series.prototype.drawBreaks = function (axis, keys) { var series = this, points = series.points, breaks, threshold, eventName, y; each(keys, function (key) { breaks = axis.breakArray || []; threshold = axis.isXAxis ? axis.min : pick(series.options.threshold, axis.min); each(points, function (point) { y = pick(point['stack' + key.toUpperCase()], point[key]); each(breaks, function (brk) { eventName = false; if ((threshold < brk.from && y > brk.to) || (threshold > brk.from && y < brk.from)) { eventName = 'pointBreak'; } else if ((threshold < brk.from && y > brk.from && y < brk.to) || (threshold > brk.from && y > brk.to && y < brk.from)) { // point falls inside the break eventName = 'pointInBreak'; } if (eventName) { fireEvent(axis, eventName, { point: point, brk: brk }); } }); }); }); }; wrap(H.seriesTypes.column.prototype, 'drawPoints', drawPointsWrapped); wrap(H.Series.prototype, 'drawPoints', drawPointsWrapped); })); /* **************************************************************************** * Start data grouping module * ******************************************************************************/ var DATA_GROUPING = 'dataGrouping', seriesProto = Series.prototype, baseProcessData = seriesProto.processData, baseGeneratePoints = seriesProto.generatePoints, baseDestroy = seriesProto.destroy, commonOptions = { approximation: 'average', // average, open, high, low, close, sum //enabled: null, // (true for stock charts, false for basic), //forced: undefined, groupPixelWidth: 2, // the first one is the point or start value, the second is the start value if we're dealing with range, // the third one is the end value if dealing with a range dateTimeLabelFormats: { millisecond: ['%A, %b %e, %H:%M:%S.%L', '%A, %b %e, %H:%M:%S.%L', '-%H:%M:%S.%L'], second: ['%A, %b %e, %H:%M:%S', '%A, %b %e, %H:%M:%S', '-%H:%M:%S'], minute: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'], hour: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'], day: ['%A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'], week: ['Week from %A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'], month: ['%B %Y', '%B', '-%B %Y'], year: ['%Y', '%Y', '-%Y'] } // smoothed = false, // enable this for navigator series only }, specificOptions = { // extends common options line: {}, spline: {}, area: {}, areaspline: {}, column: { approximation: 'sum', groupPixelWidth: 10 }, arearange: { approximation: 'range' }, areasplinerange: { approximation: 'range' }, columnrange: { approximation: 'range', groupPixelWidth: 10 }, candlestick: { approximation: 'ohlc', groupPixelWidth: 10 }, ohlc: { approximation: 'ohlc', groupPixelWidth: 5 } }, // units are defined in a separate array to allow complete overriding in case of a user option defaultDataGroupingUnits = [ [ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1] ], [ 'week', [1] ], [ 'month', [1, 3, 6] ], [ 'year', null ] ], /** * Define the available approximation types. The data grouping approximations takes an array * or numbers as the first parameter. In case of ohlc, four arrays are sent in as four parameters. * Each array consists only of numbers. In case null values belong to the group, the property * .hasNulls will be set to true on the array. */ approximations = { sum: function (arr) { var len = arr.length, ret; // 1. it consists of nulls exclusively if (!len && arr.hasNulls) { ret = null; // 2. it has a length and real values } else if (len) { ret = 0; while (len--) { ret += arr[len]; } } // 3. it has zero length, so just return undefined // => doNothing() return ret; }, average: function (arr) { var len = arr.length, ret = approximations.sum(arr); // If we have a number, return it divided by the length. If not, return // null or undefined based on what the sum method finds. if (isNumber(ret) && len) { ret = ret / len; } return ret; }, open: function (arr) { return arr.length ? arr[0] : (arr.hasNulls ? null : UNDEFINED); }, high: function (arr) { return arr.length ? arrayMax(arr) : (arr.hasNulls ? null : UNDEFINED); }, low: function (arr) { return arr.length ? arrayMin(arr) : (arr.hasNulls ? null : UNDEFINED); }, close: function (arr) { return arr.length ? arr[arr.length - 1] : (arr.hasNulls ? null : UNDEFINED); }, // ohlc and range are special cases where a multidimensional array is input and an array is output ohlc: function (open, high, low, close) { open = approximations.open(open); high = approximations.high(high); low = approximations.low(low); close = approximations.close(close); if (isNumber(open) || isNumber(high) || isNumber(low) || isNumber(close)) { return [open, high, low, close]; } // else, return is undefined }, range: function (low, high) { low = approximations.low(low); high = approximations.high(high); if (isNumber(low) || isNumber(high)) { return [low, high]; } // else, return is undefined } }; /** * Takes parallel arrays of x and y data and groups the data into intervals defined by groupPositions, a collection * of starting x values for each group. */ seriesProto.groupData = function (xData, yData, groupPositions, approximation) { var series = this, data = series.data, dataOptions = series.options.data, groupedXData = [], groupedYData = [], groupMap = [], dataLength = xData.length, pointX, pointY, groupedY, handleYData = !!yData, // when grouping the fake extended axis for panning, we don't need to consider y values = [[], [], [], []], approximationFn = typeof approximation === 'function' ? approximation : approximations[approximation], pointArrayMap = series.pointArrayMap, pointArrayMapLength = pointArrayMap && pointArrayMap.length, i, pos = 0, start = 0; // Start with the first point within the X axis range (#2696) for (i = 0; i <= dataLength; i++) { if (xData[i] >= groupPositions[0]) { break; } } for (i; i <= dataLength; i++) { // when a new group is entered, summarize and initiate the previous group while ((groupPositions[pos + 1] !== undefined && xData[i] >= groupPositions[pos + 1]) || i === dataLength) { // get the last group // get group x and y pointX = groupPositions[pos]; series.dataGroupInfo = { start: start, length: values[0].length }; groupedY = approximationFn.apply(series, values); // push the grouped data if (groupedY !== UNDEFINED) { groupedXData.push(pointX); groupedYData.push(groupedY); groupMap.push(series.dataGroupInfo); } // reset the aggregate arrays start = i; values[0] = []; values[1] = []; values[2] = []; values[3] = []; // Advance on the group positions pos += 1; // don't loop beyond the last group if (i === dataLength) { break; } } // break out if (i === dataLength) { break; } // for each raw data point, push it to an array that contains all values for this specific group if (pointArrayMap) { var index = series.cropStart + i, point = (data && data[index]) || series.pointClass.prototype.applyOptions.apply({ series: series }, [dataOptions[index]]), j, val; for (j = 0; j < pointArrayMapLength; j++) { val = point[pointArrayMap[j]]; if (isNumber(val)) { values[j].push(val); } else if (val === null) { values[j].hasNulls = true; } } } else { pointY = handleYData ? yData[i] : null; if (isNumber(pointY)) { values[0].push(pointY); } else if (pointY === null) { values[0].hasNulls = true; } } } return [groupedXData, groupedYData, groupMap]; }; /** * Extend the basic processData method, that crops the data to the current zoom * range, with data grouping logic. */ seriesProto.processData = function () { var series = this, chart = series.chart, options = series.options, dataGroupingOptions = options[DATA_GROUPING], groupingEnabled = series.allowDG !== false && dataGroupingOptions && pick(dataGroupingOptions.enabled, chart.options._stock), hasGroupedData, skip; // run base method series.forceCrop = groupingEnabled; // #334 series.groupPixelWidth = null; // #2110 series.hasProcessed = true; // #2692 // skip if processData returns false or if grouping is disabled (in that order) or #5493 skip = baseProcessData.apply(series, arguments) === false || !groupingEnabled || !series.visible; if (!skip) { series.destroyGroupedData(); var i, processedXData = series.processedXData, processedYData = series.processedYData, plotSizeX = chart.plotSizeX, xAxis = series.xAxis, ordinal = xAxis.options.ordinal, groupPixelWidth = series.groupPixelWidth = xAxis.getGroupPixelWidth && xAxis.getGroupPixelWidth(); // Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth if (groupPixelWidth) { hasGroupedData = true; series.isDirty = true; // force recreation of point instances in series.translate, #5699 var extremes = xAxis.getExtremes(), xMin = extremes.min, xMax = extremes.max, groupIntervalFactor = (ordinal && xAxis.getGroupIntervalFactor(xMin, xMax, series)) || 1, interval = (groupPixelWidth * (xMax - xMin) / plotSizeX) * groupIntervalFactor, groupPositions = xAxis.getTimeTicks( xAxis.normalizeTimeTickInterval(interval, dataGroupingOptions.units || defaultDataGroupingUnits), Math.min(xMin, processedXData[0]), // Processed data may extend beyond axis (#4907) Math.max(xMax, processedXData[processedXData.length - 1]), xAxis.options.startOfWeek, processedXData, series.closestPointRange ), groupedData = seriesProto.groupData.apply(series, [processedXData, processedYData, groupPositions, dataGroupingOptions.approximation]), groupedXData = groupedData[0], groupedYData = groupedData[1]; // prevent the smoothed data to spill out left and right, and make // sure data is not shifted to the left if (dataGroupingOptions.smoothed) { i = groupedXData.length - 1; groupedXData[i] = Math.min(groupedXData[i], xMax); while (i-- && i > 0) { groupedXData[i] += interval / 2; } groupedXData[0] = Math.max(groupedXData[0], xMin); } // record what data grouping values were used series.currentDataGrouping = groupPositions.info; series.closestPointRange = groupPositions.info.totalRange; series.groupMap = groupedData[2]; // Make sure the X axis extends to show the first group (#2533) if (defined(groupedXData[0]) && groupedXData[0] < xAxis.dataMin) { if (xAxis.min === xAxis.dataMin) { xAxis.min = groupedXData[0]; } xAxis.dataMin = groupedXData[0]; } // set series props series.processedXData = groupedXData; series.processedYData = groupedYData; } else { series.currentDataGrouping = series.groupMap = null; } series.hasGroupedData = hasGroupedData; } }; /** * Destroy the grouped data points. #622, #740 */ seriesProto.destroyGroupedData = function () { var groupedData = this.groupedData; // clear previous groups each(groupedData || [], function (point, i) { if (point) { groupedData[i] = point.destroy ? point.destroy() : null; } }); this.groupedData = null; }; /** * Override the generatePoints method by adding a reference to grouped data */ seriesProto.generatePoints = function () { baseGeneratePoints.apply(this); // record grouped data in order to let it be destroyed the next time processData runs this.destroyGroupedData(); // #622 this.groupedData = this.hasGroupedData ? this.points : null; }; /** * Override point prototype to throw a warning when trying to update grouped points */ wrap(Point.prototype, 'update', function (proceed) { if (this.dataGroup) { error(24); } else { proceed.apply(this, [].slice.call(arguments, 1)); } }); /** * Extend the original method, make the tooltip's header reflect the grouped range */ wrap(Tooltip.prototype, 'tooltipFooterHeaderFormatter', function (proceed, labelConfig, isFooter) { var tooltip = this, series = labelConfig.series, options = series.options, tooltipOptions = series.tooltipOptions, dataGroupingOptions = options.dataGrouping, xDateFormat = tooltipOptions.xDateFormat, xDateFormatEnd, xAxis = series.xAxis, currentDataGrouping, dateTimeLabelFormats, labelFormats, formattedKey; // apply only to grouped series if (xAxis && xAxis.options.type === 'datetime' && dataGroupingOptions && isNumber(labelConfig.key)) { // set variables currentDataGrouping = series.currentDataGrouping; dateTimeLabelFormats = dataGroupingOptions.dateTimeLabelFormats; // if we have grouped data, use the grouping information to get the right format if (currentDataGrouping) { labelFormats = dateTimeLabelFormats[currentDataGrouping.unitName]; if (currentDataGrouping.count === 1) { xDateFormat = labelFormats[0]; } else { xDateFormat = labelFormats[1]; xDateFormatEnd = labelFormats[2]; } // if not grouped, and we don't have set the xDateFormat option, get the best fit, // so if the least distance between points is one minute, show it, but if the // least distance is one day, skip hours and minutes etc. } else if (!xDateFormat && dateTimeLabelFormats) { xDateFormat = tooltip.getXDateFormat(labelConfig, tooltipOptions, xAxis); } // now format the key formattedKey = dateFormat(xDateFormat, labelConfig.key); if (xDateFormatEnd) { formattedKey += dateFormat(xDateFormatEnd, labelConfig.key + currentDataGrouping.totalRange - 1); } // return the replaced format return format(tooltipOptions[(isFooter ? 'footer' : 'header') + 'Format'], { point: extend(labelConfig.point, { key: formattedKey }), series: series }); } // else, fall back to the regular formatter return proceed.call(tooltip, labelConfig, isFooter); }); /** * Extend the series destroyer */ seriesProto.destroy = function () { var series = this, groupedData = series.groupedData || [], i = groupedData.length; while (i--) { if (groupedData[i]) { groupedData[i].destroy(); } } baseDestroy.apply(series); }; // Handle default options for data grouping. This must be set at runtime because some series types are // defined after this. wrap(seriesProto, 'setOptions', function (proceed, itemOptions) { var options = proceed.call(this, itemOptions), type = this.type, plotOptions = this.chart.options.plotOptions, defaultOptions = defaultPlotOptions[type].dataGrouping; if (specificOptions[type]) { // #1284 if (!defaultOptions) { defaultOptions = merge(commonOptions, specificOptions[type]); } options.dataGrouping = merge( defaultOptions, plotOptions.series && plotOptions.series.dataGrouping, // #1228 plotOptions[type].dataGrouping, // Set by the StockChart constructor itemOptions.dataGrouping ); } if (this.chart.options._stock) { this.requireSorting = true; } return options; }); /** * When resetting the scale reset the hasProccessed flag to avoid taking previous data grouping * of neighbour series into accound when determining group pixel width (#2692). */ wrap(Axis.prototype, 'setScale', function (proceed) { proceed.call(this); each(this.series, function (series) { series.hasProcessed = false; }); }); /** * Get the data grouping pixel width based on the greatest defined individual width * of the axis' series, and if whether one of the axes need grouping. */ Axis.prototype.getGroupPixelWidth = function () { var series = this.series, len = series.length, i, groupPixelWidth = 0, doGrouping = false, dataLength, dgOptions; // If multiple series are compared on the same x axis, give them the same // group pixel width (#334) i = len; while (i--) { dgOptions = series[i].options.dataGrouping; if (dgOptions) { groupPixelWidth = mathMax(groupPixelWidth, dgOptions.groupPixelWidth); } } // If one of the series needs grouping, apply it to all (#1634) i = len; while (i--) { dgOptions = series[i].options.dataGrouping; if (dgOptions && series[i].hasProcessed) { // #2692 dataLength = (series[i].processedXData || series[i].data).length; // Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth if (series[i].groupPixelWidth || dataLength > (this.chart.plotSizeX / groupPixelWidth) || (dataLength && dgOptions.forced)) { doGrouping = true; } } } return doGrouping ? groupPixelWidth : 0; }; /** * Force data grouping on all the axis' series. */ Axis.prototype.setDataGrouping = function (dataGrouping, redraw) { var i; redraw = pick(redraw, true); if (!dataGrouping) { dataGrouping = { forced: false, units: null }; } // Axis is instantiated, update all series if (this instanceof Axis) { i = this.series.length; while (i--) { this.series[i].update({ dataGrouping: dataGrouping }, false); } // Axis not yet instanciated, alter series options } else { each(this.chart.options.series, function (seriesOptions) { seriesOptions.dataGrouping = dataGrouping; }, false); } if (redraw) { this.chart.redraw(); } }; /* **************************************************************************** * End data grouping module * ******************************************************************************/ /* **************************************************************************** * Start OHLC series code * *****************************************************************************/ // 1 - Set default options defaultPlotOptions.ohlc = merge(defaultPlotOptions.column, { lineWidth: 1, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span> <b> {series.name}</b><br/>' + 'Open: {point.open}<br/>' + 'High: {point.high}<br/>' + 'Low: {point.low}<br/>' + 'Close: {point.close}<br/>' }, states: { hover: { lineWidth: 3 } }, threshold: null //upColor: undefined }); // 2 - Create the OHLCSeries object var OHLCSeries = extendClass(seriesTypes.column, { type: 'ohlc', pointArrayMap: ['open', 'high', 'low', 'close'], // array point configs are mapped to this toYData: function (point) { // return a plain array for speedy calculation return [point.open, point.high, point.low, point.close]; }, pointValKey: 'high', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'color', 'stroke-width': 'lineWidth' }, upColorProp: 'stroke', /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.column.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upColor = options.upColor || series.color, seriesDownPointAttr = merge(series.pointAttr), upColorProp = series.upColorProp; seriesDownPointAttr[''][upColorProp] = upColor; seriesDownPointAttr.hover[upColorProp] = stateOptions.hover.upColor || upColor; seriesDownPointAttr.select[upColorProp] = stateOptions.select.upColor || upColor; each(series.points, function (point) { if (point.open < point.close && !point.options.color) { point.pointAttr = seriesDownPointAttr; } }); }, /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis, hasModifyValue = !!series.modifyValue, translatedOLC = ['plotOpen', 'yBottom', 'plotClose']; seriesTypes.column.prototype.translate.apply(series); // Do the translation each(series.points, function (point) { each([point.open, point.low, point.close], function (value, i) { if (value !== null) { if (hasModifyValue) { value = series.modifyValue(value); } point[translatedOLC[i]] = yAxis.toPixels(value, true); } }); }); }, /** * Draw the data points */ drawPoints: function () { var series = this, points = series.points, chart = series.chart, pointAttr, plotOpen, plotClose, crispCorr, halfWidth, path, graphic, crispX; each(points, function (point) { if (point.plotY !== UNDEFINED) { graphic = point.graphic; pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || series.pointAttr[NORMAL_STATE]; // crisp vector coordinates crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathRound(point.plotX) - crispCorr; // #2596 halfWidth = mathRound(point.shapeArgs.width / 2); // the vertical stem path = [ 'M', crispX, mathRound(point.yBottom), 'L', crispX, mathRound(point.plotY) ]; // open if (point.open !== null) { plotOpen = mathRound(point.plotOpen) + crispCorr; path.push( 'M', crispX, plotOpen, 'L', crispX - halfWidth, plotOpen ); } // close if (point.close !== null) { plotClose = mathRound(point.plotClose) + crispCorr; path.push( 'M', crispX, plotClose, 'L', crispX + halfWidth, plotClose ); } // create and/or update the graphic if (graphic) { graphic .attr(pointAttr) // #3897 .animate({ d: path }); } else { point.graphic = chart.renderer.path(path) .attr(pointAttr) .add(series.group); } } }); }, /** * Disable animation */ animate: null }); seriesTypes.ohlc = OHLCSeries; /* **************************************************************************** * End OHLC series code * *****************************************************************************/ /* **************************************************************************** * Start Candlestick series code * *****************************************************************************/ // 1 - set default options defaultPlotOptions.candlestick = merge(defaultPlotOptions.column, { lineColor: 'black', lineWidth: 1, states: { hover: { lineWidth: 2 } }, tooltip: defaultPlotOptions.ohlc.tooltip, threshold: null, upColor: 'white' // upLineColor: null }); // 2 - Create the CandlestickSeries object var CandlestickSeries = extendClass(OHLCSeries, { type: 'candlestick', /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'color', stroke: 'lineColor', 'stroke-width': 'lineWidth' }, upColorProp: 'fill', /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.ohlc.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upLineColor = options.upLineColor || options.lineColor, hoverStroke = stateOptions.hover.upLineColor || upLineColor, selectStroke = stateOptions.select.upLineColor || upLineColor; // Add custom line color for points going up (close > open). // Fill is handled by OHLCSeries' getAttribs. each(series.points, function (point) { if (point.open < point.close) { // If an individual line color is set, we need to merge the // point attributes, because they are shared between all up // points by inheritance from OHCLSeries. if (point.lineColor) { point.pointAttr = merge(point.pointAttr); upLineColor = point.lineColor; } point.pointAttr[''].stroke = upLineColor; point.pointAttr.hover.stroke = hoverStroke; point.pointAttr.select.stroke = selectStroke; } }); }, /** * Draw the data points */ drawPoints: function () { var series = this, //state = series.state, points = series.points, chart = series.chart, pointAttr, seriesPointAttr = series.pointAttr[''], plotOpen, plotClose, topBox, bottomBox, hasTopWhisker, hasBottomWhisker, crispCorr, crispX, graphic, path, halfWidth; each(points, function (point) { graphic = point.graphic; if (point.plotY !== UNDEFINED) { pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || seriesPointAttr; // crisp vector coordinates crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathRound(point.plotX) - crispCorr; // #2596 plotOpen = point.plotOpen; plotClose = point.plotClose; topBox = math.min(plotOpen, plotClose); bottomBox = math.max(plotOpen, plotClose); halfWidth = mathRound(point.shapeArgs.width / 2); hasTopWhisker = mathRound(topBox) !== mathRound(point.plotY); hasBottomWhisker = bottomBox !== point.yBottom; topBox = mathRound(topBox) + crispCorr; bottomBox = mathRound(bottomBox) + crispCorr; // Create the path. Due to a bug in Chrome 49, the path is first instanciated // with no values, then the values pushed. For unknown reasons, instanciated // the path array with all the values would lead to a crash when updating // frequently (#5193). path = []; path.push( 'M', crispX - halfWidth, bottomBox, 'L', crispX - halfWidth, topBox, 'L', crispX + halfWidth, topBox, 'L', crispX + halfWidth, bottomBox, 'Z', // Use a close statement to ensure a nice rectangle #2602 'M', crispX, topBox, 'L', crispX, hasTopWhisker ? mathRound(point.plotY) : topBox, // #460, #2094 'M', crispX, bottomBox, 'L', crispX, hasBottomWhisker ? mathRound(point.yBottom) : bottomBox // #460, #2094 ); if (graphic) { graphic .attr(pointAttr) // #3897 .animate({ d: path }); } else { point.graphic = chart.renderer.path(path) .attr(pointAttr) .add(series.group) .shadow(series.options.shadow); } } }); } }); seriesTypes.candlestick = CandlestickSeries; /* **************************************************************************** * End Candlestick series code * *****************************************************************************/ /* **************************************************************************** * Start Flags series code * *****************************************************************************/ var symbols = SVGRenderer.prototype.symbols; // 1 - set default options defaultPlotOptions.flags = merge(defaultPlotOptions.column, { fillColor: 'white', lineWidth: 1, pointRange: 0, // #673 //radius: 2, shape: 'flag', stackDistance: 12, states: { hover: { lineColor: 'black', fillColor: '#FCFFC5' } }, style: { fontSize: '11px', fontWeight: 'bold', textAlign: 'center' }, tooltip: { pointFormat: '{point.text}<br/>' }, threshold: null, y: -30 }); // 2 - Create the CandlestickSeries object seriesTypes.flags = extendClass(seriesTypes.column, { type: 'flags', sorted: false, noSharedTooltip: true, allowDG: false, takeOrdinalPosition: false, // #1074 trackerGroups: ['markerGroup'], forceCrop: true, /** * Inherit the initialization from base Series */ init: Series.prototype.init, /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'fillColor', stroke: 'color', 'stroke-width': 'lineWidth', r: 'radius' }, /** * Extend the translate method by placing the point on the related series */ translate: function () { seriesTypes.column.prototype.translate.apply(this); var series = this, options = series.options, chart = series.chart, points = series.points, cursor = points.length - 1, point, lastPoint, optionsOnSeries = options.onSeries, onSeries = optionsOnSeries && chart.get(optionsOnSeries), onKey = options.onKey || 'y', step = onSeries && onSeries.options.step, onData = onSeries && onSeries.points, i = onData && onData.length, xAxis = series.xAxis, xAxisExt = xAxis.getExtremes(), xOffset = 0, leftPoint, lastX, rightPoint, currentDataGrouping; // relate to a master series if (onSeries && onSeries.visible && i) { xOffset = (onSeries.pointXOffset || 0) + (onSeries.barW || 0) / 2; currentDataGrouping = onSeries.currentDataGrouping; lastX = onData[i - 1].x + (currentDataGrouping ? currentDataGrouping.totalRange : 0); // #2374 // sort the data points points.sort(function (a, b) { return (a.x - b.x); }); onKey = 'plot' + onKey[0].toUpperCase() + onKey.substr(1); while (i-- && points[cursor]) { point = points[cursor]; leftPoint = onData[i]; if (leftPoint.x <= point.x && leftPoint[onKey] !== undefined) { if (point.x <= lastX) { // #803 point.plotY = leftPoint[onKey]; // interpolate between points, #666 if (leftPoint.x < point.x && !step) { rightPoint = onData[i + 1]; if (rightPoint && rightPoint[onKey] !== UNDEFINED) { point.plotY += ((point.x - leftPoint.x) / (rightPoint.x - leftPoint.x)) * // the distance ratio, between 0 and 1 (rightPoint[onKey] - leftPoint[onKey]); // the y distance } } } cursor--; i++; // check again for points in the same x position if (cursor < 0) { break; } } } } // Add plotY position and handle stacking each(points, function (point, i) { var stackIndex; // Undefined plotY means the point is either on axis, outside series range or hidden series. // If the series is outside the range of the x axis it should fall through with // an undefined plotY, but then we must remove the shapeArgs (#847). if (point.plotY === UNDEFINED) { if (point.x >= xAxisExt.min && point.x <= xAxisExt.max) { // we're inside xAxis range point.plotY = chart.chartHeight - xAxis.bottom - (xAxis.opposite ? xAxis.height : 0) + xAxis.offset - chart.plotTop; } else { point.shapeArgs = {}; // 847 } } point.plotX += xOffset; // #2049 // if multiple flags appear at the same x, order them into a stack lastPoint = points[i - 1]; if (lastPoint && lastPoint.plotX === point.plotX) { if (lastPoint.stackIndex === UNDEFINED) { lastPoint.stackIndex = 0; } stackIndex = lastPoint.stackIndex + 1; } point.stackIndex = stackIndex; // #3639 }); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, seriesPointAttr = series.pointAttr[''], points = series.points, chart = series.chart, renderer = chart.renderer, plotX, plotY, options = series.options, optionsY = options.y, shape, i, point, graphic, stackIndex, anchorX, anchorY, outsideRight, yAxis = series.yAxis, text; i = points.length; while (i--) { point = points[i]; outsideRight = point.plotX > series.xAxis.len; plotX = point.plotX; if (plotX > 0) { // #3119 plotX -= pick(point.lineWidth, options.lineWidth) % 2; // #4285 } stackIndex = point.stackIndex; shape = point.options.shape || options.shape; plotY = point.plotY; if (plotY !== UNDEFINED) { plotY = point.plotY + optionsY - (stackIndex !== UNDEFINED && stackIndex * options.stackDistance); } anchorX = stackIndex ? UNDEFINED : point.plotX; // skip connectors for higher level stacked points anchorY = stackIndex ? UNDEFINED : point.plotY; graphic = point.graphic; // only draw the point if y is defined and the flag is within the visible area if (plotY !== UNDEFINED && plotX >= 0 && !outsideRight) { // shortcuts pointAttr = point.pointAttr[point.selected ? 'select' : ''] || seriesPointAttr; text = pick(point.options.title, options.title, 'A'); if (graphic) { // update graphic.attr({ text: text // first apply text, so text will be centered later }).attr({ x: plotX, y: plotY, r: pointAttr.r, anchorX: anchorX, anchorY: anchorY }); } else { graphic = point.graphic = renderer.label( text, plotX, plotY, shape, anchorX, anchorY, options.useHTML ) .css(merge(options.style, point.style)) .attr(pointAttr) .attr({ align: shape === 'flag' ? 'left' : 'center', width: options.width, height: options.height }) .add(series.markerGroup) .shadow(options.shadow); } // Set the tooltip anchor position point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - plotX] : [plotX, plotY]; } else if (graphic) { point.graphic = graphic.destroy(); } } }, /** * Extend the column trackers with listeners to expand and contract stacks */ drawTracker: function () { var series = this, points = series.points; TrackerMixin.drawTrackerPoint.apply(this); // Bring each stacked flag up on mouse over, this allows readability of vertically // stacked elements as well as tight points on the x axis. #1924. each(points, function (point) { var graphic = point.graphic; if (graphic) { addEvent(graphic.element, 'mouseover', function () { // Raise this point if (point.stackIndex > 0 && !point.raised) { point._y = graphic.y; graphic.attr({ y: point._y - 8 }); point.raised = true; } // Revert other raised points each(points, function (otherPoint) { if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) { otherPoint.graphic.attr({ y: otherPoint._y }); otherPoint.raised = false; } }); }); } }); }, /** * Disable animation */ animate: noop, buildKDTree: noop, setClip: noop }); // create the flag icon with anchor symbols.flag = function (x, y, w, h, options) { var anchorX = (options && options.anchorX) || x, anchorY = (options && options.anchorY) || y; return [ 'M', anchorX, anchorY, 'L', x, y + h, x, y, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }; // create the circlepin and squarepin icons with anchor each(['circle', 'square'], function (shape) { symbols[shape + 'pin'] = function (x, y, w, h, options) { var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, labelTopOrBottomY; // For single-letter flags, make sure circular flags are not taller than their width if (shape === 'circle' && h > w) { x -= mathRound((h - w) / 2); w = h; } path = symbols[shape](x, y, w, h); if (anchorX && anchorY) { // if the label is below the anchor, draw the connecting line from the top edge of the label // otherwise start drawing from the bottom edge labelTopOrBottomY = (y > anchorY) ? y : y + h; path.push('M', anchorX, labelTopOrBottomY, 'L', anchorX, anchorY); } return path; }; }); // The symbol callbacks are generated on the SVGRenderer object in all browsers. Even // VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === Highcharts.VMLRenderer) { each(['flag', 'circlepin', 'squarepin'], function (shape) { VMLRenderer.prototype.symbols[shape] = symbols[shape]; }); } /* **************************************************************************** * End Flags series code * *****************************************************************************/ var defaultScrollbarOptions = { //enabled: true height: isTouchDevice ? 20 : 14, barBackgroundColor: '#bfc8d1', barBorderRadius: 0, barBorderWidth: 1, barBorderColor: '#bfc8d1', buttonArrowColor: '#666', buttonBackgroundColor: '#ebe7e8', buttonBorderColor: '#bbb', buttonBorderRadius: 0, buttonBorderWidth: 1, //showFull: true, margin: 10, minWidth: 6, rifleColor: '#666', zIndex: 3, step: 0.2, //size: null, trackBackgroundColor: '#eeeeee', trackBorderColor: '#eeeeee', trackBorderWidth: 1, // trackBorderRadius: 0 liveRedraw: hasSVG && !isTouchDevice }; defaultOptions.scrollbar = merge(true, defaultScrollbarOptions, defaultOptions.scrollbar); /** * The Scrollbar class * @param {Object} renderer * @param {Object} options * @param {Object} chart */ function Scrollbar(renderer, options, chart) { this.scrollbarButtons = []; this.renderer = renderer; this.userOptions = options; this.options = merge(defaultScrollbarOptions, options); this.chart = chart; this.size = pick(this.options.size, this.options.height); // backward compatibility // Init this.render(); this.initEvents(); this.addEvents(); } Scrollbar.prototype = { /** * Render scrollbar with all required items. */ render: function () { var scroller = this, renderer = scroller.renderer, options = scroller.options, strokeWidth = options.trackBorderWidth, scrollbarStrokeWidth = options.barBorderWidth, size = scroller.size, group; // Draw the scrollbar group: scroller.group = group = renderer.g(PREFIX + 'scrollbar').attr({ zIndex: options.zIndex, translateY: -99999 }).add(); // Draw the scrollbar track: scroller.track = renderer.rect().attr({ height: size, width: size, y: -strokeWidth % 2 / 2, x: -strokeWidth % 2 / 2, 'stroke-width': strokeWidth, fill: options.trackBackgroundColor, stroke: options.trackBorderColor, r: options.trackBorderRadius || 0 }).add(group); // Draw the scrollbar itself: scroller.scrollbarGroup = renderer.g().add(group); scroller.scrollbar = renderer.rect().attr({ height: size, width: size, y: -scrollbarStrokeWidth % 2 / 2, x: -scrollbarStrokeWidth % 2 / 2, 'stroke-width': scrollbarStrokeWidth, fill: options.barBackgroundColor, stroke: options.barBorderColor, r: options.barBorderRadius || 0 }).add(scroller.scrollbarGroup); // Draw the scrollbat rifles: scroller.scrollbarRifles = renderer.path(scroller.swapXY([ M, -3, size / 4, L, -3, 2 * size / 3, M, 0, size / 4, L, 0, 2 * size / 3, M, 3, size / 4, L, 3, 2 * size / 3 ], options.vertical)).attr({ stroke: options.rifleColor, 'stroke-width': 1 }).add(scroller.scrollbarGroup); // Draw the buttons: scroller.drawScrollbarButton(0); scroller.drawScrollbarButton(1); }, /** * Position the scrollbar, method called from a parent with defined dimensions * @param {Number} x - x-position on the chart * @param {Number} y - y-position on the chart * @param {Number} width - width of the scrollbar * @param {Number} height - height of the scorllbar */ position: function (x, y, width, height) { var scroller = this, options = scroller.options, vertical = options.vertical, xOffset = height, yOffset = 0, method = scroller.rendered ? 'animate' : 'attr'; scroller.x = x; scroller.y = y + options.trackBorderWidth; scroller.width = width; // width with buttons scroller.height = height; scroller.xOffset = xOffset; scroller.yOffset = yOffset; // If Scrollbar is a vertical type, swap options: if (vertical) { scroller.width = scroller.yOffset = width = yOffset = scroller.size; scroller.xOffset = xOffset = 0; scroller.barWidth = height - width * 2; // width without buttons scroller.x = x = x + scroller.options.margin; } else { scroller.height = scroller.xOffset = height = xOffset = scroller.size; scroller.barWidth = width - height * 2; // width without buttons scroller.y = scroller.y + scroller.options.margin; } // Set general position for a group: scroller.group[method]({ translateX: x, translateY: scroller.y }); // Resize background/track: scroller.track[method]({ width: width, height: height }); // Move right/bottom button ot it's place: scroller.scrollbarButtons[1].attr({ translateX: vertical ? 0 : width - xOffset, translateY: vertical ? height - yOffset : 0 }); }, /** * Draw the scrollbar buttons with arrows * @param {Number} index 0 is left, 1 is right */ drawScrollbarButton: function (index) { var scroller = this, renderer = scroller.renderer, scrollbarButtons = scroller.scrollbarButtons, options = scroller.options, size = scroller.size, group; group = renderer.g().add(scroller.group); scrollbarButtons.push(group); // Button rect: renderer.rect( -0.5, -0.5, size + 1, // +1 to compensate for crispifying in rect method size + 1, options.buttonBorderRadius, options.buttonBorderWidth ).attr({ stroke: options.buttonBorderColor, 'stroke-width': options.buttonBorderWidth, fill: options.buttonBackgroundColor }).add(group); // Button arrow: renderer.path(scroller.swapXY([ 'M', size / 2 + (index ? -1 : 1), size / 2 - 3, 'L', size / 2 + (index ? -1 : 1), size / 2 + 3, 'L', size / 2 + (index ? 2 : -2), size / 2 ], options.vertical)).attr({ fill: options.buttonArrowColor }).add(group); }, /** * When we have vertical scrollbar, rifles are rotated, the same for arrow in buttons: * @param {Array} path - path to be rotated * @param {Boolean} vertical - if vertical scrollbar, swap x-y values */ swapXY: function (path, vertical) { var i, len = path.length, temp; if (vertical) { for (i = 0; i < len; i += 3) { temp = path[i + 1]; path[i + 1] = path[i + 2]; path[i + 2] = temp; } } return path; }, /** * Set scrollbar size, with a given scale. * @param {Number} from - scale (0-1) where bar should start * @param {Number} to - scale (0-1) where bar should end */ setRange: function (from, to) { var scroller = this, options = scroller.options, vertical = options.vertical, minWidth = options.minWidth, fullWidth = scroller.barWidth, fromPX, toPX, newPos, newSize, newRiflesPos, method = this.rendered && !this.hasDragged ? 'animate' : 'attr'; if (!defined(fullWidth)) { return; } from = Math.max(from, 0); fromPX = fullWidth * from; toPX = fullWidth * Math.min(to, 1); scroller.calculatedWidth = newSize = correctFloat(toPX - fromPX); // We need to recalculate position, if minWidth is used if (newSize < minWidth) { fromPX = (fullWidth - minWidth + newSize) * from; newSize = minWidth; } newPos = Math.floor(fromPX + scroller.xOffset + scroller.yOffset); newRiflesPos = newSize / 2 - 0.5; // -0.5 -> rifle line width / 2 // Store current position: scroller.from = from; scroller.to = to; if (!vertical) { scroller.scrollbarGroup[method]({ translateX: newPos }); scroller.scrollbar[method]({ width: newSize }); scroller.scrollbarRifles[method]({ translateX: newRiflesPos }); scroller.scrollbarLeft = newPos; scroller.scrollbarTop = 0; } else { scroller.scrollbarGroup[method]({ translateY: newPos }); scroller.scrollbar[method]({ height: newSize }); scroller.scrollbarRifles[method]({ translateY: newRiflesPos }); scroller.scrollbarTop = newPos; scroller.scrollbarLeft = 0; } if (newSize <= 12) { scroller.scrollbarRifles.hide(); } else { scroller.scrollbarRifles.show(true); } // Show or hide the scrollbar based on the showFull setting if (options.showFull === false) { if (from <= 0 && to >= 1) { scroller.group.hide(); } else { scroller.group.show(); } } scroller.rendered = true; }, /** * Init events methods, so we have an access to the Scrollbar itself */ initEvents: function () { var scroller = this; /** * Event handler for the mouse move event. */ scroller.mouseMoveHandler = function (e) { var normalizedEvent = scroller.chart.pointer.normalize(e), options = scroller.options, direction = options.vertical ? 'chartY' : 'chartX', initPositions = scroller.initPositions, scrollPosition, chartPosition, change; // In iOS, a mousemove event with e.pageX === 0 is fired when holding the finger // down in the center of the scrollbar. This should be ignored. if (scroller.grabbedCenter && (!e.touches || e.touches[0][direction] !== 0)) { // #4696, scrollbar failed on Android chartPosition = scroller.cursorToScrollbarPosition(normalizedEvent)[direction]; scrollPosition = scroller[direction]; change = chartPosition - scrollPosition; scroller.hasDragged = true; scroller.updatePosition(initPositions[0] + change, initPositions[1] + change); if (scroller.hasDragged) { fireEvent(scroller, 'changed', { from: scroller.from, to: scroller.to, trigger: 'scrollbar', DOMType: e.type, DOMEvent: e }); } } }; /** * Event handler for the mouse up event. */ scroller.mouseUpHandler = function (e) { if (scroller.hasDragged) { fireEvent(scroller, 'changed', { from: scroller.from, to: scroller.to, trigger: 'scrollbar', DOMType: e.type, DOMEvent: e }); } scroller.grabbedCenter = scroller.hasDragged = scroller.chartX = scroller.chartY = null; }; scroller.mouseDownHandler = function (e) { var normalizedEvent = scroller.chart.pointer.normalize(e), mousePosition = scroller.cursorToScrollbarPosition(normalizedEvent); scroller.chartX = mousePosition.chartX; scroller.chartY = mousePosition.chartY; scroller.initPositions = [scroller.from, scroller.to]; scroller.grabbedCenter = true; }; scroller.buttonToMinClick = function (e) { var range = correctFloat(scroller.to - scroller.from) * scroller.options.step; scroller.updatePosition(correctFloat(scroller.from - range), correctFloat(scroller.to - range)); fireEvent(scroller, 'changed', { from: scroller.from, to: scroller.to, trigger: 'scrollbar', DOMEvent: e }); }; scroller.buttonToMaxClick = function (e) { var range = (scroller.to - scroller.from) * scroller.options.step; scroller.updatePosition(scroller.from + range, scroller.to + range); fireEvent(scroller, 'changed', { from: scroller.from, to: scroller.to, trigger: 'scrollbar', DOMEvent: e }); }; scroller.trackClick = function (e) { var normalizedEvent = scroller.chart.pointer.normalize(e), range = scroller.to - scroller.from, top = scroller.y + scroller.scrollbarTop, left = scroller.x + scroller.scrollbarLeft; if ((scroller.options.vertical && normalizedEvent.chartY > top) || (!scroller.options.vertical && normalizedEvent.chartX > left)) { // On the top or on the left side of the track: scroller.updatePosition(scroller.from + range, scroller.to + range); } else { // On the bottom or the right side of the track: scroller.updatePosition(scroller.from - range, scroller.to - range); } fireEvent(scroller, 'changed', { from: scroller.from, to: scroller.to, trigger: 'scrollbar', DOMEvent: e }); }; }, /** * Get normalized (0-1) cursor position over the scrollbar * @param {Event} normalizedEvent - normalized event, with chartX and chartY values * @return {Object} Local position {chartX, chartY} */ cursorToScrollbarPosition: function (normalizedEvent) { var scroller = this, options = scroller.options, minWidthDifference = options.minWidth > scroller.calculatedWidth ? options.minWidth : 0; // minWidth distorts translation return { chartX: (normalizedEvent.chartX - scroller.x - scroller.xOffset) / (scroller.barWidth - minWidthDifference), chartY: (normalizedEvent.chartY - scroller.y - scroller.yOffset) / (scroller.barWidth - minWidthDifference) }; }, /** * Update position option in the Scrollbar, with normalized 0-1 scale */ updatePosition: function (from, to) { if (to > 1) { from = correctFloat(1 - correctFloat(to - from)); to = 1; } if (from < 0) { to = correctFloat(to - from); from = 0; } this.from = from; this.to = to; }, /** * Set up the mouse and touch events for the Scrollbar */ addEvents: function () { var buttonsOrder = this.options.inverted ? [1, 0] : [0, 1], buttons = this.scrollbarButtons, bar = this.scrollbarGroup.element, track = this.track.element, mouseDownHandler = this.mouseDownHandler, mouseMoveHandler = this.mouseMoveHandler, mouseUpHandler = this.mouseUpHandler, _events; // Mouse events _events = [ [buttons[buttonsOrder[0]].element, 'click', this.buttonToMinClick], [buttons[buttonsOrder[1]].element, 'click', this.buttonToMaxClick], [track, 'click', this.trackClick], [bar, 'mousedown', mouseDownHandler], [doc, 'mousemove', mouseMoveHandler], [doc, 'mouseup', mouseUpHandler] ]; // Touch events if (hasTouch) { _events.push( [bar, 'touchstart', mouseDownHandler], [doc, 'touchmove', mouseMoveHandler], [doc, 'touchend', mouseUpHandler] ); } // Add them all each(_events, function (args) { addEvent.apply(null, args); }); this._events = _events; }, /** * Removes the event handlers attached previously with addEvents. */ removeEvents: function () { each(this._events, function (args) { removeEvent.apply(null, args); }); this._events = UNDEFINED; }, /** * Destroys allocated elements. */ destroy: function () { var scroller = this; // Disconnect events added in addEvents scroller.removeEvents(); // Destroy properties each([scroller.track, scroller.scrollbarRifles, scroller.scrollbar, scroller.scrollbarGroup, scroller.group], function (prop) { if (prop && prop.destroy) { prop = prop.destroy(); } }); // Destroy elements in collection destroyObjectProperties(scroller.scrollbarButtons); } }; /** * Wrap axis initialization and create scrollbar if enabled: */ wrap(Axis.prototype, 'init', function (proceed) { var axis = this; proceed.apply(axis, [].slice.call(arguments, 1)); if (axis.options.scrollbar && axis.options.scrollbar.enabled) { // Predefined options: axis.options.scrollbar.vertical = !axis.horiz; axis.options.startOnTick = axis.options.endOnTick = false; axis.scrollbar = new Scrollbar(axis.chart.renderer, axis.options.scrollbar, axis.chart); addEvent(axis.scrollbar, 'changed', function (e) { var unitedMin = Math.min(pick(axis.options.min, axis.min), axis.min, axis.dataMin), unitedMax = Math.max(pick(axis.options.max, axis.max), axis.max, axis.dataMax), range = unitedMax - unitedMin, to, from; if ((axis.horiz && !axis.reversed) || (!axis.horiz && axis.reversed)) { to = unitedMin + range * this.to; from = unitedMin + range * this.from; } else { // y-values in browser are reversed, but this also applies for reversed horizontal axis: to = unitedMin + range * (1 - this.from); from = unitedMin + range * (1 - this.to); } axis.setExtremes(from, to, true, false, e); }); } }); /** * Wrap rendering axis, and update scrollbar if one is created: */ wrap(Axis.prototype, 'render', function (proceed) { var axis = this, scrollMin = Math.min(pick(axis.options.min, axis.min), axis.min, axis.dataMin), scrollMax = Math.max(pick(axis.options.max, axis.max), axis.max, axis.dataMax), scrollbar = axis.scrollbar, from, to; proceed.apply(axis, [].slice.call(arguments, 1)); if (scrollbar) { if (axis.horiz) { scrollbar.position( axis.left, axis.top + axis.height + axis.offset + 2 + (axis.opposite ? 0 : axis.axisTitleMargin), axis.width, axis.height ); } else { scrollbar.position( axis.left + axis.width + 2 + axis.offset + (axis.opposite ? axis.axisTitleMargin : 0), axis.top, axis.width, axis.height ); } if (isNaN(scrollMin) || isNaN(scrollMax) || !defined(axis.min) || !defined(axis.max)) { scrollbar.setRange(0, 0); // default action: when there is not extremes on the axis, but scrollbar exists, make it full size } else { from = (axis.min - scrollMin) / (scrollMax - scrollMin); to = (axis.max - scrollMin) / (scrollMax - scrollMin); if ((axis.horiz && !axis.reversed) || (!axis.horiz && axis.reversed)) { scrollbar.setRange(from, to); } else { scrollbar.setRange(1 - to, 1 - from); // inverse vertical axis } } } }); /** * Make space for a scrollbar */ wrap(Axis.prototype, 'getOffset', function (proceed) { var axis = this, index = axis.horiz ? 2 : 1, scrollbar = axis.scrollbar; proceed.apply(axis, [].slice.call(arguments, 1)); if (scrollbar) { axis.chart.axisOffset[index] += scrollbar.size + scrollbar.options.margin; } }); /** * Destroy scrollbar when connected to the specific axis */ wrap(Axis.prototype, 'destroy', function (proceed) { if (this.scrollbar) { this.scrollbar = this.scrollbar.destroy(); } proceed.apply(this, [].slice.call(arguments, 1)); }); Highcharts.Scrollbar = Scrollbar; /* **************************************************************************** * Start Navigator code * *****************************************************************************/ var units = [].concat(defaultDataGroupingUnits), // copy defaultSeriesType, // Finding the min or max of a set of variables where we don't know if they are defined, // is a pattern that is repeated several places in Highcharts. Consider making this // a global utility method. numExt = function (extreme) { var numbers = grep(arguments, isNumber); if (numbers.length) { return Math[extreme].apply(0, numbers); } }; // add more resolution to units units[4] = ['day', [1, 2, 3, 4]]; // allow more days units[5] = ['week', [1, 2, 3]]; // allow more weeks defaultSeriesType = seriesTypes.areaspline === UNDEFINED ? 'line' : 'areaspline'; extend(defaultOptions, { navigator: { //enabled: true, handles: { backgroundColor: '#ebe7e8', borderColor: '#b2b1b6' }, height: 40, margin: 25, maskFill: 'rgba(128,179,236,0.3)', maskInside: true, outlineColor: '#b2b1b6', outlineWidth: 1, series: { type: defaultSeriesType, color: '#4572A7', compare: null, fillOpacity: 0.05, dataGrouping: { approximation: 'average', enabled: true, groupPixelWidth: 2, smoothed: true, units: units }, dataLabels: { enabled: false, zIndex: 2 // #1839 }, id: PREFIX + 'navigator-series', lineColor: null, // Allow color setting while disallowing default candlestick setting (#4602) lineWidth: 1, marker: { enabled: false }, pointRange: 0, shadow: false, threshold: null }, //top: undefined, xAxis: { tickWidth: 0, lineWidth: 0, gridLineColor: '#EEE', gridLineWidth: 1, tickPixelInterval: 200, labels: { align: 'left', style: { color: '#888' }, x: 3, y: -4 }, crosshair: false }, yAxis: { gridLineWidth: 0, startOnTick: false, endOnTick: false, minPadding: 0.1, maxPadding: 0.1, labels: { enabled: false }, crosshair: false, title: { text: null }, tickWidth: 0 } } }); /** * The Navigator class * @param {Object} chart */ function Navigator(chart) { var chartOptions = chart.options, navigatorOptions = chartOptions.navigator, navigatorEnabled = navigatorOptions.enabled, scrollbarOptions = chartOptions.scrollbar, scrollbarEnabled = scrollbarOptions.enabled, height = navigatorEnabled ? navigatorOptions.height : 0, scrollbarHeight = scrollbarEnabled ? scrollbarOptions.height : 0; this.handles = []; this.elementsToDestroy = []; // Array containing the elements to destroy when Navigator is destroyed this.chart = chart; this.setBaseSeries(); this.height = height; this.scrollbarHeight = scrollbarHeight; this.scrollbarEnabled = scrollbarEnabled; this.navigatorEnabled = navigatorEnabled; this.navigatorOptions = navigatorOptions; this.outlineHeight = height + scrollbarHeight; // Run scroller this.init(); } Navigator.prototype = { /** * Draw one of the handles on the side of the zoomed range in the navigator * @param {Number} x The x center for the handle * @param {Number} index 0 for left and 1 for right */ drawHandle: function (x, index) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, elementsToDestroy = scroller.elementsToDestroy, handles = scroller.handles, handlesOptions = scroller.navigatorOptions.handles, attr = { fill: handlesOptions.backgroundColor, stroke: handlesOptions.borderColor, 'stroke-width': 1 }, tempElem; // create the elements if (!scroller.rendered) { // the group handles[index] = renderer.g('navigator-handle-' + ['left', 'right'][index]) .css({ cursor: 'ew-resize' }) .attr({ zIndex: 10 - index }) // zIndex = 3 for right handle, 4 for left / 10 - #2908 .add(); // the rectangle tempElem = renderer.rect(-4.5, 0, 9, 16, 0, 1) .attr(attr) .add(handles[index]); elementsToDestroy.push(tempElem); // the rifles tempElem = renderer .path([ 'M', -1.5, 4, 'L', -1.5, 12, 'M', 0.5, 4, 'L', 0.5, 12 ]).attr(attr) .add(handles[index]); elementsToDestroy.push(tempElem); } // Place it handles[index][scroller.rendered && !scroller.hasDragged ? 'animate' : 'attr']({ translateX: scroller.scrollerLeft + scroller.scrollbarHeight + parseInt(x, 10), translateY: scroller.top + scroller.height / 2 - 8 }); }, /** * Render the navigator * @param {Number} min X axis value minimum * @param {Number} max X axis value maximum * @param {Number} pxMin Pixel value minimum * @param {Number} pxMax Pixel value maximum */ render: function (min, max, pxMin, pxMax) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, navigatorLeft, navigatorWidth, scrollerLeft, scrollerWidth, navigatorGroup = scroller.navigatorGroup, scrollbarHeight = scroller.scrollbarHeight, xAxis = scroller.xAxis, navigatorOptions = scroller.navigatorOptions, height = scroller.height, top = scroller.top, navigatorEnabled = scroller.navigatorEnabled, outlineWidth = navigatorOptions.outlineWidth, halfOutline = outlineWidth / 2, zoomedMin, zoomedMax, outlineHeight = scroller.outlineHeight, outlineTop = top + halfOutline, rendered = scroller.rendered, verb; // Don't render the navigator until we have data (#486, #4202, #5172). Don't redraw while moving the handles (#4703). if (!isNumber(min) || !isNumber(max) || (scroller.hasDragged && !defined(pxMin))) { return; } scroller.navigatorLeft = navigatorLeft = pick( xAxis.left, chart.plotLeft + scrollbarHeight // in case of scrollbar only, without navigator ); scroller.navigatorWidth = navigatorWidth = pick(xAxis.len, chart.plotWidth - 2 * scrollbarHeight); scroller.scrollerLeft = scrollerLeft = navigatorLeft - scrollbarHeight; scroller.scrollerWidth = scrollerWidth = scrollerWidth = navigatorWidth + 2 * scrollbarHeight; // Get the pixel position of the handles pxMin = pick(pxMin, xAxis.translate(min)); pxMax = pick(pxMax, xAxis.translate(max)); if (!isNumber(pxMin) || mathAbs(pxMin) === Infinity) { // Verify (#1851, #2238) pxMin = 0; pxMax = scrollerWidth; } // Are we below the minRange? (#2618) if (xAxis.translate(pxMax, true) - xAxis.translate(pxMin, true) < chart.xAxis[0].minRange) { return; } // handles are allowed to cross, but never exceed the plot area scroller.zoomedMax = mathMin(mathMax(pxMin, pxMax, 0), navigatorWidth); scroller.zoomedMin = mathMin(mathMax(scroller.fixedWidth ? scroller.zoomedMax - scroller.fixedWidth : mathMin(pxMin, pxMax), 0), navigatorWidth); scroller.range = scroller.zoomedMax - scroller.zoomedMin; zoomedMax = mathRound(scroller.zoomedMax); zoomedMin = mathRound(scroller.zoomedMin); if (!rendered) { if (navigatorEnabled) { // draw the navigator group scroller.navigatorGroup = navigatorGroup = renderer.g('navigator') .attr({ zIndex: 3 }) .add(); scroller.leftShade = renderer.rect() .attr({ fill: navigatorOptions.maskFill }).add(navigatorGroup); if (navigatorOptions.maskInside) { scroller.leftShade.css({ cursor: 'ew-resize' }); } else { scroller.rightShade = renderer.rect() .attr({ fill: navigatorOptions.maskFill }).add(navigatorGroup); } scroller.outline = renderer.path() .attr({ 'stroke-width': outlineWidth, stroke: navigatorOptions.outlineColor }) .add(navigatorGroup); } } // place elements verb = rendered && !scroller.hasDragged ? 'animate' : 'attr'; if (navigatorEnabled) { scroller.leftShade[verb](navigatorOptions.maskInside ? { x: navigatorLeft + zoomedMin, y: top, width: zoomedMax - zoomedMin, height: height } : { x: navigatorLeft, y: top, width: zoomedMin, height: height }); if (scroller.rightShade) { scroller.rightShade[verb]({ x: navigatorLeft + zoomedMax, y: top, width: navigatorWidth - zoomedMax, height: height }); } scroller.outline[verb]({ d: [ M, scrollerLeft, outlineTop, // left L, navigatorLeft + zoomedMin - halfOutline, outlineTop, // upper left of zoomed range navigatorLeft + zoomedMin - halfOutline, outlineTop + outlineHeight, // lower left of z.r. L, navigatorLeft + zoomedMax - halfOutline, outlineTop + outlineHeight, // lower right of z.r. L, navigatorLeft + zoomedMax - halfOutline, outlineTop, // upper right of z.r. scrollerLeft + scrollerWidth, outlineTop // right ].concat(navigatorOptions.maskInside ? [ M, navigatorLeft + zoomedMin + halfOutline, outlineTop, // upper left of zoomed range L, navigatorLeft + zoomedMax - halfOutline, outlineTop // upper right of z.r. ] : []) }); // draw handles scroller.drawHandle(zoomedMin + halfOutline, 0); scroller.drawHandle(zoomedMax + halfOutline, 1); } if (scroller.scrollbar) { scroller.scrollbar.hasDragged = scroller.hasDragged; // Keep scale 0-1 scroller.scrollbar.position( scroller.scrollerLeft, scroller.top + (navigatorEnabled ? scroller.height : -scroller.scrollbarHeight), scroller.scrollerWidth, scroller.scrollbarHeight ); scroller.scrollbar.setRange( zoomedMin / navigatorWidth, zoomedMax / navigatorWidth ); } scroller.rendered = true; }, /** * Set up the mouse and touch events for the navigator */ addEvents: function () { var chart = this.chart, container = chart.container, mouseDownHandler = this.mouseDownHandler, mouseMoveHandler = this.mouseMoveHandler, mouseUpHandler = this.mouseUpHandler, _events; // Mouse events _events = [ [container, 'mousedown', mouseDownHandler], [container, 'mousemove', mouseMoveHandler], [doc, 'mouseup', mouseUpHandler] ]; // Touch events if (hasTouch) { _events.push( [container, 'touchstart', mouseDownHandler], [container, 'touchmove', mouseMoveHandler], [doc, 'touchend', mouseUpHandler] ); } // Add them all each(_events, function (args) { addEvent.apply(null, args); }); this._events = _events; // Data events if (this.series) { addEvent(this.series.xAxis, 'foundExtremes', function () { chart.scroller.modifyNavigatorAxisExtremes(); }); } addEvent(chart, 'redraw', function () { // Move the scrollbar after redraw, like after data updata even if axes don't redraw var scroller = this.scroller, xAxis = scroller && scroller.baseSeries && scroller.baseSeries.xAxis; if (xAxis) { scroller.render(xAxis.min, xAxis.max); } }); }, /** * Removes the event handlers attached previously with addEvents. */ removeEvents: function () { each(this._events, function (args) { removeEvent.apply(null, args); }); this._events = UNDEFINED; this.removeBaseSeriesEvents(); }, removeBaseSeriesEvents: function () { if (this.navigatorEnabled && this.baseSeries && this.baseSeries.xAxis && this.navigatorOptions.adaptToUpdatedData !== false) { removeEvent(this.baseSeries, 'updatedData', this.updatedDataHandler); removeEvent(this.baseSeries.xAxis, 'foundExtremes', this.modifyBaseAxisExtremes); } }, /** * Initiate the Navigator object */ init: function () { var scroller = this, chart = scroller.chart, xAxis, yAxis, scrollbarHeight = scroller.scrollbarHeight, navigatorOptions = scroller.navigatorOptions, height = scroller.height, top = scroller.top, dragOffset, baseSeries = scroller.baseSeries; /** * Event handler for the mouse down event. */ scroller.mouseDownHandler = function (e) { e = chart.pointer.normalize(e); var zoomedMin = scroller.zoomedMin, zoomedMax = scroller.zoomedMax, top = scroller.top, scrollerLeft = scroller.scrollerLeft, scrollerWidth = scroller.scrollerWidth, navigatorLeft = scroller.navigatorLeft, navigatorWidth = scroller.navigatorWidth, scrollbarPad = scroller.scrollbarPad || 0, range = scroller.range, chartX = e.chartX, chartY = e.chartY, baseXAxis = chart.xAxis[0], fixedMax, ext, handleSensitivity = isTouchDevice ? 10 : 7, left; if (chartY > top && chartY < top + height) { // we're vertically inside the navigator // grab the left handle if (math.abs(chartX - zoomedMin - navigatorLeft) < handleSensitivity) { scroller.grabbedLeft = true; scroller.otherHandlePos = zoomedMax; scroller.fixedExtreme = baseXAxis.max; chart.fixedRange = null; // grab the right handle } else if (math.abs(chartX - zoomedMax - navigatorLeft) < handleSensitivity) { scroller.grabbedRight = true; scroller.otherHandlePos = zoomedMin; scroller.fixedExtreme = baseXAxis.min; chart.fixedRange = null; // grab the zoomed range } else if (chartX > navigatorLeft + zoomedMin - scrollbarPad && chartX < navigatorLeft + zoomedMax + scrollbarPad) { scroller.grabbedCenter = chartX; scroller.fixedWidth = range; dragOffset = chartX - zoomedMin; // shift the range by clicking on shaded areas } else if (chartX > scrollerLeft && chartX < scrollerLeft + scrollerWidth) { left = chartX - navigatorLeft - range / 2; if (left < 0) { left = 0; } else if (left + range >= navigatorWidth) { left = navigatorWidth - range; fixedMax = scroller.getUnionExtremes().dataMax; // #2293, #3543 } if (left !== zoomedMin) { // it has actually moved scroller.fixedWidth = range; // #1370 ext = xAxis.toFixedRange(left, left + range, null, fixedMax); baseXAxis.setExtremes( ext.min, ext.max, true, null, // auto animation { trigger: 'navigator' } ); } } } }; /** * Event handler for the mouse move event. */ scroller.mouseMoveHandler = function (e) { var scrollbarHeight = scroller.scrollbarHeight, navigatorLeft = scroller.navigatorLeft, navigatorWidth = scroller.navigatorWidth, scrollerLeft = scroller.scrollerLeft, scrollerWidth = scroller.scrollerWidth, range = scroller.range, chartX; // In iOS, a mousemove event with e.pageX === 0 is fired when holding the finger // down in the center of the scrollbar. This should be ignored. if (!e.touches || e.touches[0].pageX !== 0) { // #4696, scrollbar failed on Android e = chart.pointer.normalize(e); chartX = e.chartX; // validation for handle dragging if (chartX < navigatorLeft) { chartX = navigatorLeft; } else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) { chartX = scrollerLeft + scrollerWidth - scrollbarHeight; } // drag left handle if (scroller.grabbedLeft) { scroller.hasDragged = true; scroller.render(0, 0, chartX - navigatorLeft, scroller.otherHandlePos); // drag right handle } else if (scroller.grabbedRight) { scroller.hasDragged = true; scroller.render(0, 0, scroller.otherHandlePos, chartX - navigatorLeft); // drag scrollbar or open area in navigator } else if (scroller.grabbedCenter) { scroller.hasDragged = true; if (chartX < dragOffset) { // outside left chartX = dragOffset; } else if (chartX > navigatorWidth + dragOffset - range) { // outside right chartX = navigatorWidth + dragOffset - range; } scroller.render(0, 0, chartX - dragOffset, chartX - dragOffset + range); } if (scroller.hasDragged && scroller.scrollbar && scroller.scrollbar.options.liveRedraw) { e.DOMType = e.type; // DOMType is for IE8 because it can't read type async setTimeout(function () { scroller.mouseUpHandler(e); }, 0); } } }; /** * Event handler for the mouse up event. */ scroller.mouseUpHandler = function (e) { var ext, fixedMin, fixedMax, DOMEvent = e.DOMEvent || e; if (scroller.hasDragged || e.trigger === 'scrollbar') { // When dragging one handle, make sure the other one doesn't change if (scroller.zoomedMin === scroller.otherHandlePos) { fixedMin = scroller.fixedExtreme; } else if (scroller.zoomedMax === scroller.otherHandlePos) { fixedMax = scroller.fixedExtreme; } // Snap to right edge (#4076) if (scroller.zoomedMax === scroller.navigatorWidth) { fixedMax = scroller.getUnionExtremes().dataMax; } ext = xAxis.toFixedRange(scroller.zoomedMin, scroller.zoomedMax, fixedMin, fixedMax); if (defined(ext.min)) { chart.xAxis[0].setExtremes( ext.min, ext.max, true, scroller.hasDragged ? false : null, // Run animation when clicking buttons, scrollbar track etc, but not when dragging handles or scrollbar { trigger: 'navigator', triggerOp: 'navigator-drag', DOMEvent: DOMEvent // #1838 } ); } } if (e.DOMType !== 'mousemove') { scroller.grabbedLeft = scroller.grabbedRight = scroller.grabbedCenter = scroller.fixedWidth = scroller.fixedExtreme = scroller.otherHandlePos = scroller.hasDragged = dragOffset = null; } }; var xAxisIndex = chart.xAxis.length, yAxisIndex = chart.yAxis.length; // make room below the chart chart.extraBottomMargin = scroller.outlineHeight + navigatorOptions.margin; if (scroller.navigatorEnabled) { // an x axis is required for scrollbar also scroller.xAxis = xAxis = new Axis(chart, merge({ // inherit base xAxis' break and ordinal options breaks: baseSeries && baseSeries.xAxis.options.breaks, ordinal: baseSeries && baseSeries.xAxis.options.ordinal }, navigatorOptions.xAxis, { id: 'navigator-x-axis', isX: true, type: 'datetime', index: xAxisIndex, height: height, offset: 0, offsetLeft: scrollbarHeight, offsetRight: -scrollbarHeight, keepOrdinalPadding: true, // #2436 startOnTick: false, endOnTick: false, minPadding: 0, maxPadding: 0, zoomEnabled: false })); scroller.yAxis = yAxis = new Axis(chart, merge(navigatorOptions.yAxis, { id: 'navigator-y-axis', alignTicks: false, height: height, offset: 0, index: yAxisIndex, zoomEnabled: false })); // If we have a base series, initialize the navigator series if (baseSeries || navigatorOptions.series.data) { scroller.addBaseSeries(); // If not, set up an event to listen for added series } else if (chart.series.length === 0) { wrap(chart, 'redraw', function (proceed, animation) { // We've got one, now add it as base and reset chart.redraw if (chart.series.length > 0 && !scroller.series) { scroller.setBaseSeries(); chart.redraw = proceed; // reset } proceed.call(chart, animation); }); } // in case of scrollbar only, fake an x axis to get translation } else { scroller.xAxis = xAxis = { translate: function (value, reverse) { var axis = chart.xAxis[0], ext = axis.getExtremes(), scrollTrackWidth = chart.plotWidth - 2 * scrollbarHeight, min = numExt('min', axis.options.min, ext.dataMin), valueRange = numExt('max', axis.options.max, ext.dataMax) - min; return reverse ? // from pixel to value (value * valueRange / scrollTrackWidth) + min : // from value to pixel scrollTrackWidth * (value - min) / valueRange; }, toFixedRange: Axis.prototype.toFixedRange }; } // Initialize the scrollbar if (chart.options.scrollbar.enabled) { scroller.scrollbar = new Scrollbar( chart.renderer, merge(chart.options.scrollbar, { margin: scroller.navigatorEnabled ? 0 : 10 }), chart ); addEvent(scroller.scrollbar, 'changed', function (e) { var range = scroller.navigatorWidth, to = range * this.to, from = range * this.from; scroller.hasDragged = scroller.scrollbar.hasDragged; scroller.render(0, 0, from, to); if (chart.options.scrollbar.liveRedraw || e.DOMType !== 'mousemove') { setTimeout(function () { scroller.mouseUpHandler(e); }); } }); } // Add data events scroller.addBaseSeriesEvents(); /** * For stock charts, extend the Chart.getMargins method so that we can set the final top position * of the navigator once the height of the chart, including the legend, is determined. #367. */ wrap(chart, 'getMargins', function (proceed) { var legend = this.legend, legendOptions = legend.options; proceed.apply(this, [].slice.call(arguments, 1)); // Compute the top position scroller.top = top = scroller.navigatorOptions.top || this.chartHeight - scroller.height - scroller.scrollbarHeight - this.spacing[2] - (legendOptions.verticalAlign === 'bottom' && legendOptions.enabled && !legendOptions.floating ? legend.legendHeight + pick(legendOptions.margin, 10) : 0); if (xAxis && yAxis) { // false if navigator is disabled (#904) xAxis.options.top = yAxis.options.top = top; xAxis.setAxisSize(); yAxis.setAxisSize(); } }); scroller.addEvents(); }, /** * Get the union data extremes of the chart - the outer data extremes of the base * X axis and the navigator axis. */ getUnionExtremes: function (returnFalseOnNoBaseSeries) { var baseAxis = this.chart.xAxis[0], navAxis = this.xAxis, navAxisOptions = navAxis.options, baseAxisOptions = baseAxis.options, ret; if (!returnFalseOnNoBaseSeries || baseAxis.dataMin !== null) { ret = { dataMin: pick( // #4053 navAxisOptions && navAxisOptions.min, numExt( 'min', baseAxisOptions.min, baseAxis.dataMin, navAxis.dataMin, navAxis.min ) ), dataMax: pick( navAxisOptions && navAxisOptions.max, numExt( 'max', baseAxisOptions.max, baseAxis.dataMax, navAxis.dataMax, navAxis.max ) ) }; } return ret; }, /** * Set the base series. With a bit of modification we should be able to make * this an API method to be called from the outside */ setBaseSeries: function (baseSeriesOption) { var chart = this.chart; baseSeriesOption = baseSeriesOption || chart.options.navigator.baseSeries; // If we're resetting, remove the existing series if (this.series) { this.removeBaseSeriesEvents(); this.series.remove(); } // Set the new base series this.baseSeries = chart.series[baseSeriesOption] || (typeof baseSeriesOption === 'string' && chart.get(baseSeriesOption)) || chart.series[0]; // When run after render, this.xAxis already exists if (this.xAxis) { this.addBaseSeries(); } }, addBaseSeries: function () { var baseSeries = this.baseSeries, baseOptions = baseSeries ? baseSeries.options : {}, baseData = baseOptions.data, mergedNavSeriesOptions, navigatorSeriesOptions = this.navigatorOptions.series, navigatorData; // remove it to prevent merging one by one navigatorData = navigatorSeriesOptions.data; this.hasNavigatorData = !!navigatorData; // Merge the series options mergedNavSeriesOptions = merge(baseOptions, navigatorSeriesOptions, { enableMouseTracking: false, group: 'nav', // for columns padXAxis: false, xAxis: 'navigator-x-axis', yAxis: 'navigator-y-axis', name: 'Navigator', showInLegend: false, stacking: false, // We only allow one series anyway (#4823) isInternal: true, visible: true }); // Set the data. Do a slice to avoid mutating the navigator options from base series (#4923). mergedNavSeriesOptions.data = navigatorData || baseData.slice(0); // Add the series this.series = this.chart.initSeries(mergedNavSeriesOptions); this.addBaseSeriesEvents(); }, addBaseSeriesEvents: function () { var baseSeries = this.baseSeries; // Respond to updated data in the base series. // Abort if lazy-loading data from the server. if (baseSeries && baseSeries.xAxis && this.navigatorOptions.adaptToUpdatedData !== false) { addEvent(baseSeries, 'updatedData', this.updatedDataHandler); addEvent(baseSeries.xAxis, 'foundExtremes', this.modifyBaseAxisExtremes); // Survive Series.update() baseSeries.userOptions.events = extend(baseSeries.userOptions.event, { updatedData: this.updatedDataHandler }); } }, /** * Set the scroller x axis extremes to reflect the total. The navigator extremes * should always be the extremes of the union of all series in the chart as * well as the navigator series. */ modifyNavigatorAxisExtremes: function () { var xAxis = this.xAxis, unionExtremes; if (xAxis.getExtremes) { unionExtremes = this.getUnionExtremes(true); if (unionExtremes && (unionExtremes.dataMin !== xAxis.min || unionExtremes.dataMax !== xAxis.max)) { xAxis.min = unionExtremes.dataMin; xAxis.max = unionExtremes.dataMax; } } }, /** * Hook to modify the base axis extremes with information from the Navigator */ modifyBaseAxisExtremes: function () { if (!this.chart.scroller.baseSeries || !this.chart.scroller.baseSeries.xAxis) { return; } var baseXAxis = this, scroller = baseXAxis.chart.scroller, baseExtremes = baseXAxis.getExtremes(), baseMin = baseExtremes.min, baseMax = baseExtremes.max, baseDataMin = baseExtremes.dataMin, baseDataMax = baseExtremes.dataMax, range = baseMax - baseMin, stickToMin = scroller.stickToMin, stickToMax = scroller.stickToMax, newMax, newMin, navigatorSeries = scroller.series, hasSetExtremes = !!baseXAxis.setExtremes, // When the extremes have been set by range selector button, don't stick to min or max. // The range selector buttons will handle the extremes. (#5489) unmutable = baseXAxis.eventArgs && baseXAxis.eventArgs.trigger === 'rangeSelectorButton'; if (!unmutable) { // If the zoomed range is already at the min, move it to the right as new data // comes in if (stickToMin) { newMin = baseDataMin; newMax = newMin + range; } // If the zoomed range is already at the max, move it to the right as new data // comes in if (stickToMax) { newMax = baseDataMax; if (!stickToMin) { // if stickToMin is true, the new min value is set above newMin = mathMax(newMax - range, navigatorSeries && navigatorSeries.xData ? navigatorSeries.xData[0] : -Number.MAX_VALUE); } } // Update the extremes if (hasSetExtremes && (stickToMin || stickToMax)) { if (isNumber(newMin)) { baseXAxis.min = baseXAxis.userMin = newMin; baseXAxis.max = baseXAxis.userMax = newMax; } } } // Reset scroller.stickToMin = scroller.stickToMax = null; }, /** * Handler for updated data on the base series. When data is modified, the navigator series * must reflect it. This is called from the Chart.redraw function before axis and series * extremes are computed. */ updatedDataHandler: function () { var scroller = this.chart.scroller, baseSeries = scroller.baseSeries, navigatorSeries = scroller.series; // Detect whether the zoomed area should stick to the minimum or maximum. If the current // axis minimum falls outside the new updated dataset, we must adjust. scroller.stickToMin = isNumber(baseSeries.xAxis.min) && (baseSeries.xAxis.min <= baseSeries.xData[0]); // If the scrollbar is scrolled all the way to the right, keep right as new data // comes in. scroller.stickToMax = Math.round(scroller.zoomedMax) >= Math.round(scroller.navigatorWidth); // Set the navigator series data to the new data of the base series if (navigatorSeries && !scroller.hasNavigatorData) { navigatorSeries.options.pointStart = baseSeries.xData[0]; navigatorSeries.setData(baseSeries.options.data, false, null, false); // #5414 } }, /** * Destroys allocated elements. */ destroy: function () { var scroller = this; // Disconnect events added in addEvents scroller.removeEvents(); // Destroy properties each([scroller.scrollbar, scroller.xAxis, scroller.yAxis, scroller.leftShade, scroller.rightShade, scroller.outline], function (prop) { if (prop && prop.destroy) { prop.destroy(); } }); scroller.xAxis = scroller.yAxis = scroller.leftShade = scroller.rightShade = scroller.outline = null; // Destroy elements in collection each([scroller.handles, scroller.elementsToDestroy], function (coll) { destroyObjectProperties(coll); }); } }; Highcharts.Navigator = Navigator; /** * For Stock charts, override selection zooming with some special features because * X axis zooming is already allowed by the Navigator and Range selector. */ wrap(Axis.prototype, 'zoom', function (proceed, newMin, newMax) { var chart = this.chart, chartOptions = chart.options, zoomType = chartOptions.chart.zoomType, previousZoom, navigator = chartOptions.navigator, rangeSelector = chartOptions.rangeSelector, ret; if (this.isXAxis && ((navigator && navigator.enabled) || (rangeSelector && rangeSelector.enabled))) { // For x only zooming, fool the chart.zoom method not to create the zoom button // because the property already exists if (zoomType === 'x') { chart.resetZoomButton = 'blocked'; // For y only zooming, ignore the X axis completely } else if (zoomType === 'y') { ret = false; // For xy zooming, record the state of the zoom before zoom selection, then when // the reset button is pressed, revert to this state } else if (zoomType === 'xy') { previousZoom = this.previousZoom; if (defined(newMin)) { this.previousZoom = [this.min, this.max]; } else if (previousZoom) { newMin = previousZoom[0]; newMax = previousZoom[1]; delete this.previousZoom; } } } return ret !== UNDEFINED ? ret : proceed.call(this, newMin, newMax); }); // Initialize scroller for stock charts wrap(Chart.prototype, 'init', function (proceed, options, callback) { addEvent(this, 'beforeRender', function () { var options = this.options; if (options.navigator.enabled || options.scrollbar.enabled) { this.scroller = new Navigator(this); } }); proceed.call(this, options, callback); }); // Pick up badly formatted point options to addPoint wrap(Series.prototype, 'addPoint', function (proceed, options, redraw, shift, animation) { var turboThreshold = this.options.turboThreshold; if (turboThreshold && this.xData.length > turboThreshold && isObject(options, true) && this.chart.scroller) { error(20, true); } proceed.call(this, options, redraw, shift, animation); }); /* **************************************************************************** * End Navigator code * *****************************************************************************/ /* **************************************************************************** * Start Range Selector code * *****************************************************************************/ extend(defaultOptions, { rangeSelector: { // allButtonsEnabled: false, // enabled: true, // buttons: {Object} // buttonSpacing: 0, buttonTheme: { width: 28, height: 18, fill: '#f7f7f7', padding: 2, r: 0, 'stroke-width': 0, style: { color: '#444', cursor: 'pointer', fontWeight: 'normal' }, zIndex: 7, // #484, #852 states: { hover: { fill: '#e7e7e7' }, select: { fill: '#e7f0f9', style: { color: 'black', fontWeight: 'bold' } } } }, height: 35, // reserved space for buttons and input inputPosition: { align: 'right' }, // inputDateFormat: '%b %e, %Y', // inputEditDateFormat: '%Y-%m-%d', // inputEnabled: true, // inputStyle: {}, labelStyle: { color: '#666' } // selected: undefined } }); defaultOptions.lang = merge(defaultOptions.lang, { rangeSelectorZoom: 'Zoom', rangeSelectorFrom: 'From', rangeSelectorTo: 'To' }); /** * The object constructor for the range selector * @param {Object} chart */ function RangeSelector(chart) { // Run RangeSelector this.init(chart); } RangeSelector.prototype = { /** * The method to run when one of the buttons in the range selectors is clicked * @param {Number} i The index of the button * @param {Object} rangeOptions * @param {Boolean} redraw */ clickButton: function (i, redraw) { var rangeSelector = this, selected = rangeSelector.selected, chart = rangeSelector.chart, buttons = rangeSelector.buttons, rangeOptions = rangeSelector.buttonOptions[i], baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis || {}, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, newMin, newMax = baseAxis && mathRound(mathMin(baseAxis.max, pick(dataMax, baseAxis.max))), // #1568 now, type = rangeOptions.type, baseXAxisOptions, range = rangeOptions._range, rangeMin, year, minSetting, rangeSetting, ctx, dataGrouping = rangeOptions.dataGrouping; if (dataMin === null || dataMax === null || // chart has no data, base series is removed i === rangeSelector.selected) { // same button is clicked twice return; } // Set the fixed range before range is altered chart.fixedRange = range; // Apply dataGrouping associated to button if (dataGrouping) { this.forcedDataGrouping = true; Axis.prototype.setDataGrouping.call(baseAxis || { chart: this.chart }, dataGrouping, false); } // Apply range if (type === 'month' || type === 'year') { if (!baseAxis) { // This is set to the user options and picked up later when the axis is instantiated // so that we know the min and max. range = rangeOptions; } else { ctx = { range: rangeOptions, max: newMax, dataMin: dataMin, dataMax: dataMax }; newMin = baseAxis.minFromRange.call(ctx); if (isNumber(ctx.newMax)) { newMax = ctx.newMax; } } // Fixed times like minutes, hours, days } else if (range) { newMin = mathMax(newMax - range, dataMin); newMax = mathMin(newMin + range, dataMax); } else if (type === 'ytd') { // On user clicks on the buttons, or a delayed action running from the beforeRender // event (below), the baseAxis is defined. if (baseAxis) { // When "ytd" is the pre-selected button for the initial view, its calculation // is delayed and rerun in the beforeRender event (below). When the series // are initialized, but before the chart is rendered, we have access to the xData // array (#942). if (dataMax === UNDEFINED) { dataMin = Number.MAX_VALUE; dataMax = Number.MIN_VALUE; each(chart.series, function (series) { var xData = series.xData; // reassign it to the last item dataMin = mathMin(xData[0], dataMin); dataMax = mathMax(xData[xData.length - 1], dataMax); }); redraw = false; } now = new Date(dataMax); year = now.getFullYear(); newMin = rangeMin = mathMax(dataMin || 0, Date.UTC(year, 0, 1)); now = now.getTime(); newMax = mathMin(dataMax || now, now); // "ytd" is pre-selected. We don't yet have access to processed point and extremes data // (things like pointStart and pointInterval are missing), so we delay the process (#942) } else { addEvent(chart, 'beforeRender', function () { rangeSelector.clickButton(i); }); return; } } else if (type === 'all' && baseAxis) { newMin = dataMin; newMax = dataMax; } // Deselect previous button if (buttons[selected]) { buttons[selected].setState(0); } // Select this button if (buttons[i]) { buttons[i].setState(2); rangeSelector.lastSelected = i; } // Update the chart if (!baseAxis) { // Axis not yet instanciated. Temporarily set min and range // options and remove them on chart load (#4317). baseXAxisOptions = splat(chart.options.xAxis)[0]; rangeSetting = baseXAxisOptions.range; baseXAxisOptions.range = range; minSetting = baseXAxisOptions.min; baseXAxisOptions.min = rangeMin; rangeSelector.setSelected(i); addEvent(chart, 'load', function resetMinAndRange() { baseXAxisOptions.range = rangeSetting; baseXAxisOptions.min = minSetting; }); } else { // Existing axis object. Set extremes after render time. baseAxis.setExtremes( newMin, newMax, pick(redraw, 1), null, // auto animation { trigger: 'rangeSelectorButton', rangeSelectorButton: rangeOptions } ); rangeSelector.setSelected(i); } }, /** * Set the selected option. This method only sets the internal flag, it doesn't * update the buttons or the actual zoomed range. */ setSelected: function (selected) { this.selected = this.options.selected = selected; }, /** * The default buttons for pre-selecting time frames */ defaultButtons: [{ type: 'month', count: 1, text: '1m' }, { type: 'month', count: 3, text: '3m' }, { type: 'month', count: 6, text: '6m' }, { type: 'ytd', text: 'YTD' }, { type: 'year', count: 1, text: '1y' }, { type: 'all', text: 'All' }], /** * Initialize the range selector */ init: function (chart) { var rangeSelector = this, options = chart.options.rangeSelector, buttonOptions = options.buttons || [].concat(rangeSelector.defaultButtons), selectedOption = options.selected, blurInputs = rangeSelector.blurInputs = function () { var minInput = rangeSelector.minInput, maxInput = rangeSelector.maxInput; if (minInput && minInput.blur) { //#3274 in some case blur is not defined fireEvent(minInput, 'blur'); //#3274 } if (maxInput && maxInput.blur) { //#3274 in some case blur is not defined fireEvent(maxInput, 'blur'); //#3274 } }; rangeSelector.chart = chart; rangeSelector.options = options; rangeSelector.buttons = []; chart.extraTopMargin = options.height; rangeSelector.buttonOptions = buttonOptions; addEvent(chart.container, 'mousedown', blurInputs); addEvent(chart, 'resize', blurInputs); // Extend the buttonOptions with actual range each(buttonOptions, rangeSelector.computeButtonRange); // zoomed range based on a pre-selected button index if (selectedOption !== UNDEFINED && buttonOptions[selectedOption]) { this.clickButton(selectedOption, false); } addEvent(chart, 'load', function () { // If a data grouping is applied to the current button, release it when extremes change addEvent(chart.xAxis[0], 'setExtremes', function (e) { if (this.max - this.min !== chart.fixedRange && e.trigger !== 'rangeSelectorButton' && e.trigger !== 'updatedData' && rangeSelector.forcedDataGrouping) { this.setDataGrouping(false, false); } }); // Normalize the pressed button whenever a new range is selected addEvent(chart.xAxis[0], 'afterSetExtremes', function () { rangeSelector.updateButtonStates(true); }); }); }, /** * Dynamically update the range selector buttons after a new range has been set */ updateButtonStates: function (updating) { var rangeSelector = this, chart = this.chart, baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, selected = rangeSelector.selected, allButtonsEnabled = rangeSelector.options.allButtonsEnabled, buttons = rangeSelector.buttons; if (updating && chart.fixedRange !== mathRound(baseAxis.max - baseAxis.min)) { if (buttons[selected]) { buttons[selected].setState(0); } rangeSelector.setSelected(null); } each(rangeSelector.buttonOptions, function (rangeOptions, i) { var actualRange = mathRound(baseAxis.max - baseAxis.min), range = rangeOptions._range, type = rangeOptions.type, count = rangeOptions.count || 1, // Disable buttons where the range exceeds what is allowed in the current view isTooGreatRange = range > dataMax - dataMin, // Disable buttons where the range is smaller than the minimum range isTooSmallRange = range < baseAxis.minRange, // Disable the All button if we're already showing all isAllButAlreadyShowingAll = rangeOptions.type === 'all' && baseAxis.max - baseAxis.min >= dataMax - dataMin && buttons[i].state !== 2, // Set a button on export isSelectedForExport = chart.renderer.forExport && i === selected, isSameRange = range === actualRange, hasNoData = !baseAxis.hasVisibleSeries; // Months and years have a variable range so we check the extremes if ((type === 'month' || type === 'year') && (actualRange >= { month: 28, year: 365 }[type] * 24 * 36e5 * count) && (actualRange <= { month: 31, year: 366 }[type] * 24 * 36e5 * count)) { isSameRange = true; } // The new zoom area happens to match the range for a button - mark it selected. // This happens when scrolling across an ordinal gap. It can be seen in the intraday // demos when selecting 1h and scroll across the night gap. if (isSelectedForExport || (isSameRange && i !== selected) && i === rangeSelector.lastSelected) { rangeSelector.setSelected(i); buttons[i].setState(2); } else if (!allButtonsEnabled && (isTooGreatRange || isTooSmallRange || isAllButAlreadyShowingAll || hasNoData)) { buttons[i].setState(3); } else if (buttons[i].state === 3) { buttons[i].setState(0); } }); }, /** * Compute and cache the range for an individual button */ computeButtonRange: function (rangeOptions) { var type = rangeOptions.type, count = rangeOptions.count || 1, // these time intervals have a fixed number of milliseconds, as opposed // to month, ytd and year fixedTimes = { millisecond: 1, second: 1000, minute: 60 * 1000, hour: 3600 * 1000, day: 24 * 3600 * 1000, week: 7 * 24 * 3600 * 1000 }; // Store the range on the button object if (fixedTimes[type]) { rangeOptions._range = fixedTimes[type] * count; } else if (type === 'month' || type === 'year') { rangeOptions._range = { month: 30, year: 365 }[type] * 24 * 36e5 * count; } }, /** * Set the internal and displayed value of a HTML input for the dates * @param {String} name * @param {Number} time */ setInputValue: function (name, time) { var options = this.chart.options.rangeSelector; if (defined(time)) { this[name + 'Input'].HCTime = time; } this[name + 'Input'].value = dateFormat( options.inputEditDateFormat || '%Y-%m-%d', this[name + 'Input'].HCTime ); this[name + 'DateBox'].attr({ text: dateFormat(options.inputDateFormat || '%b %e, %Y', this[name + 'Input'].HCTime) }); }, showInput: function (name) { var inputGroup = this.inputGroup, dateBox = this[name + 'DateBox']; css(this[name + 'Input'], { left: (inputGroup.translateX + dateBox.x) + PX, top: inputGroup.translateY + PX, width: (dateBox.width - 2) + PX, height: (dateBox.height - 2) + PX, border: '2px solid silver' }); }, hideInput: function (name) { css(this[name + 'Input'], { border: 0, width: '1px', height: '1px' }); this.setInputValue(name); }, /** * Draw either the 'from' or the 'to' HTML input box of the range selector * @param {Object} name */ drawInput: function (name) { var rangeSelector = this, chart = rangeSelector.chart, chartStyle = chart.renderer.style, renderer = chart.renderer, options = chart.options.rangeSelector, lang = defaultOptions.lang, div = rangeSelector.div, isMin = name === 'min', input, label, dateBox, inputGroup = this.inputGroup; function updateExtremes() { var inputValue = input.value, value = (options.inputDateParser || Date.parse)(inputValue), xAxis = chart.scroller && chart.scroller.xAxis ? chart.scroller.xAxis : chart.xAxis[0], dataMin = xAxis.dataMin, dataMax = xAxis.dataMax; if (value !== input.previousValue) { input.previousValue = value; // If the value isn't parsed directly to a value by the browser's Date.parse method, // like YYYY-MM-DD in IE, try parsing it a different way if (!isNumber(value)) { value = inputValue.split('-'); value = Date.UTC(pInt(value[0]), pInt(value[1]) - 1, pInt(value[2])); } if (isNumber(value)) { // Correct for timezone offset (#433) if (!defaultOptions.global.useUTC) { value = value + new Date().getTimezoneOffset() * 60 * 1000; } // Validate the extremes. If it goes beyound the data min or max, use the // actual data extreme (#2438). if (isMin) { if (value > rangeSelector.maxInput.HCTime) { value = UNDEFINED; } else if (value < dataMin) { value = dataMin; } } else { if (value < rangeSelector.minInput.HCTime) { value = UNDEFINED; } else if (value > dataMax) { value = dataMax; } } // Set the extremes if (value !== UNDEFINED) { chart.xAxis[0].setExtremes( isMin ? value : xAxis.min, isMin ? xAxis.max : value, UNDEFINED, UNDEFINED, { trigger: 'rangeSelectorInput' } ); } } } } // Create the text label this[name + 'Label'] = label = renderer.label(lang[isMin ? 'rangeSelectorFrom' : 'rangeSelectorTo'], this.inputGroup.offset) .attr({ padding: 2 }) .css(merge(chartStyle, options.labelStyle)) .add(inputGroup); inputGroup.offset += label.width + 5; // Create an SVG label that shows updated date ranges and and records click events that // bring in the HTML input. this[name + 'DateBox'] = dateBox = renderer.label('', inputGroup.offset) .attr({ padding: 2, width: options.inputBoxWidth || 90, height: options.inputBoxHeight || 17, stroke: options.inputBoxBorderColor || 'silver', 'stroke-width': 1 }) .css(merge({ textAlign: 'center', color: '#444' }, chartStyle, options.inputStyle)) .on('click', function () { rangeSelector.showInput(name); // If it is already focused, the onfocus event doesn't fire (#3713) rangeSelector[name + 'Input'].focus(); }) .add(inputGroup); inputGroup.offset += dateBox.width + (isMin ? 10 : 0); // Create the HTML input element. This is rendered as 1x1 pixel then set to the right size // when focused. this[name + 'Input'] = input = createElement('input', { name: name, className: PREFIX + 'range-selector', type: 'text' }, extend({ position: ABSOLUTE, border: 0, width: '1px', // Chrome needs a pixel to see it height: '1px', padding: 0, textAlign: 'center', fontSize: chartStyle.fontSize, fontFamily: chartStyle.fontFamily, left: '-9em', // #4798 top: chart.plotTop + PX // prevent jump on focus in Firefox }, options.inputStyle), div); // Blow up the input box input.onfocus = function () { rangeSelector.showInput(name); }; // Hide away the input box input.onblur = function () { rangeSelector.hideInput(name); }; // handle changes in the input boxes input.onchange = updateExtremes; input.onkeypress = function (event) { // IE does not fire onchange on enter if (event.keyCode === 13) { updateExtremes(); } }; }, /** * Get the position of the range selector buttons and inputs. This can be overridden from outside for custom positioning. */ getPosition: function () { var chart = this.chart, options = chart.options.rangeSelector, buttonTop = pick((options.buttonPosition || {}).y, chart.plotTop - chart.axisOffset[0] - options.height); return { buttonTop: buttonTop, inputTop: buttonTop - 10 }; }, /** * Render the range selector including the buttons and the inputs. The first time render * is called, the elements are created and positioned. On subsequent calls, they are * moved and updated. * @param {Number} min X axis minimum * @param {Number} max X axis maximum */ render: function (min, max) { var rangeSelector = this, chart = rangeSelector.chart, renderer = chart.renderer, container = chart.container, chartOptions = chart.options, navButtonOptions = chartOptions.exporting && chartOptions.exporting.enabled !== false && chartOptions.navigation && chartOptions.navigation.buttonOptions, options = chartOptions.rangeSelector, buttons = rangeSelector.buttons, lang = defaultOptions.lang, div = rangeSelector.div, inputGroup = rangeSelector.inputGroup, buttonTheme = options.buttonTheme, buttonPosition = options.buttonPosition || {}, inputEnabled = options.inputEnabled, states = buttonTheme && buttonTheme.states, plotLeft = chart.plotLeft, buttonLeft, pos = this.getPosition(), buttonGroup = rangeSelector.group, buttonBBox, rendered = rangeSelector.rendered; // create the elements if (!rendered) { rangeSelector.group = buttonGroup = renderer.g('range-selector-buttons').add(); rangeSelector.zoomText = renderer.text(lang.rangeSelectorZoom, pick(buttonPosition.x, plotLeft), 15) .css(options.labelStyle) .add(buttonGroup); // button starting position buttonLeft = pick(buttonPosition.x, plotLeft) + rangeSelector.zoomText.getBBox().width + 5; each(rangeSelector.buttonOptions, function (rangeOptions, i) { buttons[i] = renderer.button( rangeOptions.text, buttonLeft, 0, function () { rangeSelector.clickButton(i); rangeSelector.isActive = true; }, buttonTheme, states && states.hover, states && states.select, states && states.disabled ) .css({ textAlign: 'center' }) .add(buttonGroup); // increase button position for the next button buttonLeft += buttons[i].width + pick(options.buttonSpacing, 5); if (rangeSelector.selected === i) { buttons[i].setState(2); } }); rangeSelector.updateButtonStates(); // first create a wrapper outside the container in order to make // the inputs work and make export correct if (inputEnabled !== false) { rangeSelector.div = div = createElement('div', null, { position: 'relative', height: 0, zIndex: 1 // above container }); container.parentNode.insertBefore(div, container); // Create the group to keep the inputs rangeSelector.inputGroup = inputGroup = renderer.g('input-group') .add(); inputGroup.offset = 0; rangeSelector.drawInput('min'); rangeSelector.drawInput('max'); } } // Set or update the group position buttonGroup[rendered ? 'animate' : 'attr']({ translateY: pos.buttonTop }); if (inputEnabled !== false) { // Update the alignment to the updated spacing box inputGroup.align(extend({ y: pos.inputTop, width: inputGroup.offset, // Detect collision with the exporting buttons x: navButtonOptions && (pos.inputTop < (navButtonOptions.y || 0) + navButtonOptions.height - chart.spacing[0]) ? -40 : 0 }, options.inputPosition), true, chart.spacingBox); // Hide if overlapping - inputEnabled is null or undefined if (!defined(inputEnabled)) { buttonBBox = buttonGroup.getBBox(); inputGroup[inputGroup.translateX < buttonBBox.x + buttonBBox.width + 10 ? 'hide' : 'show'](); } // Set or reset the input values rangeSelector.setInputValue('min', min); rangeSelector.setInputValue('max', max); } rangeSelector.rendered = true; }, /** * Destroys allocated elements. */ destroy: function () { var minInput = this.minInput, maxInput = this.maxInput, chart = this.chart, blurInputs = this.blurInputs, key; removeEvent(chart.container, 'mousedown', blurInputs); removeEvent(chart, 'resize', blurInputs); // Destroy elements in collections destroyObjectProperties(this.buttons); // Clear input element events if (minInput) { minInput.onfocus = minInput.onblur = minInput.onchange = null; } if (maxInput) { maxInput.onfocus = maxInput.onblur = maxInput.onchange = null; } // Destroy HTML and SVG elements for (key in this) { if (this[key] && key !== 'chart') { if (this[key].destroy) { // SVGElement this[key].destroy(); } else if (this[key].nodeType) { // HTML element discardElement(this[key]); } } this[key] = null; } } }; /** * Add logic to normalize the zoomed range in order to preserve the pressed state of range selector buttons */ Axis.prototype.toFixedRange = function (pxMin, pxMax, fixedMin, fixedMax) { var fixedRange = this.chart && this.chart.fixedRange, newMin = pick(fixedMin, this.translate(pxMin, true)), newMax = pick(fixedMax, this.translate(pxMax, true)), changeRatio = fixedRange && (newMax - newMin) / fixedRange; // If the difference between the fixed range and the actual requested range is // too great, the user is dragging across an ordinal gap, and we need to release // the range selector button. if (changeRatio > 0.7 && changeRatio < 1.3) { if (fixedMax) { newMin = newMax - fixedRange; } else { newMax = newMin + fixedRange; } } if (!isNumber(newMin)) { // #1195 newMin = newMax = undefined; } return { min: newMin, max: newMax }; }; Axis.prototype.minFromRange = function () { var rangeOptions = this.range, type = rangeOptions.type, timeName = { month: 'Month', year: 'FullYear' }[type], min, max = this.max, dataMin, range, // Get the true range from a start date getTrueRange = function (base, count) { var date = new Date(base); date['set' + timeName](date['get' + timeName]() + count); return date.getTime() - base; }; if (isNumber(rangeOptions)) { min = this.max - rangeOptions; range = rangeOptions; } else { min = max + getTrueRange(max, -rangeOptions.count); } dataMin = pick(this.dataMin, Number.MIN_VALUE); if (!isNumber(min)) { min = dataMin; } if (min <= dataMin) { min = dataMin; if (range === undefined) { // #4501 range = getTrueRange(min, rangeOptions.count); } this.newMax = mathMin(min + range, this.dataMax); } if (!isNumber(max)) { min = undefined; } return min; }; // Initialize scroller for stock charts wrap(Chart.prototype, 'init', function (proceed, options, callback) { addEvent(this, 'init', function () { if (this.options.rangeSelector.enabled) { this.rangeSelector = new RangeSelector(this); } }); proceed.call(this, options, callback); }); Highcharts.RangeSelector = RangeSelector; /* **************************************************************************** * End Range Selector code * *****************************************************************************/ Chart.prototype.callbacks.push(function (chart) { var extremes, scroller = chart.scroller, rangeSelector = chart.rangeSelector; function renderRangeSelector() { extremes = chart.xAxis[0].getExtremes(); if (isNumber(extremes.min)) { rangeSelector.render(extremes.min, extremes.max); } } function afterSetExtremesHandlerRangeSelector(e) { rangeSelector.render(e.min, e.max); } function destroyEvents() { if (rangeSelector) { removeEvent(chart, 'resize', renderRangeSelector); removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector); } } // initiate the scroller if (scroller) { extremes = chart.xAxis[0].getExtremes(); scroller.render(extremes.min, extremes.max); } if (rangeSelector) { // redraw the scroller on setExtremes addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector); // redraw the scroller chart resize addEvent(chart, 'resize', renderRangeSelector); // do it now renderRangeSelector(); } // Remove resize/afterSetExtremes at chart destroy addEvent(chart, 'destroy', destroyEvents); }); /** * A wrapper for Chart with all the default values for a Stock chart */ Highcharts.StockChart = Highcharts.stockChart = function (a, b, c) { var hasRenderToArg = isString(a) || a.nodeName, options = arguments[hasRenderToArg ? 1 : 0], seriesOptions = options.series, // to increase performance, don't merge the data opposite, // Always disable startOnTick:true on the main axis when the navigator is enabled (#1090) navigatorEnabled = pick(options.navigator && options.navigator.enabled, true), disableStartOnTick = navigatorEnabled ? { startOnTick: false, endOnTick: false } : null, lineOptions = { marker: { enabled: false, radius: 2 } // gapSize: 0 }, columnOptions = { shadow: false, borderWidth: 0 }; // apply X axis options to both single and multi y axes options.xAxis = map(splat(options.xAxis || {}), function (xAxisOptions) { return merge( { // defaults minPadding: 0, maxPadding: 0, ordinal: true, title: { text: null }, labels: { overflow: 'justify' }, showLastLabel: true }, xAxisOptions, // user options { // forced options type: 'datetime', categories: null }, disableStartOnTick ); }); // apply Y axis options to both single and multi y axes options.yAxis = map(splat(options.yAxis || {}), function (yAxisOptions) { opposite = pick(yAxisOptions.opposite, true); return merge({ // defaults labels: { y: -2 }, opposite: opposite, showLastLabel: false, title: { text: null } }, yAxisOptions // user options ); }); options.series = null; options = merge( { chart: { panning: true, pinchType: 'x' }, navigator: { enabled: true }, scrollbar: { enabled: true }, rangeSelector: { enabled: true }, title: { text: null, style: { fontSize: '16px' } }, tooltip: { shared: true, crosshairs: true }, legend: { enabled: false }, plotOptions: { line: lineOptions, spline: lineOptions, area: lineOptions, areaspline: lineOptions, arearange: lineOptions, areasplinerange: lineOptions, column: columnOptions, columnrange: columnOptions, candlestick: columnOptions, ohlc: columnOptions } }, options, // user's options { // forced options _stock: true, // internal flag chart: { inverted: false } } ); options.series = seriesOptions; return hasRenderToArg ? new Chart(a, options, c) : new Chart(options, b); }; // Implement the pinchType option wrap(Pointer.prototype, 'init', function (proceed, chart, options) { var pinchType = options.chart.pinchType || ''; proceed.call(this, chart, options); // Pinch status this.pinchX = this.pinchHor = pinchType.indexOf('x') !== -1; this.pinchY = this.pinchVert = pinchType.indexOf('y') !== -1; this.hasZoom = this.hasZoom || this.pinchHor || this.pinchVert; }); // Override the automatic label alignment so that the first Y axis' labels // are drawn on top of the grid line, and subsequent axes are drawn outside wrap(Axis.prototype, 'autoLabelAlign', function (proceed) { var chart = this.chart, options = this.options, panes = chart._labelPanes = chart._labelPanes || {}, key, labelOptions = this.options.labels; if (this.chart.options._stock && this.coll === 'yAxis') { key = options.top + ',' + options.height; if (!panes[key] && labelOptions.enabled) { // do it only for the first Y axis of each pane if (labelOptions.x === 15) { // default labelOptions.x = 0; } if (labelOptions.align === undefined) { labelOptions.align = 'right'; } panes[key] = 1; return 'right'; } } return proceed.call(this, [].slice.call(arguments, 1)); }); // Override getPlotLinePath to allow for multipane charts wrap(Axis.prototype, 'getPlotLinePath', function (proceed, value, lineWidth, old, force, translatedValue) { var axis = this, series = (this.isLinked && !this.series ? this.linkedParent.series : this.series), chart = axis.chart, renderer = chart.renderer, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, result = [], axes = [], //#3416 need a default array axes2, uniqueAxes, transVal; // Ignore in case of color Axis. #3360, #3524 if (axis.coll === 'colorAxis') { return proceed.apply(this, [].slice.call(arguments, 1)); } // Get the related axes based on series axes = (axis.isXAxis ? (defined(axis.options.yAxis) ? [chart.yAxis[axis.options.yAxis]] : map(series, function (s) { return s.yAxis; }) ) : (defined(axis.options.xAxis) ? [chart.xAxis[axis.options.xAxis]] : map(series, function (s) { return s.xAxis; }) ) ); // Get the related axes based options.*Axis setting #2810 axes2 = (axis.isXAxis ? chart.yAxis : chart.xAxis); each(axes2, function (A) { if (defined(A.options.id) ? A.options.id.indexOf('navigator') === -1 : true) { var a = (A.isXAxis ? 'yAxis' : 'xAxis'), rax = (defined(A.options[a]) ? chart[a][A.options[a]] : chart[a][0]); if (axis === rax) { axes.push(A); } } }); // Remove duplicates in the axes array. If there are no axes in the axes array, // we are adding an axis without data, so we need to populate this with grid // lines (#2796). uniqueAxes = axes.length ? [] : [axis.isXAxis ? chart.yAxis[0] : chart.xAxis[0]]; //#3742 each(axes, function (axis2) { if (inArray(axis2, uniqueAxes) === -1) { uniqueAxes.push(axis2); } }); transVal = pick(translatedValue, axis.translate(value, null, null, old)); if (isNumber(transVal)) { if (axis.horiz) { each(uniqueAxes, function (axis2) { var skip; y1 = axis2.pos; y2 = y1 + axis2.len; x1 = x2 = mathRound(transVal + axis.transB); if (x1 < axisLeft || x1 > axisLeft + axis.width) { // outside plot area if (force) { x1 = x2 = mathMin(mathMax(axisLeft, x1), axisLeft + axis.width); } else { skip = true; } } if (!skip) { result.push('M', x1, y1, 'L', x2, y2); } }); } else { each(uniqueAxes, function (axis2) { var skip; x1 = axis2.pos; x2 = x1 + axis2.len; y1 = y2 = mathRound(axisTop + axis.height - transVal); if (y1 < axisTop || y1 > axisTop + axis.height) { // outside plot area if (force) { y1 = y2 = mathMin(mathMax(axisTop, y1), axis.top + axis.height); } else { skip = true; } } if (!skip) { result.push('M', x1, y1, 'L', x2, y2); } }); } } return result.length > 0 ? renderer.crispPolyLine(result, lineWidth || 1) : null; //#3557 getPlotLinePath in regular Highcharts also returns null }); // Override getPlotBandPath to allow for multipane charts Axis.prototype.getPlotBandPath = function (from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true), result = [], i; if (path && toPath && path.toString() !== toPath.toString()) { // Go over each subpath for (i = 0; i < path.length; i += 6) { result.push('M', path[i + 1], path[i + 2], 'L', path[i + 4], path[i + 5], toPath[i + 4], toPath[i + 5], toPath[i + 1], toPath[i + 2]); } } else { // outside the axis area result = null; } return result; }; // Function to crisp a line with multiple segments SVGRenderer.prototype.crispPolyLine = function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line var i; for (i = 0; i < points.length; i = i + 6) { if (points[i + 1] === points[i + 4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[i + 1] = points[i + 4] = mathRound(points[i + 1]) - (width % 2 / 2); } if (points[i + 2] === points[i + 5]) { points[i + 2] = points[i + 5] = mathRound(points[i + 2]) + (width % 2 / 2); } } return points; }; if (Renderer === Highcharts.VMLRenderer) { VMLRenderer.prototype.crispPolyLine = SVGRenderer.prototype.crispPolyLine; } // Wrapper to hide the label wrap(Axis.prototype, 'hideCrosshair', function (proceed, i) { proceed.call(this, i); if (this.crossLabel) { this.crossLabel = this.crossLabel.hide(); } }); // Wrapper to draw the label wrap(Axis.prototype, 'drawCrosshair', function (proceed, e, point) { // Draw the crosshair proceed.call(this, e, point); // Check if the label has to be drawn if (!defined(this.crosshair.label) || !this.crosshair.label.enabled || !this.cross) { return; } var chart = this.chart, options = this.options.crosshair.label, // the label's options horiz = this.horiz, // axis orientation opposite = this.opposite, // axis position left = this.left, // left position top = this.top, // top position crossLabel = this.crossLabel, // reference to the svgElement posx, posy, crossBox, formatOption = options.format, formatFormat = '', limit, align, tickInside = this.options.tickPosition === 'inside', snap = this.crosshair.snap !== false, value, offset = 0; // Use last available event (#5287) if (!e) { e = this.cross && this.cross.e; } align = (horiz ? 'center' : opposite ? (this.labelAlign === 'right' ? 'right' : 'left') : (this.labelAlign === 'left' ? 'left' : 'center')); // If the label does not exist yet, create it. if (!crossLabel) { crossLabel = this.crossLabel = chart.renderer.label(null, null, null, options.shape || 'callout') .attr({ align: options.align || align, zIndex: 12, fill: options.backgroundColor || (this.series[0] && this.series[0].color) || 'gray', padding: pick(options.padding, 8), stroke: options.borderColor || '', 'stroke-width': options.borderWidth || 0, r: pick(options.borderRadius, 3) }) .css(extend({ color: 'white', fontWeight: 'normal', fontSize: '11px', textAlign: 'center' }, options.style)) .add(); } if (horiz) { posx = snap ? point.plotX + left : e.chartX; posy = top + (opposite ? 0 : this.height); } else { posx = opposite ? this.width + left : 0; posy = snap ? point.plotY + top : e.chartY; } if (!formatOption && !options.formatter) { if (this.isDatetimeAxis) { formatFormat = '%b %d, %Y'; } formatOption = '{value' + (formatFormat ? ':' + formatFormat : '') + '}'; } // Show the label value = snap ? point[this.isXAxis ? 'x' : 'y'] : this.toValue(horiz ? e.chartX : e.chartY); crossLabel.attr({ text: formatOption ? format(formatOption, { value: value }) : options.formatter.call(this, value), x: posx, y: posy, visibility: 'visible' }); crossBox = crossLabel.getBBox(); // now it is placed we can correct its position if (horiz) { if ((tickInside && !opposite) || (!tickInside && opposite)) { posy = crossLabel.y - crossBox.height; } } else { posy = crossLabel.y - (crossBox.height / 2); } // check the edges if (horiz) { limit = { left: left - crossBox.x, right: left + this.width - crossBox.x }; } else { limit = { left: this.labelAlign === 'left' ? left : 0, right: this.labelAlign === 'right' ? left + this.width : chart.chartWidth }; } // left edge if (crossLabel.translateX < limit.left) { offset = limit.left - crossLabel.translateX; } // right edge if (crossLabel.translateX + crossBox.width >= limit.right) { offset = -(crossLabel.translateX + crossBox.width - limit.right); } // show the crosslabel crossLabel.attr({ x: posx + offset, y: posy, // First set x and y, then anchorX and anchorY, when box is actually calculated, #5702 anchorX: horiz ? posx : (this.opposite ? 0 : chart.chartWidth), anchorY: horiz ? (this.opposite ? chart.chartHeight : 0) : posy + crossBox.height / 2 }); }); /* **************************************************************************** * Start value compare logic * *****************************************************************************/ var seriesInit = seriesProto.init, seriesProcessData = seriesProto.processData, pointTooltipFormatter = Point.prototype.tooltipFormatter; /** * Extend series.init by adding a method to modify the y value used for plotting * on the y axis. This method is called both from the axis when finding dataMin * and dataMax, and from the series.translate method. */ seriesProto.init = function () { // Call base method seriesInit.apply(this, arguments); // Set comparison mode this.setCompare(this.options.compare); }; /** * The setCompare method can be called also from the outside after render time */ seriesProto.setCompare = function (compare) { // Set or unset the modifyValue method this.modifyValue = (compare === 'value' || compare === 'percent') ? function (value, point) { var compareValue = this.compareValue; if (value !== UNDEFINED) { // #2601 // get the modified value value = compare === 'value' ? value - compareValue : // compare value value = 100 * (value / compareValue) - 100; // compare percent // record for tooltip etc. if (point) { point.change = value; } } return value; } : null; // Survive to export, #5485 this.userOptions.compare = compare; // Mark dirty if (this.chart.hasRendered) { this.isDirty = true; } }; /** * Extend series.processData by finding the first y value in the plot area, * used for comparing the following values */ seriesProto.processData = function () { var series = this, i, keyIndex = -1, processedXData, processedYData, length, compareValue; // call base method seriesProcessData.apply(this, arguments); if (series.xAxis && series.processedYData) { // not pies // local variables processedXData = series.processedXData; processedYData = series.processedYData; length = processedYData.length; // For series with more than one value (range, OHLC etc), compare against // close or the pointValKey (#4922, #3112) if (series.pointArrayMap) { // Use close if present (#3112) keyIndex = inArray('close', series.pointArrayMap); if (keyIndex === -1) { keyIndex = inArray(series.pointValKey || 'y', series.pointArrayMap); } } // find the first value for comparison for (i = 0; i < length - 1; i++) { compareValue = keyIndex > -1 ? processedYData[i][keyIndex] : processedYData[i]; if (isNumber(compareValue) && processedXData[i + 1] >= series.xAxis.min && compareValue !== 0) { series.compareValue = compareValue; break; } } } }; /** * Modify series extremes */ wrap(seriesProto, 'getExtremes', function (proceed) { var extremes; proceed.apply(this, [].slice.call(arguments, 1)); if (this.modifyValue) { extremes = [this.modifyValue(this.dataMin), this.modifyValue(this.dataMax)]; this.dataMin = arrayMin(extremes); this.dataMax = arrayMax(extremes); } }); /** * Add a utility method, setCompare, to the Y axis */ Axis.prototype.setCompare = function (compare, redraw) { if (!this.isXAxis) { each(this.series, function (series) { series.setCompare(compare); }); if (pick(redraw, true)) { this.chart.redraw(); } } }; /** * Extend the tooltip formatter by adding support for the point.change variable * as well as the changeDecimals option */ Point.prototype.tooltipFormatter = function (pointFormat) { var point = this; pointFormat = pointFormat.replace( '{point.change}', (point.change > 0 ? '+' : '') + Highcharts.numberFormat(point.change, pick(point.series.tooltipOptions.changeDecimals, 2)) ); return pointTooltipFormatter.apply(this, [pointFormat]); }; /* **************************************************************************** * End value compare logic * *****************************************************************************/ /** * Extend the Series prototype to create a separate series clip box. This is related * to using multiple panes, and a future pane logic should incorporate this feature (#2754). */ wrap(Series.prototype, 'render', function (proceed) { // Only do this on stock charts (#2939), and only if the series type handles clipping // in the animate method (#2975). if (this.chart.options._stock && this.xAxis) { // First render, initial clip box if (!this.clipBox && this.animate) { this.clipBox = merge(this.chart.clipBox); this.clipBox.width = this.xAxis.len; this.clipBox.height = this.yAxis.len; // On redrawing, resizing etc, update the clip rectangle } else if (this.chart[this.sharedClipKey]) { stop(this.chart[this.sharedClipKey]); // #2998 this.chart[this.sharedClipKey].attr({ width: this.xAxis.len, height: this.yAxis.len }); // #3111 } else if (this.clipBox) { this.clipBox.width = this.xAxis.len; this.clipBox.height = this.yAxis.len; } } proceed.call(this); }); // global variables extend(Highcharts, { // Constructors Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, correctFloat: correctFloat, dateFormat: dateFormat, error: error, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, map: map, merge: merge, splat: splat, stableSort: stableSort, extendClass: extendClass, pInt: pInt, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); return Highcharts; }));
ajax/libs/rxjs/2.3.9/rx.all.js
drewfreyling/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * 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; })(); 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 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)); (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; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return 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); } }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * 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); }; /** * 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) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; 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; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (!onError) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * * @example * var res = source.takeLast(5); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * 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)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }); }; /** * 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 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 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)); }); }; 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(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(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 a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * 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. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @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 = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @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 = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @example * 1 - res = source.contains(42); * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); * @param value The value to locate in the source sequence. * @param {Function} [comparer] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. */ observableProto.contains = function (value, comparer) { comparer || (comparer = defaultComparer); return this.where(function (v) { return comparer(v, value); }).any(); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * 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. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { if (count < len) { equal = comparer(value, second[count++]); } } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * 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); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal, v; if (ql.length > 0) { v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * 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. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate? this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue) }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * 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); }; function toSet(source, type) { return new AnonymousObservable(function (observer) { var s = new type(); return source.subscribe( s.add.bind(s), observer.onError.bind(observer), function () { observer.onNext(s); observer.onCompleted(); }); }); } if (!!root.Set) { /** * 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 () { return toSet(this, root.Set); }; } if (!!root.WeakSet) { /** * Converts the observable sequence to a WeakSet if it exists. * @returns {Observable} An observable sequence with a single value of a WeakSet containing the values from the observable sequence. */ observableProto.toWeakSet = function () { return toSet(this, root.WeakSet); }; } function toMap(source, type, keySelector, elementSelector) { return new AnonymousObservable(function (observer) { var m = new type(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { observer.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { observer.onError(e); return; } } m.set(key, element); }, observer.onError.bind(observer), function () { observer.onNext(m); observer.onCompleted(); }); }); } if (!!root.Map) { /** * 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) { return toMap(this, root.Map, keySelector, elementSelector); }; } if (!!root.WeakMap) { /** * Converts the observable sequence to a WeakMap if it exists. * @param {Function} keySelector A function which produces the key for the WeakMap * @param {Function} [elementSelector] An optional function which produces the element for the WeakMap. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a WeakMap containing the values from the observable sequence. */ observableProto.toWeakMap = function (keySelector, elementSelector) { return toMap(this, root.WeakMap, keySelector, elementSelector); }; } /** * 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. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var 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(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } 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)); /** * 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 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 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)); 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)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof obj === 'string') { return stringHashFn(valueOf); } } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new Error('out of range'); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { return this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch(exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.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, function () { return observableEmpty(); }, function (_, window) { return window; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var window = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); d.add(windowBoundaries.subscribe(function (w) { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var createWindowClose, m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), window = new Subject(); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); observer.onCompleted(); })); createWindowClose = function () { var m1, windowClose; try { windowClose = windowClosingSelector(); } catch (exception) { observer.onError(exception); return; } m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); createWindowClose(); })); }; createWindowClose(); return r; }); } /** * 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)); }); }; /** * 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) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector) { return enumerableFor(sources, resultSelector).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * 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 = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = (function () { /** * @constructor * @private */ function Map() { this.keys = []; this.values = []; } /** * @private * @memberOf Map# */ Map.prototype['delete'] = function (key) { var i = this.keys.indexOf(key); if (i !== -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } return i !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.get = function (key, fallback) { var i = this.keys.indexOf(key); return i !== -1 ? this.values[i] : fallback; }; /** * @private * @memberOf Map# */ Map.prototype.set = function (key, value) { var i = this.keys.indexOf(key); if (i !== -1) { this.values[i] = value; } this.values[this.keys.push(key) - 1] = value; }; /** * @private * @memberOf Map# */ Map.prototype.size = function () { return this.keys.length; }; /** * @private * @memberOf Map# */ Map.prototype.has = function (key) { return this.keys.indexOf(key) !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.getKeys = function () { return this.keys.slice(0); }; /** * @private * @memberOf Map# */ Map.prototype.getValues = function () { return this.values.slice(0); }; 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 object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { var patterns = this.patterns.slice(0); patterns.push(other); return new Pattern(patterns); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * * @param 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 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 (exception) { observer.onError(exception); 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; } // Active Plan function ActivePlan(joinObserverArray, onNext, onCompleted) { var i, joinObserver; this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (i = 0; i < this.joinObserverArray.length; i++) { joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { var values = this.joinObservers.getValues(); for (var i = 0, len = values.length; i < len; i++) { values[i].queue.shift(); } }; ActivePlan.prototype.match = function () { var firstValues, i, len, isCompleted, values, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { firstValues = []; isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); if (this.joinObserverArray[i].queue[0].kind === 'C') { isCompleted = true; } } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); values = []; for (i = 0; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; /** @private */ var JoinObserver = (function (_super) { inherits(JoinObserver, _super); /** * @constructor * @private */ 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; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.error = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.completed = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.removeActivePlan = function (activePlan) { var idx = this.activePlans.indexOf(activePlan); this.activePlans.splice(idx, 1); if (this.activePlans.length === 0) { this.dispose(); } }; /** * @memberOf JoinObserver# * @private */ 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 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 plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(), group, i, len, joinObserver, joinValues, outObserver; outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { var values = externalSubscriptions.getValues(); for (var j = 0, jlen = values.length; j < jlen; j++) { values[j].onError(exception); } observer.onError(exception); }, observer.onCompleted.bind(observer)); try { for (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); if (activePlans.length === 0) { outObserver.onCompleted(); } })); } } catch (e) { observableThrow(e).subscribe(observer); } group = new CompositeDisposable(); joinValues = externalSubscriptions.getValues(); for (i = 0, len = joinValues.length; i < len; i++) { joinObserver = joinValues[i]; joinObserver.subscribe(); group.add(joinObserver); } return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var 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); }) }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (typeof timeShiftOrScheduler === 'object') { 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); q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; 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; isSpan && (nextSpan += timeShift); isShift && (nextShift += timeShift); m.setDisposable(scheduler.scheduleWithRelative(ts, function () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); } }); }; /** * 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. * @example * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items * * @memberOf Observable# * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var createTimer, groupDisposable, n = 0, refCountDisposable, s = new Subject() timerD = new SerialDisposable(), windowId = 0; groupDisposable = new CompositeDisposable(timerD); refCountDisposable = new RefCountDisposable(groupDisposable); observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe(function (x) { var newId = 0, newWindow = false; s.onNext(x); n++; 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; function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { var newId; if (id !== windowId) { return; } n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * 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); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(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(); }); }); }; /** * 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; 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(), 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; 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))); }); }; /** * 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]); * 2 - res = source.skipUntilWithTime(5000, [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) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * 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]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } 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 Error(argumentOutOfRange); } 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 Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { 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 GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * 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/index.js
jmahc/that-react-app-you-want
import React from 'react' import ReactDOM from 'react-dom' import App from '@/containers/App' import '#/index.css' const renderApplication = (ApplicationComponent) => ReactDOM.render(<ApplicationComponent />, document.getElementById('⚛')) // Render the application. renderApplication(App)
node_modules/react-bootstrap/es/Grid.js
mohammed52/door-quote-automator
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 PropTypes from 'prop-types'; import elementType from 'prop-types-extra/lib/elementType'; import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * Turn any fixed-width grid layout into a full-width layout by this property. * * Adds `container-fluid` class. */ fluid: PropTypes.bool, /** * You can use a custom element for this component */ componentClass: elementType }; var defaultProps = { componentClass: 'div', fluid: false }; var Grid = function (_React$Component) { _inherits(Grid, _React$Component); function Grid() { _classCallCheck(this, Grid); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Grid.prototype.render = function render() { var _props = this.props, fluid = _props.fluid, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['fluid', 'componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = prefix(bsProps, fluid && 'fluid'); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Grid; }(React.Component); Grid.propTypes = propTypes; Grid.defaultProps = defaultProps; export default bsClass('container', Grid);
packages/wix-style-react/src/TagList/TagListAction/TagListAction.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import Button from '../../Button'; import { st, classes } from '../TagList.st.css'; const TagListAction = ({ className, ...rest }) => ( <Button className={st(classes.item, className)} {...rest} /> ); TagListAction.displayName = 'TagListAction'; TagListAction.propTypes = { dataHook: PropTypes.string, children: PropTypes.node, onClick: PropTypes.func, }; TagListAction.defaultProps = { size: 'tiny', skin: 'inverted', }; export default TagListAction;